text
stringlengths
2
1.04M
meta
dict
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package rms.models.management; import rms.models.DBTable; /** * * @author squeekyclean */ public class BranchDBTable extends DBTable{ public static final String TABLE_NAME = "branches"; public static final String ID = "id"; public static final String NAME = "name"; public static final String ADDRESS = "address"; public static final String STATUS = "status"; public static final String ALIAS_ID = "ID"; public static final String ALIAS_NAME = "Branch"; public static final String ALIAS_ADDRESS = "Address"; public static final String ALIAS_STATUS = "Status"; private static final String[] columns = {NAME, ID, ADDRESS, STATUS}; private static final String[] columnsAliases = {ALIAS_NAME, ALIAS_ID, ALIAS_ADDRESS, ALIAS_STATUS}; private static final String[] primaryColumns = {ID}; private static final String[] uniqueColumns = {ID}; private static final String[] invisibleColumns = {ALIAS_ID, ALIAS_STATUS}; private static final String[] uneditableColumns = {ID, STATUS}; private static final String[] nonNullableColumns = {NAME, STATUS}; private static BranchDBTable INSTANCE; private BranchDBTable(){} public static BranchDBTable getInstance(){ if(INSTANCE == null) INSTANCE = new BranchDBTable(); return INSTANCE; } @Override public String getTableName() { return TABLE_NAME; } @Override public String[] getColumns() { return columns; } @Override public String[] getPrimaryColumns() { return primaryColumns; } @Override public String[] getUniqueColumns() { return uniqueColumns; } @Override public String[] getColumnsDefaultAliases() { return columnsAliases; } @Override public String[] getInvisibleColumns() { return invisibleColumns; } @Override public String[] getNonNullableColumns() { return nonNullableColumns; } @Override public String[] getUneditableColumns() { return uneditableColumns; } }
{ "content_hash": "455ed603b2103f0729adec511e4a8782", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 103, "avg_line_length": 26.776470588235295, "alnum_prop": 0.6401581722319859, "repo_name": "greenlover1991/rms", "id": "6f8a072955d432c12f1d25bd7e29b43b5f9ba810", "size": "2276", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/rms/models/management/BranchDBTable.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "633522" } ], "symlink_target": "" }
set -e # Install gflags development files if not already present. [ -d /usr/include/gflags/ ] || sudo apt -y install libgflags-dev # For travis: libomp.so is not found otherwise. export LD_LIBRARY_PATH=/usr/local/clang/lib:$LD_LIBRARY_PATH cd "$(readlink -f "$(dirname "$0")")" echo "Compiling..." ./compile.sh echo "Computing exact truss decomposition" ./truss_decomposition_parallel < clique10.nde echo "Computing approximate truss decomposition" ./td_approx_external < clique10.nde echo "Computing approximate truss decomposition and switching to exact algorithm" ./td_approx_external --edge_limit 10000 --exact_exe ./truss_decomposition_parallel < clique10.nde
{ "content_hash": "efdef649cc0cf048b21513490e657586", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 97, "avg_line_length": 27.04, "alnum_prop": 0.7514792899408284, "repo_name": "google-research/google-research", "id": "536255e8b026696ec6965db9f19bd8d419d92689", "size": "1282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "truss_decomposition/run.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "9817" }, { "name": "C++", "bytes": "4166670" }, { "name": "CMake", "bytes": "6412" }, { "name": "CSS", "bytes": "27092" }, { "name": "Cuda", "bytes": "1431" }, { "name": "Dockerfile", "bytes": "7145" }, { "name": "Gnuplot", "bytes": "11125" }, { "name": "HTML", "bytes": "77599" }, { "name": "ImageJ Macro", "bytes": "50488" }, { "name": "Java", "bytes": "487585" }, { "name": "JavaScript", "bytes": "896512" }, { "name": "Julia", "bytes": "67986" }, { "name": "Jupyter Notebook", "bytes": "71290299" }, { "name": "Lua", "bytes": "29905" }, { "name": "MATLAB", "bytes": "103813" }, { "name": "Makefile", "bytes": "5636" }, { "name": "NASL", "bytes": "63883" }, { "name": "Perl", "bytes": "8590" }, { "name": "Python", "bytes": "53790200" }, { "name": "R", "bytes": "101058" }, { "name": "Roff", "bytes": "1208" }, { "name": "Rust", "bytes": "2389" }, { "name": "Shell", "bytes": "730444" }, { "name": "Smarty", "bytes": "5966" }, { "name": "Starlark", "bytes": "245038" } ], "symlink_target": "" }
ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
{ "content_hash": "2941d4533410d06bcfc3769b51f422af", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 23, "avg_line_length": 9.076923076923077, "alnum_prop": 0.6779661016949152, "repo_name": "mdoering/backbone", "id": "49837dca45a310bcfc2e2d0404cbaa512563162d", "size": "181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Chlorophyta/Zygnematophyceae/Zygnematales/Desmidiaceae/Staurodesmus/Staurodesmus mamillatus/Staurodesmus mamillatus mamillatus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.king.applib.util; import android.content.Context; import android.graphics.Color; import androidx.annotation.ColorRes; import androidx.annotation.DimenRes; import androidx.core.content.ContextCompat; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextPaint; import android.text.TextUtils; import android.text.style.AbsoluteSizeSpan; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.text.style.StrikethroughSpan; import android.text.style.StyleSpan; import android.view.View; import android.widget.TextView; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 字符串工具类。 * * @author VanceKing * @since 2016/9/29 */ public final class StringUtil { private StringUtil() { throw new UnsupportedOperationException("No instances!"); } /** * 判断字符串是否是null或者empty(""," ") */ public static boolean isNullOrEmpty(final String string) { return string == null || string.trim().isEmpty(); } /** * 字符串为null或empty(""," ")返回false,否则返回true. */ public static boolean isNotNullOrEmpty(final String string) { return !isNullOrEmpty(string); } /** * 判断字符串是否 not null或者not empty(""," ") */ public static boolean isNotEmpty(final String string) { return !isNullOrEmpty(string); } /** * 如果可变字符串中包含null或empty,返回true;否则返回false. */ public static boolean isAnyEmpty(final String... strings) { if (strings == null || strings.length < 1) { return true; } for (String str : strings) { if (isNullOrEmpty(str)) { return true; } } return false; } /** * 字符串都不为null或""返回true,否则返回false. */ public static boolean isNoneEmpty(final String... strings) { return !isAnyEmpty(strings); } /** * 判断是否所有字符串都为空(null/empty) */ public static boolean isAllEmpty(final String... strings) { if (strings == null || strings.length <= 0) { return true; } for (String str : strings) { if (isNotNullOrEmpty(str)) { return false; } } return true; } /** 如果 text == null ,返回空字符串 */ public static String getStringExceptNull(String text) { return text != null ? text : ""; } /** 如果 text == null ,返回默认字符串 */ public static String getStringExceptNull(String text, String defaultText) { return text != null ? text : defaultText; } /** * 设置字符串中指定字符的样式。<br/> * 当keyword 为"\"时,Pattern.compile会报 PatternSyntaxException。 * * @param context 上下文 * @param text 字符串 * @param keyword 关键字 * @param colorId 指定字体的颜色.-1不设置颜色 * @param sizeId 指定字体的大小.-1不设置字体大小 * @return 特殊的字符串 */ public static SpannableStringBuilder buildSingleTextStyle(Context context, String text, String keyword, @ColorRes int colorId, @DimenRes int sizeId) { if (context == null || StringUtil.isNullOrEmpty(text)) { return SpannableStringBuilder.valueOf(""); } SpannableStringBuilder style = SpannableStringBuilder.valueOf(text); if (StringUtil.isNullOrEmpty(keyword)) { return style; } Pattern p = PatternUtil.convertPattern(keyword); if (p == null) { return style; } Matcher matcher = p.matcher(text); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); if (colorId != -1) { style.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorId)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } if (sizeId != -1) { style.setSpan(new AbsoluteSizeSpan((int) context.getResources().getDimension(sizeId)), start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); } } return style; } /** * 设置字符串中指定字符的样式 * * @param context 上下文 * @param text 字符串 * @param start 关键字开始位置 * @param end 关键字结束位置 * @param colorId 关键字的颜色.-1不设置颜色 * @param sizeId 关键字的大小.-1不设置字体大小 */ public static SpannableStringBuilder buildSingleTextStyle(Context context, String text, int start, int end, @ColorRes int colorId, @DimenRes int sizeId) { if (context == null || StringUtil.isNullOrEmpty(text)) { return SpannableStringBuilder.valueOf(""); } SpannableStringBuilder style = new SpannableStringBuilder(text); if (colorId != -1) { style.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorId)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } if (sizeId != -1) { style.setSpan(new AbsoluteSizeSpan((int) context.getResources().getDimension(sizeId)), start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); } return style; } /** * 设置字符串中指定多个字符的样式 * * @param context 上下文 * @param text 字符串 * @param keywordArray 关键字数组。要一一对应。 * @param colorResArray 颜色值资源数组。要一一对应。-1不设置颜色 * @param sizeResArray 字符大小资源数组。要一一对应。-1不设置大小 * @return 特殊的字符串 */ public static SpannableStringBuilder buildMulTextStyle(Context context, String text, String[] keywordArray, int[] colorResArray, int[] sizeResArray) { if (context == null || StringUtil.isNullOrEmpty(text)) { return SpannableStringBuilder.valueOf(""); } SpannableStringBuilder spannableBuilder = SpannableStringBuilder.valueOf(text); if (ExtendUtil.isArrayNullOrEmpty(keywordArray)) { return spannableBuilder; } for (int i = 0; i < keywordArray.length; i++) { Pattern p = PatternUtil.convertPattern(keywordArray[i]); if (p == null) { continue; } final Matcher matcher = p.matcher(text); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); if (colorResArray[i] != -1) { spannableBuilder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorResArray[i])), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } if (sizeResArray[i] != -1) { spannableBuilder.setSpan(new AbsoluteSizeSpan((int) context.getResources().getDimension(sizeResArray[i]), false), start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE); } } } return spannableBuilder; } /** * 创建一个Spannable对象 */ public static Spannable createSpannable(String string) { return new SpannableString(string); } /** * FOR: textview.setText(WordtoSpan) * Textview文字设置俩种不同颜色 * * @param tag 从哪个索引开始分割 */ private static Spannable setTextColor(Context context, String string, int tag, int colorFirstId, int colorSecondId) { Spannable wordtoSpan = createSpannable(string); wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorFirstId)), 0, tag, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, colorSecondId)), tag, string.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return wordtoSpan; } /** * 设置字符串中部分串的字体颜色 */ public static void setTextColor(Spannable sp, int color, int start, int end) { if (sp != null) { sp.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } /** * 设置字符串中部分串的字体大小 */ public static void setTextSize(Spannable sp, int textSize, int start, int end) { if (sp != null) { //设置字体大小,第二个参数boolean dip,如果为true,表示前面的字体大小单位为dip,否则为像素, sp.setSpan(new AbsoluteSizeSpan(textSize, true), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } /** * 设置不同的样式 */ public static void setTextStyle(Spannable sp, int textStyle, int start, int end) { if (sp != null) { sp.setSpan(new StyleSpan(textStyle), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } /** * FOR: * SpannableString spStr = new SpannableString(str); * SpannableUtils.setTextClickable(tv_1, spStr, start, end); * tv_1.setText(spStr); * 设置字符串的可点击部分 */ public static void setTextClickable(TextView textView, Spannable sp, int start, int end) { if (sp != null) { sp.setSpan(new ClickableSpan() { @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setColor(Color.BLUE); //设置文件颜色 ds.setUnderlineText(true); //设置下划线 } @Override public void onClick(View widget) { // do somthing... } }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setHighlightColor(Color.TRANSPARENT); //设置点击后的颜色为透明,否则会一直出现高亮 //textView.setMovementMethod(LinkMovementMethod.getInstance());//开始响应点击事件 } } /** * 设置中划线 */ public static void setTextMiddleLine(Spannable sp, int start, int end) { if (sp != null) { StrikethroughSpan stSpan = new StrikethroughSpan(); //设置删除线样式 sp.setSpan(stSpan, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } } /** 去掉字符串中的空格。包括回车、换行和制表符。 */ public static String trimAllSpace(String text) { if (text == null) { return ""; } final String temp = text.trim(); return temp.isEmpty() ? "" : temp.replaceAll("\\s*", ""); } /** 把字符串中的空格、回车、换行和制表符替换成指定字符 */ public static String replaceAllSpace(String text, String replacement) { if (isNullOrEmpty(text)) { return ""; } if (isNullOrEmpty(replacement)) { return text; } //注意:不是 "\s*" return text.replaceAll("\\s+", replacement); } /** * 联结多个非 null 字符串。 * * @param exceptEmpty 是否排除""字符串 */ public static String concat(boolean exceptEmpty, String... texts) { if (texts == null || texts.length <= 0) { return ""; } final StringBuilder sb = new StringBuilder(); for (String text : texts) { if (text == null) { continue; } if (exceptEmpty) { if (!TextUtils.isEmpty(text.trim())) { sb.append(text); } } else { sb.append(text); } } return sb.toString(); } }
{ "content_hash": "491c3caf38eebc68450f1bd1f199a80f", "timestamp": "", "source": "github", "line_count": 334, "max_line_length": 180, "avg_line_length": 32.91317365269461, "alnum_prop": 0.5914672973710543, "repo_name": "hubme/WorkHelperApp", "id": "0a3c6fb80f1faa14cd5bdb8622bdb73476ae115a", "size": "12031", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "applib/src/main/java/com/king/applib/util/StringUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "885" }, { "name": "HTML", "bytes": "9487" }, { "name": "Java", "bytes": "2270526" }, { "name": "JavaScript", "bytes": "3836" }, { "name": "Kotlin", "bytes": "110244" } ], "symlink_target": "" }
VERSION_MAJOR = 0 VERSION_MINOR = 8 VERSION_BUILD = 1 VERSION_INFO = (VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD) VERSION_STRING = "%d.%d.%d" % VERSION_INFO __version__ = VERSION_INFO
{ "content_hash": "bbb013654dfb6125c36d3d6ccc1f7283", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 60, "avg_line_length": 26.571428571428573, "alnum_prop": 0.7043010752688172, "repo_name": "Jumpscale/web", "id": "2b6f9eaea56c598ef566b42f1d37d5126f65b809", "size": "974", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pythonlib/watchdog/version.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5939" }, { "name": "CSS", "bytes": "322110" }, { "name": "JavaScript", "bytes": "2076089" }, { "name": "Python", "bytes": "8937633" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>equations: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1 / equations - 1.2.4+8.11</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> equations <small> 1.2.4+8.11 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-16 17:46:15 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-16 17:46:15 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.7.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; authors: [ &quot;Matthieu Sozeau &lt;matthieu.sozeau@inria.fr&gt;&quot; &quot;Cyprien Mangin &lt;cyprien.mangin@m4x.org&gt;&quot; ] dev-repo: &quot;git+https://github.com/mattam82/Coq-Equations.git#8.11&quot; maintainer: &quot;matthieu.sozeau@inria.fr&quot; homepage: &quot;https://mattam82.github.io/Coq-Equations&quot; bug-reports: &quot;https://github.com/mattam82/Coq-Equations/issues&quot; license: &quot;LGPL-2.1-only&quot; synopsis: &quot;A function definition package for Coq&quot; description: &quot;&quot;&quot; Equations is a function definition plugin for Coq, that allows the definition of functions by dependent pattern-matching and well-founded, mutual or nested structural recursion and compiles them into core terms. It automatically derives the clauses equations, the graph of the function and its associated elimination principle. &quot;&quot;&quot; tags: [ &quot;keyword:dependent pattern-matching&quot; &quot;keyword:functional elimination&quot; &quot;category:Miscellaneous/Coq Extensions&quot; &quot;logpath:Equations&quot; ] build: [ [&quot;./configure.sh&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] run-test: [ [make &quot;test-suite&quot;] ] depends: [ &quot;coq&quot; {&gt;= &quot;8.11.0&quot; &amp; &lt; &quot;8.12~&quot;} &quot;ocamlfind&quot; {build} ] url { src: &quot;https://github.com/mattam82/Coq-Equations/archive/v1.2.4-8.11.tar.gz&quot; checksum: &quot;sha512=af724f146d899a45be7b4863566adc31f88ba9b64ce934cff0be2fd81b04acc09ff9bc66dd9b97b3eae775473af6592cb58b30b9666d9b537d64e2a37185e15a&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-equations.1.2.4+8.11 coq.8.7.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1). The following dependencies couldn&#39;t be met: - coq-equations -&gt; coq &gt;= 8.11.0 -&gt; ocaml &gt;= 4.09.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-equations.1.2.4+8.11</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "5d911a948b06408e927a55e97d3c0bb7", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 159, "avg_line_length": 40.73076923076923, "alnum_prop": 0.5591528396060974, "repo_name": "coq-bench/coq-bench.github.io", "id": "61eb1e8674be8278c4e0a1c2dc30c17ae7dfeec4", "size": "7438", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.7.1/equations/1.2.4+8.11.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#include "../sae.h" #include "strangeattractors.h" #include "cohandle.h" #include "system/file.h" #include "math/intersections.h" #include "math/splines.h" #include "core/sort.h" void SAUtils::IterateStrangeAttractorPoint(StrangeAttractor& attractor, AttractorSeedParams const& seed_params, AttractorLineParams const& params, int32 iter_count, vec3& out_pos) { out_pos = seed_params.seed; attractor.m_init_point = seed_params.seed; Array<vec3> line_points; attractor.LoopAdaptative(line_points, bigball::abs(iter_count), params.step_factor, iter_count < 0 ? true : false/*reverse*/); if (line_points.size() > 0) out_pos = line_points.Last(); } void SAUtils::ComputeStrangeAttractorPoints(StrangeAttractor& attractor, AttractorSeedParams const& seed_params, AttractorLineParams const& params, Array<vec3>& line_points) { vec3 seed = seed_params.seed; attractor.m_init_point = seed; /*if (params.warmup_iter > 0) { attractor.LoopAdaptative(line_points, params.warmup_iter); seed = line_points.Last(); attractor.m_init_point = line_points.Last(); line_points.clear(); }*/ if (seed_params.rev_iter > 0) { attractor.LoopAdaptative(line_points, seed_params.rev_iter, params.step_factor, true/*reverse*/); const int32 nb_point = line_points.size(); for (int32 i = 0; i < nb_point / 2; i++) line_points.Swap(i, nb_point - 1 - i); line_points.push_back(seed); } attractor.LoopAdaptative(line_points, seed_params.iter, params.step_factor, false/*reverse*/); if (params.shearing_scale_x != 1.f || params.shearing_scale_y != 1.f || params.shearing_angle != 0.f) { const float cf = bigball::cos(params.shearing_angle); const float sf = bigball::sin(params.shearing_angle); for (int32 i = 0; i < line_points.size(); ++i) { vec3 p = line_points[i]; float rot_x = params.shearing_scale_x * (p.x * cf - p.y * sf); float rot_y = params.shearing_scale_y * (p.x * sf + p.y * cf); line_points[i].x = rot_x * cf + rot_y * sf; line_points[i].y = rot_x * -sf + rot_y * cf; } } } static float SquaredDistancePointSegment_Unclamped(vec3 const& point, vec3 const& seg0, vec3 const& seg1, float& t_on_segment_unclamped) { vec3 V_seg0 = point - seg0; vec3 dir_seg = seg1 - seg0; float t_unclamped = dot(dir_seg, V_seg0); float dot_dd = dot(dir_seg, dir_seg); t_unclamped /= dot_dd; float t = bigball::clamp(t_unclamped, 0.f, 1.f); V_seg0 += dir_seg*(-t); t_on_segment_unclamped = t_unclamped; return dot(V_seg0, V_seg0); } static void PrintBary(SABarycenterRef const* bary, int32 bary_idx, float dist) { String str_debug; str_debug = String::Printf("bary [%d][%.2f]", bary_idx, dist); for( int32 s_idx = 0; s_idx < bary->seg_refs.size(); s_idx++) { int32 seg_ref = bary->seg_refs[s_idx]; str_debug += String::Printf(" %d", seg_ref); } str_debug += "\n"; BB_LOG(SAUtils, Log, str_debug.c_str()); } void SAUtils::MergeCurves(Array<AttractorOrientedCurve>& curves, AttractorShapeParams const& shape_params, const Array<AttractorHandle>& attr_handles) { const float merge_dist = shape_params.merge_dist; const float sq_merge_dist = merge_dist * merge_dist; int32 num_curve = curves.size(); for (int32 c_idx = 0; c_idx < num_curve; c_idx++) { AttractorOrientedCurve& curve = curves[c_idx]; AttractorHandle const& handle = attr_handles[c_idx]; const int32 interp_spacing = (handle.m_seed.merge_span > 0 ? handle.m_seed.merge_span : shape_params.merge_span); if(curve.points.size() <= interp_spacing*2 + 2) continue; vec3 p_0 = curve.points[0]; vec3 p_1 = curve.points.Last(); AttractorCurveSnap snap_start, snap_end; snap_start.sq_dist = sq_merge_dist; snap_end.sq_dist = sq_merge_dist; for (int32 c_idx_2 = 0; c_idx_2 < num_curve; c_idx_2++) { AttractorOrientedCurve& curve_2 = curves[c_idx_2]; if(curve_2.points.size() <= interp_spacing*2 + 2) continue; int32 nb_point = curve_2.points.size(); ivec2 seg_range = (c_idx == c_idx_2 ? ivec2(interp_spacing, nb_point - interp_spacing - 1) : ivec2(0, nb_point - 1) ); FindNearestCurveSegment(curve_2, seg_range, p_0, p_1, sq_merge_dist, snap_start, snap_end ); } const bool blend_positions = true; GenerateSnappedCurve(curve, snap_start, snap_end, shape_params, blend_positions); } } void SAUtils::FindNearestCurveSegment(AttractorOrientedCurve const& curve, ivec2 seg_range, vec3 p_0, vec3 p_1, float sq_merge_dist, AttractorCurveSnap& min_0, AttractorCurveSnap& min_1) { for (int32 p_idx = seg_range.x; p_idx < seg_range.y; p_idx++) { vec3 cp_0 = curve.points[p_idx]; vec3 cp_1 = curve.points[p_idx + 1]; float sq_dist = sqlength(cp_0 - p_0); if (sq_dist < sq_merge_dist) { float t; sq_dist = intersect::SquaredDistancePointSegment(p_0, cp_0, cp_1, t); if (sq_dist < min_0.sq_dist) { min_0.sq_dist = sq_dist; min_0.seg = p_idx; min_0.curve = &curve; } } sq_dist = sqlength(cp_0 - p_1); if (sq_dist < sq_merge_dist) { float t; sq_dist = intersect::SquaredDistancePointSegment(p_1, cp_0, cp_1, t); if (sq_dist < min_1.sq_dist) { min_1.sq_dist = sq_dist; min_1.seg = p_idx; min_1.curve = &curve; } } } } void SAUtils::MergeLinePoints5(AttractorOrientedCurve const& line_framed, const Array<AttractorHandle>& attr_handles, AttractorShapeParams const& shape_params, Array<AttractorOrientedCurve>& snapped_lines) { BB_LOG(SAUtils, Log, "MergeLinePoints5\n"); Array<AttractorSnapRange> snap_ranges; const int32 interp_spacing = shape_params.merge_span; const bool blend_position = true; const Array<vec3>& line_points = line_framed.points; const int32 nb_points = line_points.size(); if(nb_points > interp_spacing*2 + 2) { vec3 p_0 = line_points[0]; vec3 p_1 = line_points.Last(); const float merge_dist = shape_params.merge_dist; const float sq_merge_dist = merge_dist * merge_dist; float t, sq_dist, min_sq_dist_0 = sq_merge_dist, min_sq_dist_1 = sq_merge_dist; int32 min_seg_0 = INDEX_NONE, min_seg_1 = INDEX_NONE; for (int32 p_idx = interp_spacing; p_idx < nb_points - interp_spacing - 1; p_idx++) { sq_dist = intersect::SquaredDistancePointSegment(p_0, line_points[p_idx], line_points[p_idx + 1], t); if (sq_dist < min_sq_dist_0) { min_sq_dist_0 = sq_dist; min_seg_0 = p_idx; } sq_dist = intersect::SquaredDistancePointSegment(p_1, line_points[p_idx], line_points[p_idx + 1], t); if (sq_dist < min_sq_dist_1) { min_sq_dist_1 = sq_dist; min_seg_1 = p_idx; } } if( min_seg_0 != INDEX_NONE) { AttractorSnapRange sr_0 = { ivec2(0,0), ivec2(min_seg_0, min_seg_0) }; snap_ranges.push_back(sr_0); } if( min_seg_1 != INDEX_NONE) { AttractorSnapRange sr_1 = { ivec2(nb_points-1,nb_points-1), ivec2(min_seg_1, min_seg_1) }; snap_ranges.push_back(sr_1); } } GenerateSnappedLinesWithFrames(line_framed.points, line_framed.frames, line_framed.follow_angles, snap_ranges, shape_params, snapped_lines, blend_position); } void SAUtils::MergeLinePoints4(AttractorOrientedCurve const& line_framed, const Array<AttractorHandle>& attr_handles, AttractorShapeParams const& shape_params, Array<AttractorOrientedCurve>& snapped_lines) { BB_LOG(SAUtils, Log, "MergeLinePoints4\n"); // New algo (force based) Array<vec3> line_points = line_framed.points; float avg_pt_separation = 0.f; { int max_pt = max(100, line_points.size() - 1); for (int i = 0; i < max_pt; i++) { float d = distance(line_points[i], line_points[i + 1]); avg_pt_separation += d; } avg_pt_separation /= (float)max_pt; } // 1- sort every line point into a grid SAGrid grid; grid.InitGrid(line_framed.points, 1000); // 2- parse every point and find out if it has neighbours <= merge_dist range // move_factor : mark 0.0 if no neighbours, 1.0 otherwise Array<float> move_factors; const int nb_points = line_points.size(); move_factors.resize(nb_points, 0.f); const int interp_range = 40; if(!shape_params.show_bary) { const int max_pass = shape_params.max_iter_count; for(int pass_idx = 0; pass_idx < max_pass; pass_idx++) { bool first_pass = (pass_idx == 0 ? true : false); for (int pt_idx = 0; pt_idx < nb_points; pt_idx++) { if(!first_pass && move_factors[pt_idx] < 1.0f) continue; SASegResult found_seg = grid.FindNearestSeg(pt_idx, line_points, shape_params.merge_dist, interp_range); if (found_seg.cell_id != INDEX_NONE) { SACell const& seg_cell = grid.cells[found_seg.cell_id]; int seg_idx = seg_cell.segs[found_seg.seg_in_array_idx]; vec3 seg_0 = line_points[seg_idx]; vec3 seg_1 = line_points[seg_idx + 1]; float dist = bigball::sqrt(found_seg.sq_dist); if( dist < 1e-4f ) continue; vec3 seg_p = seg_0 * (1.f - found_seg.t_seg) + seg_1 * found_seg.t_seg; vec3 p_0 = line_points[pt_idx]; vec3 dir_seg = (seg_p - p_0) / dist; float push_dist = min( dist, avg_pt_separation ); vec3 new_pos = p_0 + dir_seg * push_dist; line_points[pt_idx] = new_pos; grid.MovePoint(p_0, new_pos, pt_idx); move_factors[pt_idx] = 1.0f; } } // 3- interpolate and propagate move_factor 1.0 1.0 0.9 0.8 0.7 0.6 0.5 0.4 0.5 0.6 0.7 0.8 0.9 1.0 if (first_pass) { int last_idx = INDEX_NONE; for (int pt_idx = 0; pt_idx < nb_points; pt_idx++) { if(move_factors[pt_idx] == 1.f) last_idx = pt_idx; else { if(pt_idx - last_idx < interp_range) move_factors[pt_idx] = 1.f - (pt_idx - last_idx) / interp_range; } } last_idx = INDEX_NONE; for (int pt_idx = nb_points - 1; pt_idx >= 0 ; pt_idx--) { if(move_factors[pt_idx] == 1.f) last_idx = pt_idx; else { if(last_idx - pt_idx < interp_range) move_factors[pt_idx] = max(move_factors[pt_idx], 1.f - (last_idx - pt_idx) / interp_range); } } } // relaxation step: move midway from immediate neighbors (-1 +1), curve fitting from (-2 +2) CubicSpline spline; for (int pt_idx = 6; pt_idx < nb_points - 6; pt_idx++) { if(move_factors[pt_idx] < 1.f) continue; vec3 p_0 = line_points[pt_idx - 6]; vec3 p_1 = line_points[pt_idx - 3]; vec3 p_2 = line_points[pt_idx + 3]; vec3 p_3 = line_points[pt_idx + 6]; float dt_0 = bigball::pow(bigball::sqlength(p_0 - p_1), 0.25f); float dt_1 = bigball::pow(bigball::sqlength(p_1 - p_2), 0.25f); float dt_2 = bigball::pow(bigball::sqlength(p_2 - p_3), 0.25f); // safety check for repeated points if (dt_1 < 1e-4f) dt_1 = 1.0f; if (dt_0 < 1e-4f) dt_0 = dt_1; if (dt_2 < 1e-4f) dt_2 = dt_1; spline.InitNonuniformCatmullRom(p_0, p_1, p_2, p_3, dt_0, dt_1, dt_2); vec3 s_pos, s_tan; spline.Eval(0.5f, s_pos, s_tan); // move halfway toward spline pos line_points[pt_idx] = (s_pos + line_points[pt_idx]) * 0.5f; } } } AttractorOrientedCurve new_framed; snapped_lines.push_back(new_framed); AttractorOrientedCurve& ref_framed = snapped_lines.Last(); ref_framed.points = line_points; ref_framed.colors.resize(nb_points, 0.f); GenerateFrames(ref_framed); } void SAUtils::MergeLinePoints3(AttractorOrientedCurve const& line_framed, const Array<AttractorHandle>& attr_handles, AttractorShapeParams const& shape_params, Array<AttractorOrientedCurve>& snapped_lines) { BB_LOG(SAUtils, Log, "MergeLinePoints3\n"); // New algo with barycenters SAGrid grid; // 1- sort every line segment into a grid grid.InitGrid(line_framed.points, 1000); // 2- Parse segment in order, find a barycenter seg nearby <= merge_dist const Array<vec3>& line_points = line_framed.points; const int nb_points = line_points.size(); for (int seg_idx = 0; seg_idx < nb_points - 1; seg_idx++) { //if( seg_idx == 261 || seg_idx == 262 || seg_idx == 523 || seg_idx == 524 || seg_idx == 634 || seg_idx == 635 ) // int Break=0; vec3 p_0 = line_points[seg_idx]; vec3 p_1 = line_points[seg_idx + 1]; int cell_id = grid.GetCellIdx(p_0); SABaryResult found_bary = grid.FindBaryCenterSeg(seg_idx, p_0, /*line_points[seg_idx + 1],*/ shape_params.merge_dist); // if it exists, point to it (seg_bary_array) and update barycenter point info with weighted average(pos + w) if (found_bary.bary_in_array_idx != INDEX_NONE) { SACell const& bary_cell = grid.cells[found_bary.cell_id]; int bary_idx = bary_cell.barys[found_bary.bary_in_array_idx]; grid.seg_bary_array[seg_idx] = bary_idx; SABarycenterRef& bary_0 = grid.bary_points[bary_idx]; SABarycenterRef& bary_1 = grid.bary_points[bary_idx + 1]; // project back bary_0 pos onto segment float t_seg; float sq_dist = SquaredDistancePointSegment_Unclamped(bary_0.pos, p_0, p_1, t_seg); vec3 v_seg = p_0 * (1.f - t_seg) + p_1 * t_seg; vec3 vec = v_seg - bary_0.pos; // moving average bool move_bary = true; for( int32 s_idx = 0; s_idx < bary_0.seg_refs.size(); s_idx++) { int32 seg_ref = bary_0.seg_refs[s_idx]; if( seg_ref >= seg_idx - 5 && seg_ref <= seg_idx + 5 ) { move_bary = false; break; } } if (!move_bary) { bary_0.seg_refs.push_back(seg_idx); continue; } bary_0.pos = bary_0.pos + vec / (float)(bary_0.weight + 1); bary_0.weight++; bary_0.seg_refs.push_back(seg_idx); grid.MoveBary(found_bary, bary_0.pos, bary_idx); //TODO: backtrack to see if seg-1 / seg-2 is not snapped on same bary line, but seg-2 / seg-3 is, in which case we force contuinity of snapping if( bary_idx > 1) { //int32 p_b_m1 = grid.seg_bary_array[seg_idx - 1]; //int32 p_b_m2 = grid.seg_bary_array[seg_idx - 2]; int32 seg_idx_m2; if( INDEX_NONE == grid.FindSegInRange(bary_idx - 1, seg_idx - 1, 2) && INDEX_NONE != (seg_idx_m2 = grid.FindSegInRange(bary_idx - 2 , seg_idx - 2, 2))) { int seg_mid = (seg_idx_m2 + seg_idx) / 2; SABarycenterRef& bary_m1 = grid.bary_points[bary_idx - 1]; vec3 p_m0 = line_points[seg_mid]; vec3 p_m1 = line_points[seg_mid + 1]; // project back bary_m1 pos onto segment float t_seg_m1; SquaredDistancePointSegment_Unclamped(bary_m1.pos, p_m0, p_m1, t_seg_m1); vec3 v_seg_m = p_m0 * (1.f - t_seg_m1) + p_m1 * t_seg_m1; vec3 vec_m = v_seg_m - bary_m1.pos; vec3 prev_bary_m1_pos = bary_m1.pos; bary_m1.pos = bary_m1.pos + vec / (float)(bary_m1.weight + 1); bary_m1.weight++; bary_m1.seg_refs.push_back(seg_mid); grid.MoveBary(prev_bary_m1_pos, bary_m1.pos, bary_idx - 1); } } //grid.MoveBary(found_bary, bary_0.pos, bary_idx); if (bary_1.is_last_in_chain) { // move next bary too if end of chain vec3 prev_bary_1_pos = bary_1.pos; bary_1.pos = bary_1.pos + vec / (float)(bary_1.weight + 1); bary_1.weight++; //bary_1.seg_refs.push_back(seg_idx); grid.MoveBary(prev_bary_1_pos, bary_1.pos, bary_idx + 1); } } // otherwise, create a new barycenter point / seg with current seg info (first_leading_seg = me, bary pos = seg pos, w = 1) else { SABarycenterRef* prev_bary = nullptr; int nb_bary = grid.bary_points.size(); if (nb_bary) { prev_bary = &grid.bary_points.Last(); } if (prev_bary && prev_bary->pos == p_0) { // continuing previous chain prev_bary->is_last_in_chain = 0; prev_bary->seg_refs.push_back(seg_idx); grid.seg_bary_array[seg_idx] = nb_bary - 1; SABarycenterRef new_bary_1 = { seg_idx + 1, p_1, 1 /*weight*/, 1 /*is_last_in_chain*/ }; grid.bary_points.push_back(new_bary_1); int new_cell_id = grid.GetCellIdx(p_1); grid.cells[new_cell_id].barys.push_back(nb_bary); } else { // start new chain SABarycenterRef new_bary_0 = { seg_idx, p_0, 1 /*weight*/, 0 /*is_last_in_chain*/ }; new_bary_0.seg_refs.push_back(seg_idx); grid.bary_points.push_back(new_bary_0); grid.bary_chains.push_back(nb_bary); grid.cells[cell_id].barys.push_back(nb_bary); grid.seg_bary_array[seg_idx] = nb_bary; SABarycenterRef new_bary_1 = { seg_idx + 1, p_1, 1 /*weight*/, 1 /*is_last_in_chain*/ }; grid.bary_points.push_back(new_bary_1); int new_cell_id = grid.GetCellIdx(p_1); grid.cells[new_cell_id].barys.push_back(nb_bary + 1); } } } // TEMP { for (int chain_idx = 0; chain_idx < grid.bary_chains.size(); chain_idx++) { int bary_idx = grid.bary_chains[chain_idx]; vec3 prev_pos = grid.bary_points[bary_idx].pos; float prev2_dist = 0.f; float prev_dist = 0.f; int print_next = 0; SABarycenterRef const* prev2_bary = nullptr; SABarycenterRef const* prev_bary = nullptr; SABarycenterRef const* bary; do { bary = &grid.bary_points[bary_idx++]; vec3 pos = bary->pos; float dist = distance(prev_pos, pos); if( prev_dist > 0.f && dist > 5.f * prev_dist) { if(prev2_bary) PrintBary(prev2_bary, bary_idx - 2, prev2_dist); if(prev_bary) PrintBary(prev_bary, bary_idx - 1, prev_dist); PrintBary(bary, bary_idx, dist); print_next = 2; } else if(print_next) { PrintBary(bary, bary_idx, dist); print_next--; if(!print_next) BB_LOG(SAUtils, Log, "\n"); } prev2_dist = prev_dist; prev_dist = dist; prev_pos = pos; prev2_bary = prev_bary; prev_bary = bary; } while (!bary->is_last_in_chain); BB_LOG(SAUtils, Log, "Chain %d stops with bary %d\n", chain_idx, bary_idx); } } // TEMP debug view if( shape_params.show_bary ) { for (int chain_idx = 0; chain_idx < grid.bary_chains.size(); chain_idx++) { AttractorOrientedCurve new_framed; snapped_lines.push_back(new_framed); AttractorOrientedCurve& ref_framed = snapped_lines.Last(); int bary_idx = grid.bary_chains[chain_idx]; SABarycenterRef const* bary; do { bary = &grid.bary_points[bary_idx++]; ref_framed.points.push_back(bary->pos); ref_framed.colors.push_back((float)bary->weight); } while (!bary->is_last_in_chain); if (ref_framed.points.size() < 4) { snapped_lines.pop_back(); } else { GenerateFrames(ref_framed); } } } else { // interpolate weights // 3- Parse segment in order, smoothly lerp current blend weight of seg to next barycenter, and compute new position //AttractorOrientedCurve* new_framed = nullptr; AttractorOrientedCurve new_framed; snapped_lines.push_back(new_framed); AttractorOrientedCurve& ref_framed = snapped_lines.Last(); if (nb_points < 2) { return; } int bary_counter = 0; //static int max_bary_counter = 30; vec3 previous_interp_pos = line_points[0]; vec3 previous_interp_dir = normalize(line_points[1] - line_points[0]); vec3 previous_dir_to_bary = orthogonal(previous_interp_dir); vec3 previous_seg_dir = previous_interp_dir; quat previous_seg_quat = quat(1.f); ref_framed.points.push_back(previous_interp_pos); for (int seg_idx = 1; seg_idx < nb_points - 1; seg_idx++) { vec3 pt = line_points[seg_idx]; vec3 next_pt = line_points[seg_idx + 1]; vec3 seg_dir = next_pt - pt; float seg_len = length(seg_dir); seg_dir /= seg_len; quat seg_quat = quat::rotate(previous_seg_dir, seg_dir); int bary_idx = grid.seg_bary_array[seg_idx]; SABarycenterRef& bary_0 = grid.bary_points[bary_idx]; SABarycenterRef& bary_1 = grid.bary_points[bary_idx + 1]; int target_seg_idx = bigball::min( seg_idx + shape_params.target_bary_offset, nb_points - 2 ); int target_bary_idx = grid.seg_bary_array[target_seg_idx]; SABarycenterRef& bary_t = grid.bary_points[target_bary_idx]; float t_bary; float sq_dist = SquaredDistancePointSegment_Unclamped(pt, bary_0.pos, bary_1.pos, t_bary); float len_to_bary = bigball::sqrt(sq_dist); vec3 bary_proj = bary_0.pos * (1.f - t_bary) + bary_1.pos * t_bary; vec3 dir_to_bary; if (len_to_bary < 1e-3f) { dir_to_bary = previous_dir_to_bary; } else { dir_to_bary = bary_proj - pt; dir_to_bary /= len_to_bary; } vec3 left_dir = normalize(cross(dir_to_bary, seg_dir)); vec3 plane_dir = cross(left_dir, dir_to_bary); // extrapolate pos from previous_interp_dir // fix dir by following seg curve rotation vec3 ray_dir = /*shape_params.show_bary ? previous_interp_dir :*/ previous_seg_quat.transform(previous_interp_dir); float project_dist = intersect::RayPlaneIntersection(previous_interp_pos, ray_dir, pt, plane_dir); // compare against avg dist between points, clamp dist as we can move -50% <-> +50% float move_dist = bigball::clamp(project_dist, seg_len * 0.5f, seg_len * 1.5f); // compute project_pos (clamped) vec3 project_pos = previous_interp_pos + previous_interp_dir * move_dist; // compute interp_pos by drifting project_pos towards bary_proj by small amount vec3 interp_pos = project_pos; vec3 drift_dir; //if(shape_params.show_bary) // drift_dir = bary_proj - project_pos; //else { vec3 target_dir = bary_t.pos - project_pos; float dist_target = dot( ray_dir, target_dir ); drift_dir = target_dir - (ray_dir * dist_target); } float drift_len = length(drift_dir); if( drift_len > 1e-3f) { drift_dir /= drift_len; const float max_drift = shape_params.max_drift;// 0.01f; drift_len = bigball::clamp(drift_len, -max_drift, max_drift); interp_pos += drift_dir * drift_len; } ref_framed.points.push_back(interp_pos); ref_framed.colors.push_back((float)0.f); previous_dir_to_bary = dir_to_bary; previous_interp_dir = normalize(interp_pos - previous_interp_pos); previous_interp_pos = interp_pos; previous_seg_dir = seg_dir; previous_seg_quat = seg_quat; } #if OLD_CODE vec3 interp_pos = nb_points ? line_points[0] : vec3(0.f, 0.f, 0.f); vec3 project_pos, dir_to_bary(0.f,0.f,1.f); vec3 previous_seg_dir = nb_points > 1 ? line_points[1] - line_points[0] : vec3(0.f, 0.f, 0.f); float inc = 1.f; //float last_sstep = 0.f; for (int seg_idx = 0; seg_idx < nb_points - 1; seg_idx++) { vec3 pos = line_points[seg_idx]; int bary_idx = grid.seg_bary_array[seg_idx]; SABarycenterRef& bary_0 = grid.bary_points[bary_idx]; SABarycenterRef& bary_1 = grid.bary_points[bary_idx + 1]; float t_bary; float sq_dist = SquaredDistancePointSegment_Unclamped(pos, bary_0.pos, bary_1.pos, t_bary); float len_to_bary = bigball::sqrt(sq_dist); vec3 bary_proj = bary_0.pos * (1.f - t_bary) + bary_1.pos * t_bary; if (len_to_bary < 1e-3f) { // vec3 dir_seg = vec3(0.f,0.f,0.f); { if (seg_idx > 0) dir_seg = pos - line_points[seg_idx - 1]; dir_seg += line_points[seg_idx + 1] - pos; dir_seg = normalize(dir_seg); vec3 vec_ortho = normalize(cross(dir_seg, dir_to_bary)); dir_to_bary = cross(vec_ortho, dir_seg); } } else { dir_to_bary = bary_proj - pos; dir_to_bary /= len_to_bary; } vec3 right_dir = normalize( cross(dir_to_bary, previous_seg_dir) ); vec3 plane_dir = cross(right_dir, dir_to_bary); //float sstep = smoothstep((float)bary_counter / (float)max_bary_counter); // project last interp pos onto dir float interp_len = dot(interp_pos - pos, dir_to_bary); project_pos = pos + dir_to_bary * interp_len; float remaining_dist = len_to_bary - interp_len; float current_t = (float)bary_counter / (float)max_bary_counter; const float max_inc = 2.f / (float)max_bary_counter; float inc = bigball::clamp(remaining_dist, -max_inc, max_inc); //if (current_t == 0.f) //{ // //} //if (current_t < 1.f) { //float dsstep = 6.f*current_t - 6.f*current_t*current_t; interp_pos = project_pos + dir_to_bary * inc;//(remaining_dist * dsstep / (float)max_bary_counter); } //else //{ // interp_pos = bary_proj; //} //float dist_H = (len_to_bary - interp_len) / (1.f - last_sstep); //interp_pos = pos + dir_to_bary * (dist_H * sstep); //float dist_H = (len_to_bary - interp_len) / (1.f - last_sstep); //interp_pos = pos + dir_to_bary * (interp_len + dist_H * sstep); ref_framed.points.push_back(interp_pos); previous_seg_dir = line_points[seg_idx + 1] - pos; if (bary_1.is_last_in_chain || bary_0.weight != bary_1.weight) { bary_counter = 0; //last_sstep = 0.f; } else { bary_counter++; //last_sstep = sstep; } } #endif // OLD_CODE GenerateFrames(ref_framed); } // compute positions and frames // - if first_leading_seg = me, push pos } // Second iteration of MergeLinePoints void SAUtils::MergeLinePoints2(AttractorOrientedCurve const& line_framed, const Array<AttractorHandle>& attr_handles, AttractorShapeParams const& shape_params, Array<AttractorOrientedCurve>& snapped_lines) { BB_LOG(SAUtils, Log, "MergeLinePoints2\n"); // compute current bounds Array<AABB> bounds; ComputeBounds(line_framed.points, shape_params.merge_dist, bounds); int nb_bounds = bounds.size(); const int min_spacing = 9 * SAUtils::points_in_bound; snapped_lines.push_back(line_framed); // temporary AttractorSnapRangeEx snap_range; ivec2 last_src_points = { -1, -1 }; int b_idx1 = 0; while (b_idx1 < nb_bounds) { BB_LOG(SAUtils, Log, "\rMergeLinePoints2 %d / %d", b_idx1, nb_bounds); AABB const& b1 = bounds[b_idx1]; int next_idx = b_idx1 + 1; // compare with all previous bounds, since we want only to merge with previous lines for (int b_idx0 = 0; b_idx0 < b_idx1 - 1; b_idx0++) { AABB const& b0 = bounds[b_idx0]; if (AABB::BoundsIntersect(b0, b1)) { // potential merge, check whether at least one segment in b1 is near one in b0 snap_range.Clear(); if (FindSnapRangeEx(line_framed.points, b_idx0, b_idx1, shape_params.merge_dist, snap_range)) { if (snap_range.src_points.y - snap_range.src_points.x >= min_spacing || // ignore snap_ranges if they are too short (/*)snap_range.src_points.y >= last_src_points.x && */snap_range.src_points.x > last_src_points.y)) { // compute relative weights of snap and compute reverse infos ComputeReverseSnapRangeExInfo(line_framed.points, shape_params.merge_dist, snap_range); AttractorOrientedCurve& ref_framed = snapped_lines.Last(); for (int d_idx = 0; d_idx < snap_range.dst_seg_array.size(); d_idx++) { SnapSegInfo& snap_info = snap_range.dst_seg_array[d_idx]; int src_idx = snap_range.src_points.x + d_idx; vec3 src_pos = line_framed.points[src_idx]; vec3 dst_pos = line_framed.points[snap_info.seg_idx] * (1.f - snap_info.t_seg) + line_framed.points[snap_info.seg_idx + 1] * snap_info.t_seg; vec3 delta_pos = dst_pos - src_pos; vec3 p = src_pos + delta_pos * snap_info.weight * 0.5f; ref_framed.points[src_idx] = p; } for (int d_idx = 0; d_idx < snap_range.src_seg_array.size(); d_idx++) { SnapSegInfo& snap_info = snap_range.src_seg_array[d_idx]; int src_idx = snap_range.dst_segs.x + d_idx; vec3 src_pos = line_framed.points[src_idx]; vec3 dst_pos = line_framed.points[snap_info.seg_idx] * (1.f - snap_info.t_seg) + line_framed.points[snap_info.seg_idx + 1] * snap_info.t_seg; vec3 delta_pos = dst_pos - src_pos; vec3 p = src_pos + delta_pos * snap_info.weight * 0.5f; ref_framed.points[src_idx] = p; } // don't snap on an already snapped segment /*int snap_idx = 0; for (; snap_idx < snap_ranges.size(); snap_idx++) { if (!(snap_range.dst_segs.x > snap_ranges[snap_idx].src_points.y || snap_range.dst_segs.y < snap_ranges[snap_idx].src_points.x)) break; } if (snap_idx >= snap_ranges.size()) { // check that it does not collide with previous range bool skip_insert = false; int snap_idx_comp = snap_ranges.size() - 1; if (snap_idx_comp >= 0) { if (snap_range.src_points.y >= snap_ranges[snap_idx_comp].src_points.x && snap_range.src_points.x <= snap_ranges[snap_idx_comp].src_points.y) { // collision detected int snap_dist = snap_range.src_points.y - snap_range.src_points.x; int snap_dist_comp = snap_ranges[snap_idx_comp].src_points.y - snap_ranges[snap_idx_comp].src_points.x; if (snap_dist_comp > snap_dist) { BB_LOG(SAUtils, Log, "MergeLinePoints ignoring %d snap range\n", snap_ranges.size()); skip_insert = true; } else { BB_LOG(SAUtils, Log, "MergeLinePoints replacing %d snap range\n", snap_idx_comp); snap_ranges.erase(snap_idx_comp); } } } if (!skip_insert) snap_ranges.push_back(snap_range);*/ last_src_points.x = snap_range.src_points.x; last_src_points.y = snap_range.src_points.y; next_idx = 1 + snap_range.src_points.y / SAUtils::points_in_bound; break; //} } } } } b_idx1 = next_idx; } } void SAUtils::MergeLinePoints(AttractorOrientedCurve const& line_framed, const Array<AttractorHandle>& attr_handles, AttractorShapeParams const& shape_params, Array<AttractorOrientedCurve>& snapped_lines) { BB_LOG(SAUtils, Log, "MergeLinePoints\n"); // compute bounds Array<AABB> bounds; ComputeBounds(line_framed.points, shape_params.merge_dist, bounds); int nb_bounds = bounds.size(); Array<vec3> modified_points; Array<AttractorSnapRange> snap_ranges; const int min_spacing = 9 * SAUtils::points_in_bound; int b_idx1 = 0; while (b_idx1 < nb_bounds) { BB_LOG(SAUtils, Log, "\rMergeLinePoints2 %d / %d", b_idx1, nb_bounds); AABB const& b1 = bounds[b_idx1]; int next_idx = b_idx1 + 1; // compare with all previous bounds, since we want only to merge with previous lines for (int b_idx0 = 0; b_idx0 < b_idx1 - 1; b_idx0++) { AABB const& b0 = bounds[b_idx0]; if (AABB::BoundsIntersect(b0, b1)) { // potential merge, check whether at least one segment in b1 is near one in b0 AttractorSnapRange snap_range; if (FindSnapRange(line_framed.points, b_idx0, b_idx1, shape_params.merge_dist, snap_range)) { if (snap_range.src_points.y - snap_range.src_points.x >= min_spacing) // ignore snap_ranges if they are too short { // don't snap on an already snapped segment int snap_idx = 0; for (; snap_idx < snap_ranges.size(); snap_idx++) { if (!(snap_range.dst_segs.x > snap_ranges[snap_idx].src_points.y || snap_range.dst_segs.y < snap_ranges[snap_idx].src_points.x)) break; } if (snap_idx >= snap_ranges.size()) { // check that it does not collide with previous range bool skip_insert = false; int snap_idx_comp = snap_ranges.size() - 1; if (snap_idx_comp >= 0) { if (snap_range.src_points.y >= snap_ranges[snap_idx_comp].src_points.x && snap_range.src_points.x <= snap_ranges[snap_idx_comp].src_points.y) { // collision detected int snap_dist = snap_range.src_points.y - snap_range.src_points.x; int snap_dist_comp = snap_ranges[snap_idx_comp].src_points.y - snap_ranges[snap_idx_comp].src_points.x; if (snap_dist_comp > snap_dist) { BB_LOG(SAUtils, Log, "MergeLinePoints ignoring %d snap range\n", snap_ranges.size()); skip_insert = true; } else { BB_LOG(SAUtils, Log, "MergeLinePoints replacing %d snap range\n", snap_idx_comp); snap_ranges.erase(snap_idx_comp); } } } if (!skip_insert) snap_ranges.push_back(snap_range); next_idx = 1 + snap_range.src_points.y / SAUtils::points_in_bound; break; } } } } } b_idx1 = next_idx; } // check ending snap and whether we need to cut the line endings const int nb_range = snap_ranges.size(); int first_index = -1; int last_index = nb_range - 1; if (nb_range > 1 && shape_params.remove_line_ends) { // check if one range snaps onto beginning of curve int snap_idx = 0; for (snap_idx = 0; snap_idx < nb_range; snap_idx++) { if (snap_ranges[snap_idx].dst_segs.x == 0) break; } if (snap_idx == nb_range) first_index = 0; // check if ending of curve snaps onto sthg if (snap_ranges.Last().src_points.y < line_framed.points.size() - 1) last_index = nb_range - 2; } // build snapped_lines array if (nb_range > 0) { snapped_lines.reserve(nb_range + 2); for (int snap_idx = first_index; snap_idx <= last_index; snap_idx++) { int start_idx = (snap_idx >= 0 ? snap_ranges[snap_idx].src_points.y : 0); int end_idx = (snap_idx < nb_range - 1 ? snap_ranges[snap_idx + 1].src_points.x : line_framed.points.size() - 1); if (end_idx - start_idx < 3) continue; AttractorOrientedCurve new_framed; snapped_lines.push_back(new_framed); AttractorOrientedCurve& ref_framed = snapped_lines.Last(); int cur_seg_0 = INDEX_NONE; const int lerp_spacing = SAUtils::points_in_bound * 7 / 2; if (snap_idx >= 0 && shape_params.snap_interp) { // from snapped to unsnapped (i.e. from unplugged to plugged) cur_seg_0 = snap_ranges[snap_idx].dst_segs.y; for (int d_idx = 1; d_idx <= lerp_spacing; d_idx++) { int src_idx = start_idx - d_idx; float best_t, ratio_blend = smoothstep(float(d_idx) / float(lerp_spacing)); cur_seg_0 = FindNextBestSnapSeg(line_framed.points, src_idx, cur_seg_0, -1 /*inc*/, 1e8f, best_t); if (cur_seg_0 == INDEX_NONE) break; // oups, should not happen vec3 src_pos = line_framed.points[src_idx]; vec3 dst_pos = line_framed.points[cur_seg_0] * (1.f - best_t) + line_framed.points[cur_seg_0 + 1] * best_t; vec3 delta_pos = dst_pos - src_pos; vec3 p = src_pos + delta_pos * ratio_blend; ref_framed.points.insert(p, 0); ref_framed.frames.insert(line_framed.frames[src_idx], 0); ref_framed.follow_angles.insert(line_framed.follow_angles[src_idx], 0); } } ref_framed.snap_ranges.x = 0; ref_framed.snap_ranges.y = ref_framed.points.size(); // copy for (int idx = start_idx; idx <= end_idx; idx++) { ref_framed.points.push_back(line_framed.points[idx]); ref_framed.frames.push_back(line_framed.frames[idx]); ref_framed.follow_angles.push_back(line_framed.follow_angles[idx]); } ref_framed.snap_ranges.z = ref_framed.points.size(); if (cur_seg_0 != INDEX_NONE) { quat src_frame = line_framed.frames[cur_seg_0]; float src_follow_angle = line_framed.follow_angles[cur_seg_0]; quat dst_frame = line_framed.frames[start_idx]; float dst_follow_angle = line_framed.follow_angles[start_idx]; vec3 src_follow, dst_follow; FindNearestFollowVector(dst_frame, dst_follow_angle, src_frame, src_follow_angle, src_frame, src_follow_angle, shape_params.local_edge_count, dst_follow, src_follow); GenerateFrames(ref_framed, 0, lerp_spacing - 1, false, true /*use continuity from last copy*/, &src_follow, &dst_follow); } if (snap_idx < nb_range - 1 && shape_params.snap_interp) { // from unsnapped to snapped (i.e. from plugged to unplugged) //int prev_size = ref_framed.points.size(); int cur_seg_0 = snap_ranges[snap_idx + 1].dst_segs.x; for (int d_idx = 1; d_idx <= lerp_spacing; d_idx++) { int src_idx = end_idx + d_idx; float best_t, ratio_blend = smoothstep(float(d_idx) / float(lerp_spacing)); cur_seg_0 = FindNextBestSnapSeg(line_framed.points, src_idx, cur_seg_0, 1 /*inc*/, 1e8f, best_t); if (cur_seg_0 == INDEX_NONE) break; // oups, should not happen vec3 src_pos = line_framed.points[src_idx]; vec3 dst_pos = line_framed.points[cur_seg_0] * (1.f - best_t) + line_framed.points[cur_seg_0 + 1] * best_t; vec3 delta_pos = dst_pos - src_pos; vec3 p = src_pos + delta_pos * ratio_blend; ref_framed.points.push_back(p); ref_framed.frames.push_back(line_framed.frames[src_idx]); ref_framed.follow_angles.push_back(line_framed.follow_angles[src_idx]); } if (cur_seg_0 != INDEX_NONE) { quat src_frame = line_framed.frames[end_idx]; float src_follow_angle = line_framed.follow_angles[end_idx]; quat dst_frame = line_framed.frames[cur_seg_0]; float dst_follow_angle = line_framed.follow_angles[cur_seg_0]; vec3 src_follow, dst_follow; FindNearestFollowVector(src_frame, src_follow_angle, dst_frame, dst_follow_angle, dst_frame, dst_follow_angle, shape_params.local_edge_count, src_follow, dst_follow); GenerateFrames(ref_framed, ref_framed.points.size() - 1 - lerp_spacing, ref_framed.points.size() - 1, true /*use continuity from last copy*/, false, &src_follow, &dst_follow); } } ref_framed.snap_ranges.w = ref_framed.points.size(); } } else { snapped_lines.push_back(line_framed); } } void SAUtils::GenerateSnappedCurve(AttractorOrientedCurve& curve /*in-out*/, const AttractorCurveSnap& snap_start, const AttractorCurveSnap& snap_end, AttractorShapeParams const& shape_params, const bool blend_positions) { const int32 interp_spacing = shape_params.merge_span; AttractorOrientedCurve tmp_curve; tmp_curve.Resize(interp_spacing); int cur_seg_0 = INDEX_NONE; //const int lerp_spacing = SAUtils::points_in_bound * 7 / 2; if (snap_start.seg >= 0) { // from snapped to unsnapped [S -> U] (i.e. from unplugged to plugged) const int start_idx = 0; cur_seg_0 = snap_start.seg; for (int d_idx = 0; d_idx < interp_spacing; d_idx++) { int src_idx = start_idx + d_idx; float best_t; cur_seg_0 = FindNextBestSnapSeg(snap_start.curve->points, curve.points[src_idx], cur_seg_0, +1 /*inc*/, 1e8f, best_t); if (cur_seg_0 == INDEX_NONE) break; // oups, should not happen vec3 src_pos = curve.points[src_idx]; vec3 p = src_pos; if (blend_positions) { float ratio_blend = smoothstep(1.f - float(d_idx) / float(interp_spacing)); vec3 dst_pos = snap_start.curve->points[cur_seg_0] * (1.f - best_t) + snap_start.curve->points[cur_seg_0 + 1] * best_t; vec3 delta_pos = dst_pos - src_pos; p += delta_pos * ratio_blend; } tmp_curve.points[d_idx] = p;//.push_back(p); //cur_framed.frames.push_back(line_frames[src_idx]); //cur_framed.follow_angles.push_back(follow_angles[src_idx]); } #if 1 if (cur_seg_0 != INDEX_NONE) { int start_seg_0 = snap_start.seg;// snap_ranges[snap_idx].dst_segs.y; quat dst_frame = snap_start.curve->frames[start_seg_0];// line_frames[start_seg_0]; float dst_follow_angle = snap_start.curve->follow_angles[start_seg_0];//follow_angles[start_seg_0]; quat dst_cmp_frame = curve.frames[start_idx]; float dst_cmp_follow_angle = curve.follow_angles[start_idx]; quat src_frame = curve.frames[start_idx + interp_spacing]; float src_follow_angle = curve.follow_angles[start_idx + interp_spacing]; vec3 src_follow, dst_follow; FindNearestFollowVector(src_frame, src_follow_angle, dst_frame, dst_follow_angle, dst_cmp_frame, dst_cmp_follow_angle, shape_params.local_edge_count, src_follow, dst_follow); for (int d_idx = 0; d_idx < interp_spacing; d_idx++) curve.points[d_idx] = tmp_curve.points[d_idx]; // generate frames and follow_angles for the first section [SU] // we needed to wait for the in-between copy because of the continuity flag below GenerateFrames(curve, 0, interp_spacing - 1, false, true /*use continuity from last copy*/, &dst_follow, &src_follow); } #endif } //////////////////////////////////////////////////// if (snap_end.seg >= 0) { // from unsnapped to snapped [U -> S] (i.e. from plugged to unplugged) //const int prev_size = cur_framed.points.size(); const int end_idx = curve.points.size()-1; int cur_seg_0 = snap_end.seg;//snap_ranges[snap_idx + 1].dst_segs.x; for (int d_idx = 0; d_idx < interp_spacing; d_idx++) { int src_idx = end_idx - d_idx; float best_t; cur_seg_0 = FindNextBestSnapSeg(snap_end.curve->points, curve.points[src_idx], cur_seg_0, -1 /*inc*/, 1e8f, best_t); if (cur_seg_0 == INDEX_NONE) break; // oups, should not happen vec3 src_pos = curve.points[src_idx]; vec3 p = src_pos; if (blend_positions) { float ratio_blend = smoothstep(1.f - float(d_idx) / float(interp_spacing)); vec3 dst_pos = snap_end.curve->points[cur_seg_0] * (1.f - best_t) + snap_end.curve->points[cur_seg_0 + 1] * best_t; vec3 delta_pos = dst_pos - src_pos; p += delta_pos * ratio_blend; } tmp_curve.points[interp_spacing-1 - d_idx] = p;// //cur_framed.points.insert(p, prev_size); //cur_framed.frames.insert(line_frames[src_idx], prev_size); //cur_framed.follow_angles.insert(follow_angles[src_idx], prev_size); } #if 1 if (cur_seg_0 != INDEX_NONE) { int end_seg_0 = snap_end.seg;// snap_ranges[snap_idx + 1].dst_segs.x; quat src_frame = curve.frames[end_idx - interp_spacing]; float src_follow_angle = curve.follow_angles[end_idx - interp_spacing]; quat dst_cmp_frame = curve.frames[end_idx]; float dst_cmp_follow_angle = curve.follow_angles[end_idx]; quat dst_frame = snap_end.curve->frames[end_seg_0]; float dst_follow_angle = snap_end.curve->follow_angles[end_seg_0]; vec3 src_follow, dst_follow; FindNearestFollowVector(src_frame, src_follow_angle, dst_frame, dst_follow_angle, dst_cmp_frame, dst_cmp_follow_angle, shape_params.local_edge_count, src_follow, dst_follow); for (int d_idx = 0; d_idx < interp_spacing; d_idx++) curve.points[end_idx - (interp_spacing-1) + d_idx] = tmp_curve.points[d_idx]; GenerateFrames(curve, end_idx - interp_spacing, end_idx, true /*use continuity from last copy*/, false, &src_follow, &dst_follow); } #endif } } // takes a continuous line and a bunch of snap ranges, output an array of framed lines // note that: // - it does not generate frames where lines are snapped // - handles the case where multiple lines would snap on the same area / segments // - suppose line_points was already modified / interpolated; not line_frames nor follow_angles // - if blend_positions is true, resulting points in framed_lines will be smoothed out otherwise line_points positions will be copied as is void SAUtils::GenerateSnappedLinesWithFrames(const Array<vec3>& line_points, const Array<quat>& line_frames, const Array<float>& follow_angles, const Array<AttractorSnapRange>& snap_ranges, AttractorShapeParams const& shape_params, Array<AttractorOrientedCurve>& framed_lines /*out*/, const bool blend_positions) { const int32 interp_spacing = shape_params.merge_span; // sort snap_ranges by src_points Array<AttractorSnapRange> snap_ranges_sorted = snap_ranges; sort(&snap_ranges_sorted[0], snap_ranges_sorted.size(), [](const AttractorSnapRange & a, const AttractorSnapRange & b) -> bool { return a.src_points.x < b.src_points.x; }); // check ending snap and whether we need to cut the line endings const int nb_range = snap_ranges.size(); int first_index = -1; int last_index = nb_range - 1; if (nb_range > 0) { // check if beginning of curve snaps onto sthg first_index = snap_ranges[0].src_points.x == 0 ? 0 : -1; // check if ending of curve snaps onto sthg last_index = snap_ranges.Last().src_points.y == line_points.size() - 1 ? nb_range - 2 : nb_range - 1; } // build snapped_lines array if (nb_range > 0) { framed_lines.reserve(nb_range + 2); for (int snap_idx = first_index; snap_idx <= last_index; snap_idx++) { int start_idx = (snap_idx >= 0 ? snap_ranges[snap_idx].src_points.y : 0); int end_idx = (snap_idx < nb_range - 1 ? snap_ranges[snap_idx + 1].src_points.x : line_points.size() - 1); if (end_idx - start_idx < 2*interp_spacing + 2) continue; AttractorOrientedCurve new_framed; framed_lines.push_back(new_framed); AttractorOrientedCurve& cur_framed = framed_lines.Last(); int cur_seg_0 = INDEX_NONE; //const int lerp_spacing = SAUtils::points_in_bound * 7 / 2; if (snap_idx >= 0) { // from snapped to unsnapped [S -> U] (i.e. from unplugged to plugged) cur_seg_0 = snap_ranges[snap_idx].dst_segs.y; for (int d_idx = 0; d_idx < interp_spacing; d_idx++) { int src_idx = start_idx + d_idx; float best_t; cur_seg_0 = FindNextBestSnapSeg(line_points, src_idx, cur_seg_0, +1 /*inc*/, 1e8f, best_t); if (cur_seg_0 == INDEX_NONE) break; // oups, should not happen vec3 src_pos = line_points[src_idx]; vec3 p = src_pos; if (blend_positions) { float ratio_blend = smoothstep(1.f - float(d_idx) / float(interp_spacing)); vec3 dst_pos = line_points[cur_seg_0] * (1.f - best_t) + line_points[cur_seg_0 + 1] * best_t; vec3 delta_pos = dst_pos - src_pos; p += delta_pos * ratio_blend; } cur_framed.points.push_back(p); cur_framed.frames.push_back(line_frames[src_idx]); cur_framed.follow_angles.push_back(follow_angles[src_idx]); } } cur_framed.snap_ranges.x = 0; cur_framed.snap_ranges.y = cur_framed.points.size(); // copy for points in-between snap / smooth sections [U -> U] for (int idx = start_idx + interp_spacing; idx < end_idx - interp_spacing; idx++) { cur_framed.points.push_back(line_points[idx]); cur_framed.frames.push_back(line_frames[idx]); cur_framed.follow_angles.push_back(follow_angles[idx]); } cur_framed.snap_ranges.z = cur_framed.points.size(); if (cur_seg_0 != INDEX_NONE) { int start_seg_0 = snap_ranges[snap_idx].dst_segs.y; quat dst_frame = line_frames[start_seg_0]; float dst_follow_angle = follow_angles[start_seg_0]; quat dst_cmp_frame = line_frames[start_idx]; float dst_cmp_follow_angle = follow_angles[start_idx]; quat src_frame = line_frames[start_idx + interp_spacing]; float src_follow_angle = follow_angles[start_idx + interp_spacing]; vec3 src_follow, dst_follow; FindNearestFollowVector(src_frame, src_follow_angle, dst_frame, dst_follow_angle, dst_cmp_frame, dst_cmp_follow_angle, shape_params.local_edge_count, src_follow, dst_follow); // generate frames and follow_angles for the first section [SU] // we needed to wait for the in-between copy because of the continuity flag below GenerateFrames(cur_framed, 0, interp_spacing - 1, false, true /*use continuity from last copy*/, &dst_follow, &src_follow); } if (snap_idx < nb_range - 1) { // from unsnapped to snapped [U -> S] (i.e. from plugged to unplugged) const int prev_size = cur_framed.points.size(); int cur_seg_0 = snap_ranges[snap_idx + 1].dst_segs.x; for (int d_idx = 0; d_idx < interp_spacing; d_idx++) { int src_idx = end_idx - d_idx; float best_t; cur_seg_0 = FindNextBestSnapSeg(line_points, src_idx, cur_seg_0, -1 /*inc*/, 1e8f, best_t); if (cur_seg_0 == INDEX_NONE) break; // oups, should not happen vec3 src_pos = line_points[src_idx]; vec3 p = src_pos; if (blend_positions) { float ratio_blend = smoothstep(1.f - float(d_idx) / float(interp_spacing)); vec3 dst_pos = line_points[cur_seg_0] * (1.f - best_t) + line_points[cur_seg_0 + 1] * best_t; vec3 delta_pos = dst_pos - src_pos; p += delta_pos * ratio_blend; } cur_framed.points.insert(p, prev_size); cur_framed.frames.insert(line_frames[src_idx], prev_size); cur_framed.follow_angles.insert(follow_angles[src_idx], prev_size); } if (cur_seg_0 != INDEX_NONE) { int end_seg_0 = snap_ranges[snap_idx + 1].dst_segs.x; quat src_frame = line_frames[end_idx - interp_spacing]; float src_follow_angle = follow_angles[end_idx - interp_spacing]; quat dst_cmp_frame = line_frames[end_idx]; float dst_cmp_follow_angle = follow_angles[end_idx]; quat dst_frame = line_frames[end_seg_0]; float dst_follow_angle = follow_angles[end_seg_0]; vec3 src_follow, dst_follow; FindNearestFollowVector(src_frame, src_follow_angle, dst_frame, dst_follow_angle, dst_cmp_frame, dst_cmp_follow_angle, shape_params.local_edge_count, src_follow, dst_follow); GenerateFrames(cur_framed, cur_framed.points.size() - 1 - interp_spacing, cur_framed.points.size() - 1, true /*use continuity from last copy*/, false, &src_follow, &dst_follow); } } cur_framed.colors.resize(line_points.size(), 0.f); cur_framed.snap_ranges.w = cur_framed.points.size(); } } else { AttractorOrientedCurve new_framed; framed_lines.push_back(new_framed); AttractorOrientedCurve& cur_framed = framed_lines.Last(); cur_framed.points = line_points; cur_framed.colors.resize(line_points.size(), 0.f); GenerateFrames(cur_framed); } } //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// int32 FindSnapFromSrc(int32 src_idx, Array<AttractorSnapRange> const& snap_ranges) { for (int32 snap_idx = 0; snap_idx < snap_ranges.size(); ++snap_idx) { if (src_idx >= snap_ranges[snap_idx].src_points.x && src_idx <= snap_ranges[snap_idx].src_points.y) return snap_idx; } return INDEX_NONE; } void FindRefSnaps(int32 dst_idx, Array<AttractorSnapRange> const& snap_ranges, Array<RefSnap>& snaps) { for (int32 snap_idx = 0; snap_idx < snap_ranges.size(); ++snap_idx) { if (dst_idx >= snap_ranges[snap_idx].dst_segs.x && dst_idx <= snap_ranges[snap_idx].dst_segs.y) { } } } void FindAllRefs(int32 p_idx, Array<AttractorSnapRange> const& snap_ranges, Array<vec3> const& points, Array<int32> const& snap_segs) { Array<RefSnap> snapref_array; if (snap_segs[p_idx] != INDEX_NONE) { int32 snap_idx = FindSnapFromSrc(p_idx, snap_ranges); BB_ASSERT(snap_idx != INDEX_NONE); float t_seg; intersect::SquaredDistancePointSegment(points[p_idx], points[snap_segs[p_idx]], points[snap_segs[p_idx] + 1], t_seg); RefSnap new_ref = { snap_idx, p_idx, snap_segs[p_idx], t_seg }; snapref_array.push_back(new_ref); } int32 loop_idx = 0; while (loop_idx < snapref_array.size()) { RefSnap const& snap_ref = snapref_array[loop_idx]; // down search { int32 p_dn[2] = { snap_ref.seg_idx, snap_ref.seg_idx + 1 }; vec3 seg_pos = points[p_dn[0]] * (1.f - snap_ref.t_seg) + points[p_dn[1]] * snap_ref.t_seg; float t[2], d[2] = { FLT_MAX, FLT_MAX }; if (snap_segs[p_dn[0]] != INDEX_NONE) d[0] = intersect::SquaredDistancePointSegment(seg_pos, points[snap_segs[p_dn[0]]], points[snap_segs[p_dn[0]] + 1], t[0]); if (snap_segs[p_dn[1]] != INDEX_NONE) d[1] = intersect::SquaredDistancePointSegment(seg_pos, points[snap_segs[p_dn[1]]], points[snap_segs[p_dn[1]] + 1], t[1]); if (d[0] != FLT_MAX && d[1] != FLT_MAX) { int32 best_idx = (d[0] < d[1] ? 0 : 1); int32 snap_idx = FindSnapFromSrc(p_dn[best_idx], snap_ranges); BB_ASSERT(snap_idx != INDEX_NONE); RefSnap new_ref = { snap_idx, p_dn[best_idx], snap_segs[p_dn[best_idx]], t[best_idx] }; // TODO: push only if not already present snapref_array.push_back(new_ref); } } // top search: find all snap referencing our point { } } // find all segments to where this point should snap //struct { p8idx + t} } bool SAUtils::FindSnapRangeEx(const Array<vec3>& line_points, int b_idx0, int b_idx1, float merge_dist, AttractorSnapRangeEx& snap_range) { int start_0 = bigball::max(0, b_idx0 * SAUtils::points_in_bound - 1); int end_0 = bigball::min((b_idx0 + 1) * SAUtils::points_in_bound + 1, line_points.size()); int start_1 = b_idx1 * SAUtils::points_in_bound; int end_1 = bigball::min((b_idx1 + 1) * SAUtils::points_in_bound, line_points.size()); // find one segment in b1 that is closest to b0 chain than merge_dist const float sq_merge_dist = merge_dist * merge_dist; float t, sq_dist, min_sq_dist; int min_seg_0 = INDEX_NONE, min_seg_1 = INDEX_NONE, prev_seg_0 = INDEX_NONE; for (int p_1 = start_1; p_1 < end_1; p_1++) { min_sq_dist = FLT_MAX; for (int seg_0 = start_0; seg_0 < end_0 - 1; seg_0++) { sq_dist = intersect::SquaredDistancePointSegment(line_points[p_1], line_points[seg_0], line_points[seg_0 + 1], t); if (sq_dist < sq_merge_dist) { min_sq_dist = sq_dist; min_seg_0 = seg_0; break; } } if (min_sq_dist < sq_merge_dist) { if (prev_seg_0 != INDEX_NONE) { // found two successive points < merge_dist min_seg_1 = p_1 - 1; break; } else prev_seg_0 = min_seg_0; } else prev_seg_0 = INDEX_NONE; } if (min_seg_1 == INDEX_NONE) return false; // find out if lines are reversed or not vec3 dir_0 = line_points[min_seg_0 + 1] - line_points[min_seg_0]; vec3 dir_1 = line_points[min_seg_1 + 1] - line_points[min_seg_1]; int inc = bigball::dot(dir_0, dir_1) > 0.f ? 1 : -1; if (inc < 0) return false; // don't want to merge lines in opposite directions snap_range.dst_segs.x = prev_seg_0; snap_range.dst_segs.y = min_seg_0; snap_range.src_points.x = min_seg_1; snap_range.src_points.y = min_seg_1 + 1; // extend lines on both sides so as to get the full chain const int nb_points = line_points.size(); // left (r_1.x) { int cur_seg_0 = snap_range.dst_segs.x; int c_1_next = snap_range.src_points.x; while (c_1_next >= 0) { float best_t; cur_seg_0 = FindNextBestSnapSeg(line_points, c_1_next, cur_seg_0, -1 /*inc*/, sq_merge_dist, best_t); if (cur_seg_0 != INDEX_NONE) { snap_range.src_points.x = c_1_next--; snap_range.dst_segs.x = cur_seg_0; snap_range.dst_seg_array.insert(SnapSegInfo{ cur_seg_0, best_t, 0.f }, 0); } else { break; } } } // right (r_1.y) { int cur_seg_0 = snap_range.dst_segs.y; int c_1_next = snap_range.src_points.y; while (c_1_next < nb_points) { float best_t; cur_seg_0 = FindNextBestSnapSeg(line_points, c_1_next, cur_seg_0, 1 /*inc*/, sq_merge_dist, best_t); if (cur_seg_0 != INDEX_NONE) { snap_range.src_points.y = c_1_next++; snap_range.dst_segs.y = cur_seg_0; snap_range.dst_seg_array.push_back(SnapSegInfo{ cur_seg_0, best_t, 0.f }); } else { break; } } } return true; } bool SAUtils::ComputeReverseSnapRangeExInfo(const Array<vec3>& points, float merge_dist, AttractorSnapRangeEx& snap_range) { // we want to find reverse snapping info from the snap_range.dst_segs.x to snap_range.dst_segs.y + 1 float t[2], d[2] = { FLT_MAX, FLT_MAX }; if (snap_range.src_points.x > 0) d[0] = intersect::SquaredDistancePointSegment(points[snap_range.dst_segs.x], points[snap_range.src_points.x - 1], points[snap_range.src_points.x], t[0]); if (snap_range.src_points.x < points.size() - 1) d[1] = intersect::SquaredDistancePointSegment(points[snap_range.dst_segs.x], points[snap_range.src_points.x], points[snap_range.src_points.x + 1], t[1]); if (d[0] == FLT_MAX && d[1] == FLT_MAX) return false; int32 cur_seg_0 = (d[0] < d[1] ? snap_range.src_points.x - 1 : snap_range.src_points.x); for (int dst_idx = snap_range.dst_segs.x; dst_idx <= snap_range.dst_segs.y + 1; dst_idx++) { float best_t; cur_seg_0 = FindNextBestSnapSeg(points, dst_idx, cur_seg_0, 1 /*inc*/, 1e8f, best_t); if (cur_seg_0 == INDEX_NONE) { return false; // oups, should not happen } snap_range.src_seg_array.push_back(SnapSegInfo{ cur_seg_0, best_t, 0.f }); } // compute weighting info //static float test = 2.f; //float res = smoothstep(test); const int lerp_spacing = SAUtils::points_in_bound * 7 / 2; { const int dst_seg_count = snap_range.dst_seg_array.size(); const int dst_half_count = dst_seg_count / 2; for (int d_idx = 0; d_idx < dst_half_count; d_idx++) { SnapSegInfo& snap_info = snap_range.dst_seg_array[d_idx]; float ratio_blend = bigball::min(smoothstep(float(d_idx) / float(lerp_spacing)), 1.f); snap_info.weight = ratio_blend; } for (int d_idx = dst_half_count; d_idx < dst_seg_count; d_idx++) { SnapSegInfo& snap_info = snap_range.dst_seg_array[d_idx]; float ratio_blend = bigball::min(smoothstep(float(dst_seg_count - d_idx - 1) / float(lerp_spacing)), 1.f); snap_info.weight = ratio_blend; } } // compute reverse weighting { const int src_seg_count = snap_range.src_seg_array.size(); for (int d_idx = 0; d_idx < src_seg_count; d_idx++) { SnapSegInfo& rev_snap_info = snap_range.src_seg_array[d_idx]; if (rev_snap_info.seg_idx < snap_range.src_points.x || rev_snap_info.seg_idx >= snap_range.src_points.y) rev_snap_info.weight = 0.f; else { int d_idx = rev_snap_info.seg_idx - snap_range.src_points.x; SnapSegInfo& snap_info_0 = snap_range.dst_seg_array[d_idx]; SnapSegInfo& snap_info_1 = snap_range.dst_seg_array[d_idx + 1]; rev_snap_info.weight = snap_info_0.weight + rev_snap_info.t_seg * (snap_info_1.weight - snap_info_0.weight); } } } return true; } bool SAUtils::FindSnapRange(const Array<vec3>& line_points, int b_idx0, int b_idx1, float merge_dist, AttractorSnapRange& snap_range) { int start_0 = bigball::max(0, b_idx0 * SAUtils::points_in_bound - 1); int end_0 = bigball::min((b_idx0 + 1) * SAUtils::points_in_bound + 1, line_points.size()); int start_1 = b_idx1 * SAUtils::points_in_bound; int end_1 = bigball::min((b_idx1 + 1) * SAUtils::points_in_bound, line_points.size()); // find one segment in b1 that is closest to b0 chain than merge_dist const float sq_merge_dist = merge_dist * merge_dist; float t, sq_dist, min_sq_dist; int min_seg_0 = INDEX_NONE, min_seg_1 = INDEX_NONE, prev_seg_0 = INDEX_NONE; for (int p_1 = start_1; p_1 < end_1; p_1++) { min_sq_dist = FLT_MAX; for (int seg_0 = start_0; seg_0 < end_0 - 1; seg_0++) { sq_dist = intersect::SquaredDistancePointSegment(line_points[p_1], line_points[seg_0], line_points[seg_0 + 1], t); if (sq_dist < sq_merge_dist) { min_sq_dist = sq_dist; min_seg_0 = seg_0; break; } } if (min_sq_dist < sq_merge_dist) { if (prev_seg_0 != INDEX_NONE) { // found two successive points < merge_dist min_seg_1 = p_1 - 1; break; } else prev_seg_0 = min_seg_0; } else prev_seg_0 = INDEX_NONE; } if (min_seg_1 == INDEX_NONE) return false; // find out if lines are reversed or not vec3 dir_0 = line_points[min_seg_0 + 1] - line_points[min_seg_0]; vec3 dir_1 = line_points[min_seg_1 + 1] - line_points[min_seg_1]; int inc = bigball::dot(dir_0, dir_1) > 0.f ? 1 : -1; snap_range.dst_segs.x = prev_seg_0; snap_range.dst_segs.y = min_seg_0; snap_range.src_points.x = min_seg_1; snap_range.src_points.y = min_seg_1 + 1; if (inc < 0) return false; // don't want to merge lines in opposite directions // extend lines on both sides so as to get the full chain const int nb_points = line_points.size(); // left (r_1.x) { int cur_seg_0 = snap_range.dst_segs.x; int& c_1 = snap_range.src_points.x; int c_1_next = c_1; while (c_1_next >= 0) { float best_t; cur_seg_0 = FindNextBestSnapSeg(line_points, c_1_next, cur_seg_0, -1 /*inc*/, sq_merge_dist, best_t); if (cur_seg_0 != INDEX_NONE && (cur_seg_0 < snap_range.src_points.x || cur_seg_0 > snap_range.src_points.y)) // prevent line from wrapping and snapping on itself { c_1 = c_1_next--; snap_range.dst_segs.x = cur_seg_0; } else { break; } } } // right (r_1.y) { int cur_seg_0 = snap_range.dst_segs.y; int& c_1 = snap_range.src_points.y; int c_1_next = c_1; while (c_1_next < nb_points) { float best_t; cur_seg_0 = FindNextBestSnapSeg(line_points, c_1_next, cur_seg_0, 1 /*inc*/, sq_merge_dist, best_t); if (cur_seg_0 != INDEX_NONE && (cur_seg_0 < snap_range.src_points.x || cur_seg_0 > snap_range.src_points.y)) // prevent line from wrapping and snapping on itself { c_1 = c_1_next++; snap_range.dst_segs.y = cur_seg_0; } else { break; } } } return true; } int SAUtils::FindNextBestSnapSeg(const Array<vec3>& line_points, int c_1_next, int cur_seg_0, int inc, float sq_merge_dist, float& best_t) { return FindNextBestSnapSeg(line_points, line_points[c_1_next], cur_seg_0, inc, sq_merge_dist, best_t); } int SAUtils::FindNextBestSnapSeg(const Array<vec3>& line_points, vec3 pos, int cur_seg_0, int inc, float sq_merge_dist, float& best_t) { int best_seg = INDEX_NONE; const int max_iter = 6; for (int iter = 0; iter < max_iter; iter++) { float t, sq_dist = intersect::SquaredDistancePointSegment(pos, line_points[cur_seg_0], line_points[cur_seg_0 + 1], t); if (sq_dist < sq_merge_dist) { // move on to next seg sq_merge_dist = sq_dist; best_t = t; best_seg = cur_seg_0; cur_seg_0 = bigball::clamp(cur_seg_0 + inc, 0, line_points.size() - 2); } else break; } return best_seg; } void SAUtils::GenerateSolidMesh(Array<AttractorOrientedCurve> const& curves, const AttractorShapeParams& params, Array<vec3>& tri_vertices /*out*/, Array<vec3>* tri_normals /*out*/, Array<float>* tri_colors /*out*/, Array<int32>& tri_indices /*out*/, Array<int32>* indice_offsets, float rescale_factor) { Array<vec3> local_shape; GenerateLocalShape(local_shape, params); const int32 num_local_points = local_shape.size(); for (int line_idx = 0; line_idx < curves.size(); line_idx++) { AttractorOrientedCurve const & curve = curves[line_idx]; if(indice_offsets) indice_offsets->push_back(tri_indices.size()); int32 base_vertex = tri_vertices.size(); GenerateTriVertices(tri_vertices, tri_normals, tri_colors, local_shape, curve, params, rescale_factor); GenerateTriIndices(tri_vertices, num_local_points, tri_indices, params.weld_vertex, base_vertex); } } void SAUtils::GenerateSolidMesh(AttractorOrientedCurve const& curve, const AttractorShapeParams& params, Array<vec3>& tri_vertices /*out*/, Array<vec3>* tri_normals /*out*/, Array<int32>& tri_indices /*out*/, float rescale_factor) { Array<vec3> local_shape; GenerateLocalShape(local_shape, params); const int32 num_local_points = local_shape.size(); int32 base_vertex = tri_vertices.size(); GenerateTriVertices(tri_vertices, tri_normals, nullptr, local_shape, curve, params, rescale_factor); GenerateTriIndices(tri_vertices, num_local_points, tri_indices, params.weld_vertex, base_vertex); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// void SAUtils::GenerateColors(AttractorOrientedCurve& line_framed, float color) { int32 nb_points = line_framed.points.size(); line_framed.colors.resize(nb_points); for (int32 i = 0; i < nb_points; i++) { line_framed.colors[i] = color; } } void SAUtils::GenerateFrames(AttractorOrientedCurve& line_framed) { vec3 P_prev, P_current, P_next, vz_follow; vec3 vy_prev(1.f, 0.f, 0.f); Array<vec3> const& line_points = line_framed.points; Array<quat>& frames = line_framed.frames; Array<float>& follow_angles = line_framed.follow_angles; line_framed.frames.resize(line_points.size()); line_framed.follow_angles.resize(line_points.size()); for (int32 i = 1; i < line_points.size() - 1; i++) { P_prev = line_points[i - 1]; P_current = line_points[i]; P_next = line_points[i + 1]; vec3 V0 = P_current - P_prev; vec3 V1 = P_next - P_current; float V0_len = length(V0); vec3 V0N = V0 / V0_len; vec3 V1N = normalize(V1); vec3 vy = cross(V1N, V0N); // up vector float vy_len = length(vy); if (vy_len > 1e-4) vy /= vy_len; else vy = vy_prev; vec3 V0RightN = cross(V0N, vy); vec3 V1RightN = cross(V1N, vy); vec3 vz = normalize(V0RightN + V1RightN); // right vector vec3 vx = cross(vy, vz); // front vector frames[i] = mat3(vx, vy, vz); // Replace vz_follow inside vy, vz frame and remove vx component if (i == 1) vz_follow = vz; float dot_x = dot(vx, vz_follow); if (bigball::abs(dot_x) > 0.99f) int32 Break = 0; vz_follow -= vx * dot_x; vz_follow = normalize(vz_follow); float dot_y = dot(vy, vz_follow); float dot_z = dot(vz, vz_follow); float delta_angle = bigball::atan2(dot_y, dot_z); follow_angles[i] = delta_angle; vy_prev = vy; } frames[0] = frames[1]; frames[line_points.size() - 1] = frames[line_points.size() - 2]; follow_angles[0] = follow_angles[1]; follow_angles[line_points.size() - 1] = follow_angles[line_points.size() - 2]; } void SAUtils::GenerateFrames(AttractorOrientedCurve& line_framed, int from_idx, int to_idx, bool start_continuity, bool end_continuity, vec3* start_vector, vec3* end_vector) { vec3 P_prev, P_current, P_next, vz_follow; vec3 vy_prev(1.f, 0.f, 0.f); Array<vec3> const& line_points = line_framed.points; Array<quat>& frames = line_framed.frames; Array<float>& follow_angles = line_framed.follow_angles; int start_idx = (start_continuity ? from_idx : from_idx + 1); int end_idx = (end_continuity ? to_idx : to_idx - 1); quat delta_rot(1.f); bool constrained_vectors = (start_vector != nullptr && end_vector != nullptr) ? true : false; if (constrained_vectors) delta_rot = quat::rotate(*start_vector, *end_vector); for (int32 i = start_idx; i <= end_idx; i++) { P_prev = line_points[i - 1]; P_current = line_points[i]; P_next = line_points[i + 1]; vec3 V0 = P_current - P_prev; vec3 V1 = P_next - P_current; float V0_len = length(V0); vec3 V0N = V0 / V0_len; vec3 V1N = normalize(V1); vec3 vy = cross(V1N, V0N); // up vector float vy_len = length(vy); if (vy_len > 1e-4) vy /= vy_len; else vy = vy_prev; vec3 V0RightN = cross(V0N, vy); vec3 V1RightN = cross(V1N, vy); vec3 vz = normalize(V0RightN + V1RightN); // right vector vec3 vx = cross(vy, vz); // front vector frames[i] = mat3(vx, vy, vz); if (constrained_vectors) { // Simply interpolate between requested vectors float ratio = smoothstep(float(i - start_idx) / float(end_idx - start_idx)); quat ratio_quat = slerp(quat(1.f), delta_rot, ratio); ratio_quat = normalize(ratio_quat); vz_follow = ratio_quat.transform(*start_vector); } else { if (i == start_idx) vz_follow = vz; } // Replace vz_follow inside vy, vz frame and remove vx component float dot_x = dot(vx, vz_follow); if (bigball::abs(dot_x) > 0.99f) int32 Break = 0; vz_follow -= vx * dot_x; vz_follow = normalize(vz_follow); float dot_y = dot(vy, vz_follow); float dot_z = dot(vz, vz_follow); float delta_angle = bigball::atan2(dot_y, dot_z); follow_angles[i] = delta_angle; vy_prev = vy; } if (!start_continuity) frames[from_idx] = frames[from_idx + 1]; if (!end_continuity) frames[to_idx] = frames[to_idx - 1]; } void SAUtils::GenerateTriVertices(Array<vec3>& tri_vertices, Array<vec3>* tri_normals, Array<float>* tri_colors, const Array<vec3>& local_shape, const AttractorOrientedCurve& curve, const AttractorShapeParams& params, float rescale_factor) { const Array<vec3>& line_points = curve.points; const Array<float>& colors = curve.colors; const Array<quat>& frames = curve.frames; const Array<float>& follow_angles = curve.follow_angles; const int32 base_vertex = tri_vertices.size(); vec3 P_prev, P_current, P_next, VX_follow; const int32 num_local_points = local_shape.size(); const int32 line_inc = (params.simplify_level > 1 ? params.simplify_level : 1); Array<vec3> rotated_shape; rotated_shape.resize(num_local_points); for (int32 i = 1; i < line_points.size() - 1; i += line_inc) { mat3 mat(frames[i]); vec3 vx = mat.v0; // FRONT vec3 vy = mat.v1; // UP vec3 vz = mat.v2; // RIGHT float color = colors[i]; //if (i < line_framed.snap_ranges.y) // snap out // color = lerp(-1.f, 0.f, float(i - line_framed.snap_ranges.x) / float(line_framed.snap_ranges.y - line_framed.snap_ranges.x)); //else if (i >= line_framed.snap_ranges.z) // snap in // color = lerp(0.f, 1.f, float(i - line_framed.snap_ranges.z) / float(line_framed.snap_ranges.w - line_framed.snap_ranges.z)); P_prev = line_points[i - 1] * rescale_factor; P_current = line_points[i] * rescale_factor; //P_next = merge_line_points[i+1]; vec3 V0 = P_current - P_prev; //vec3 V1 = P_next - P_current; float V0_len = length(V0); vec3 V0N = V0 / V0_len; vec3 V0RightN = cross(V0N, vy); // Twist local shape with follow vec inside current frame VX, VY, VZ float delta_angle = follow_angles[i]; float cf = bigball::cos(delta_angle); float sf = bigball::sin(delta_angle); float cos_alpha = dot(V0RightN, vz); float scale = 1.0f / cos_alpha; for (int32 j = 0; j < num_local_points; ++j) { float local_z = local_shape[j].x * cf - local_shape[j].z * sf; float local_y = local_shape[j].x * sf + local_shape[j].z * cf; rotated_shape[j] = P_current + vz * (local_z * (scale * params.fatness_scale)) + vx * (local_shape[j].y * params.fatness_scale) + vy * (local_y * params.fatness_scale); } for (int32 j = 0; j < num_local_points; ++j) { vec3 P_shape = rotated_shape[j]; if (!params.weld_vertex) { tri_vertices.push_back(P_shape); tri_vertices.push_back(P_shape); if (tri_normals) { vec3 P_shape_prev = rotated_shape[(j + num_local_points - 1) % num_local_points]; vec3 P_shape_next = rotated_shape[(j + 1) % num_local_points]; vec3 temp_V = P_shape - P_current*2.f; vec3 normal_prev = normalize(temp_V + P_shape_prev); vec3 normal_next = normalize(temp_V + P_shape_next); tri_normals->push_back(normal_prev); tri_normals->push_back(normal_next); } if (tri_colors) { tri_colors->push_back(color); tri_colors->push_back(color); } } else { tri_vertices.push_back(P_shape); if (tri_normals) { vec3 normal_P = normalize(P_shape - P_current); tri_normals->push_back(normal_P); } if (tri_colors) { tri_colors->push_back(color); } } } //VLastZ = VZ; } // For capping... int32 ShapeWOCapCount = tri_vertices.size() - base_vertex; tri_vertices.push_back(line_points[1] * rescale_factor); vec3 start_normal = normalize(line_points[0] - line_points[1]); if (tri_normals) tri_normals->push_back(start_normal); if (tri_colors) tri_colors->push_back(-1.f); if (!params.weld_vertex) { // Push start vertices for (int32 j = 0; j < num_local_points; ++j) tri_vertices.push_back(tri_vertices[base_vertex + 2 * j]); if (tri_normals) { for (int32 j = 0; j < num_local_points; ++j) tri_normals->push_back(start_normal); } if (tri_colors) { for (int32 j = 0; j < num_local_points; ++j) tri_colors->push_back(-1.f); } } tri_vertices.push_back(line_points[line_points.size() - 2] * rescale_factor); vec3 end_normal = normalize(line_points[line_points.size() - 1] - line_points[line_points.size() - 2]); if (tri_normals) tri_normals->push_back(end_normal); if (tri_colors) tri_colors->push_back(1.f); if (!params.weld_vertex) { // Push end vertices for (int32 j = 0; j < num_local_points; ++j) tri_vertices.push_back(tri_vertices[base_vertex + ShapeWOCapCount - 2 * num_local_points + 2 * j]); if (tri_normals) { for (int32 j = 0; j < num_local_points; ++j) tri_normals->push_back(end_normal); } if (tri_colors) { for (int32 j = 0; j < num_local_points; ++j) tri_colors->push_back(1.f); } } } void SAUtils::GenerateTriIndices(const Array<vec3>& tri_vertices, int32 num_local_points, Array<int32>& tri_indices, const bool bWeldVertex, int32 base_vertex) { // Generate tri index if (bWeldVertex) { const int32 nShape = (tri_vertices.size() - base_vertex) / num_local_points; for (int32 i = 0; i<nShape - 1; i++) { for (int32 j = 0; j < num_local_points; ++j) { tri_indices.push_back(base_vertex + i * num_local_points + j); tri_indices.push_back(base_vertex + (i + 1) * num_local_points + j); tri_indices.push_back(base_vertex + i * num_local_points + (1 + j) % num_local_points); tri_indices.push_back(base_vertex + i * num_local_points + (1 + j) % num_local_points); tri_indices.push_back(base_vertex + (i + 1) * num_local_points + j); tri_indices.push_back(base_vertex + (i + 1) * num_local_points + (1 + j) % num_local_points); } } // First cap int32 nShapeSize = tri_vertices.size() - base_vertex; int32 Cap0 = nShapeSize - 2; int32 Cap1 = nShapeSize - 1; for (int32 j = 0; j < num_local_points; ++j) { tri_indices.push_back(base_vertex + Cap0); tri_indices.push_back(base_vertex + 0 * num_local_points + j); tri_indices.push_back(base_vertex + 0 * num_local_points + (1 + j) % num_local_points); } // Second cap for (int32 j = 0; j < num_local_points; ++j) { tri_indices.push_back(base_vertex + Cap1); tri_indices.push_back(base_vertex + (nShape - 1) * num_local_points + (1 + j) % num_local_points); tri_indices.push_back(base_vertex + (nShape - 1) * num_local_points + j); } } else { const int32 nShape = (tri_vertices.size() - base_vertex) / (2 * num_local_points) - 1; for (int32 i = 0; i<nShape - 1; i++) { for (int32 j = 0; j < num_local_points; ++j) { tri_indices.push_back(base_vertex + i * 2 * num_local_points + (2 * j + 1)); tri_indices.push_back(base_vertex + (i + 1) * 2 * num_local_points + (2 * j + 1)); tri_indices.push_back(base_vertex + i * 2 * num_local_points + (2 * j + 2) % (2 * num_local_points)); tri_indices.push_back(base_vertex + i * 2 * num_local_points + (2 * j + 2) % (2 * num_local_points)); tri_indices.push_back(base_vertex + (i + 1) * 2 * num_local_points + (2 * j + 1)); tri_indices.push_back(base_vertex + (i + 1) * 2 * num_local_points + (2 * j + 2) % (2 * num_local_points)); } } // First cap int32 nShapeSize = tri_vertices.size() - base_vertex; int32 Cap0 = nShapeSize - 2 - 2 * num_local_points; int32 Cap1 = nShapeSize - 1 - num_local_points; for (int32 j = 0; j < num_local_points; ++j) { tri_indices.push_back(base_vertex + Cap0); tri_indices.push_back(base_vertex + Cap0 + 1 + j); tri_indices.push_back(base_vertex + Cap0 + 1 + (j + 1) % num_local_points); //tri_indices.push_back( 0 * 2*num_local_points + (2*j+1) ); //tri_indices.push_back( 0 * 2*num_local_points + (2*j+2) % (2*num_local_points) ); } // Second cap for (int32 j = 0; j < num_local_points; ++j) { tri_indices.push_back(base_vertex + Cap1); tri_indices.push_back(base_vertex + Cap1 + 1 + (j + 1) % num_local_points); tri_indices.push_back(base_vertex + Cap1 + 1 + j); //tri_indices.push_back( (nShape-1) * 2*num_local_points + (2*j+2) % (2*num_local_points) ); //tri_indices.push_back( (nShape-1) * 2*num_local_points + (2*j+1) ); } } } void SAUtils::WriteObjFile( Archive& file, const Array<vec3>& tri_vertices, const Array<int32>& tri_indices ) { const char* filename = "strange attractor"; String tmp_str; tmp_str = String::Printf("#\n# %s\n#\n\n", filename); file.SerializeString(tmp_str); //fopen_s( &fp, filename, "wt" ); //fprintf( fp, "#\n# %s\n#\n\n", filename ); int32 i, num_points = tri_vertices.size(), num_tri = tri_indices.size() / 3; for (i = 0; i < num_points; ++i) { tmp_str = String::Printf("v %f %f %f\n", tri_vertices[i].x, tri_vertices[i].y, tri_vertices[i].z); file.SerializeString(tmp_str); //fprintf( fp, "v %f %f %f\n", vPos[i].x, vPos[i].y, vPos[i].z ); } for (i = 0; i < num_tri; ++i) { tmp_str = String::Printf("f %d %d %d\n", 1 + tri_indices[3*i], 1 + tri_indices[3*i+1], 1 + tri_indices[3*i+2] ); file.SerializeString(tmp_str); //fprintf( fp, "f %d %d %d\n", 1 + tri_indices[3*i], 1 + tri_indices[3*i+1], 1 + tri_indices[3*i+2] ); } //fclose( fp ); } void SAUtils::WritePlyFile(Archive& file, const Array<vec3>& tri_vertices, const Array<int32>& tri_indices) { bool binary_data = true; int32 i, num_points = tri_vertices.size(), num_tri = tri_indices.size() / 3; file.WriteString("ply\n"); if(binary_data) file.WriteString("format binary_little_endian 1.0\n"); else file.WriteString("format ascii 1.0\n"); //comment this file is a cube String tmp_str; tmp_str = String::Printf("element vertex %d\n", num_points); file.SerializeString(tmp_str); file.WriteString("property float32 x\n"); file.WriteString("property float32 y\n"); file.WriteString("property float32 z\n"); tmp_str = String::Printf("element face %d\n", num_tri); file.SerializeString(tmp_str); file.WriteString("property list int32 int32 vertex_index\n"); file.WriteString("end_header\n"); if (binary_data) { vec3 vertex; for (i = 0; i < num_points; ++i) { vertex = tri_vertices[i]; file.SerializeRaw(vertex); } int32 num_edge = 3, tri_idx; for (i = 0; i < num_tri; ++i) { file.SerializeRaw(num_edge); tri_idx = tri_indices[3 * i]; file.SerializeRaw(tri_idx); tri_idx = tri_indices[3 * i + 1]; file.SerializeRaw(tri_idx); tri_idx = tri_indices[3 * i + 2]; file.SerializeRaw(tri_idx); //fprintf( fp, "f %d %d %d\n", 1 + tri_indices[3*i], 1 + tri_indices[3*i+1], 1 + tri_indices[3*i+2] ); } } else { for (i = 0; i < num_points; ++i) { tmp_str = String::Printf("%f %f %f\n", tri_vertices[i].x, tri_vertices[i].y, tri_vertices[i].z); file.SerializeString(tmp_str); } for (i = 0; i < num_tri; ++i) { tmp_str = String::Printf("3 %d %d %d\n", tri_indices[3 * i], tri_indices[3 * i + 1], tri_indices[3 * i + 2]); file.SerializeString(tmp_str); //fprintf( fp, "f %d %d %d\n", 1 + tri_indices[3*i], 1 + tri_indices[3*i+1], 1 + tri_indices[3*i+2] ); } } } void SAUtils::GenerateLocalShape(Array<vec3>& local_shapes, const AttractorShapeParams& params) { bool is_simple_mesh = (params.crease_width <= 0.0 || params.crease_depth <= 0.0 ? true : false); const int32 nLocalPoint = (is_simple_mesh ? 1 : 5) * params.local_edge_count; local_shapes.resize(nLocalPoint); const float fatness = 1.0f; if (is_simple_mesh) { for (int32 edge_idx = 0; edge_idx < params.local_edge_count; ++edge_idx) { float Angle = 2.0f * F_PI * (float)edge_idx / (float)(params.local_edge_count); local_shapes[edge_idx] = vec3(fatness*bigball::cos(Angle), 0.0f, fatness*bigball::sin(Angle)); } } else { //const float min_wall = 0.7f; //float MinCreaseWidth = min_wall*0.5f / bigball::sin( F_PI / params.local_edge_count ); for (int32 edge_idx = 0; edge_idx < params.local_edge_count; ++edge_idx) { float Angle = 2.0f * F_PI * (float)edge_idx / (float)(params.local_edge_count); local_shapes[5 * edge_idx] = vec3(fatness*bigball::cos(Angle), 0.0, fatness*bigball::sin(Angle)); } vec3 V; for (int32 edge_idx = 0; edge_idx < params.local_edge_count; ++edge_idx) { const vec3& Prev = local_shapes[5 * edge_idx]; const vec3& Next = local_shapes[5 * (edge_idx + 1) % nLocalPoint]; V = Next - Prev; local_shapes[5 * edge_idx + 1] = Prev + V * params.crease_width; local_shapes[5 * edge_idx + 2] = (Prev + V * (params.crease_width + params.crease_bevel)) * (1.0f - params.crease_depth); local_shapes[5 * edge_idx + 3] = (Prev + V * (1.0f - (params.crease_width + params.crease_bevel))) * (1.0f - params.crease_depth); local_shapes[5 * edge_idx + 4] = Prev + V * (1.0f - params.crease_width); } } } int32 SAUtils::FindNearestPoint(const Array<vec3>& line_points, int32 PointIdx, int32 IgnoreStart, int32 IgnoreEnd) { vec3 V; vec3 PointToFind = line_points[PointIdx]; float NearestDist = FLT_MAX; float Len; int32 Neighbour = PointIdx; for (int32 i = 0; i<line_points.size(); ++i) { V = PointToFind - line_points[i]; Len = length(V); if (Len < NearestDist) { if (i < IgnoreStart || i > IgnoreEnd) { NearestDist = Len; Neighbour = i; } } } return Neighbour; } void SAUtils::FindNearestFollowVector(quat const& src_frame, float src_follow_angle, quat const& dst_frame, float dst_follow_angle, quat const& dst_cmp_frame, float dst_cmp_follow_angle, int32 local_edge_count, vec3& src_follow, vec3& dst_follow) { mat3 src_mat(src_frame); vec3 src_vy = src_mat.v1; // UP vec3 src_vz = src_mat.v2; // RIGHT float src_cf = bigball::cos(src_follow_angle); float src_sf = bigball::sin(src_follow_angle); src_follow = src_vz * src_cf + src_vy * src_sf; mat3 dst_cmp_mat(dst_cmp_frame); vec3 dst_cmp_vy = dst_cmp_mat.v1; // UP vec3 dst_cmp_vz = dst_cmp_mat.v2; // RIGHT float dst_cmp_cf = bigball::cos(dst_cmp_follow_angle); float dst_cmp_sf = bigball::sin(dst_cmp_follow_angle); vec3 dst_cmp_follow = dst_cmp_vz * dst_cmp_cf + dst_cmp_vy * dst_cmp_sf; dst_follow = vec3(0.f, 0.f, 0.f); mat3 dst_mat(dst_frame); vec3 dst_vy = dst_mat.v1; // UP vec3 dst_vz = dst_mat.v2; // RIGHT float best_dot = -FLT_MAX; //int32 best_i = 0; for (int32 i = 0; i < local_edge_count; ++i) { float dst_angle = dst_follow_angle + 2.0f * F_PI * (float)(i) / (float)(local_edge_count); float cf = bigball::cos(dst_angle); float sf = bigball::sin(dst_angle); vec3 new_follow = dst_vz * cf + dst_vy * sf; float dot_follow = dot(new_follow, dst_cmp_follow); if (dot_follow > best_dot) { best_dot = dot_follow; //best_i = i; dst_follow = new_follow; } } /* float dst_angle = dst_follow_angle + 2.0f * F_PI * (float)(best_i) / (float)(local_edge_count); float cf = bigball::cos(dst_angle); float sf = bigball::sin(dst_angle); dst_follow = dst_vz * cf + dst_vy * sf; */ } #if 0 void SAUtils::MergeLinePointsOld(const Array<vec3>& line_points, const Array<vec3>& VX_follow_array, const Array<vec3>& VX_array, const Array<vec3>& VZ_array, Array<vec3>& vMergePoints, Array<vec3>& vMergeFollow, const AttractorShapeParams& params) { vMergePoints = line_points; vMergeFollow = VX_follow_array; // Manage start if (params.merge_start >= 1) { // Find point nearest to us int32 StartIdx = 0; int32 Neighbour = FindNearestPoint(line_points, StartIdx, StartIdx, StartIdx + params.merge_start); // Check by which side we should go int32 Inc = 1; if (Neighbour >= line_points.size() - params.merge_start) { Inc = -1; } else if (Neighbour <= params.merge_start) { Inc = 1; } else { vec3 V0, V1; V0 = line_points[StartIdx + 1] - line_points[Neighbour + 1]; V1 = line_points[StartIdx + 1] - line_points[Neighbour - 1]; if (length(V0) < length(V1)) Inc = 1; else Inc = -1; } // Merge start const int32 Margin = 2; for (int32 Offset = 0; Offset < params.merge_start; Offset++) { float MergeRatio = (Offset < Margin) ? 1.0f : (1.0f - (float)(Offset - Margin) / (float)(params.merge_start - Margin)); vMergePoints[StartIdx + Offset] = line_points[StartIdx + Offset] * (1.0f - MergeRatio) + line_points[Neighbour + Offset*Inc] * MergeRatio; vec3 NeighbourFollow = FindNearestFollowVector(VX_follow_array[StartIdx + Offset], VX_follow_array[Neighbour + Offset*Inc], VX_array[Neighbour + Offset*Inc], VZ_array[Neighbour + Offset*Inc], params.local_edge_count); vMergeFollow[StartIdx + Offset] = VX_follow_array[StartIdx + Offset] * (1.0f - MergeRatio) + NeighbourFollow * MergeRatio; vMergeFollow[StartIdx + Offset] = normalize(vMergeFollow[StartIdx + Offset]); } } // Manage end if (params.merge_end >= 1) { // Find point nearest to us int32 StartIdx = line_points.size() - 1 - params.merge_end; int32 Neighbour = FindNearestPoint(line_points, StartIdx, StartIdx - params.merge_end, StartIdx + params.merge_end); // Check by which side we should go int32 Inc = 1; if (Neighbour >= line_points.size() - params.merge_end) { Inc = -1; } else if (Neighbour <= params.merge_end) { Inc = 1; } else { vec3 V0, V1; V0 = line_points[StartIdx + 1] - line_points[Neighbour + 1]; V1 = line_points[StartIdx + 1] - line_points[Neighbour - 1]; if (length(V0) < length(V1)) Inc = 1; else Inc = -1; } // Merge end const int32 Margin = 2; for (int32 Offset = 0; Offset < params.merge_end; Offset++) { float MergeRatio = (Offset >= params.merge_end - Margin) ? 1.0f : ((float)(Offset) / (float)(params.merge_end - Margin)); vMergePoints[StartIdx + Offset] = line_points[StartIdx + Offset] * (1.0f - MergeRatio) + line_points[Neighbour + Offset*Inc] * MergeRatio; vec3 NeighbourFollow = FindNearestFollowVector(VX_follow_array[StartIdx + Offset], VX_follow_array[Neighbour + Offset*Inc], VX_array[Neighbour + Offset*Inc], VZ_array[Neighbour + Offset*Inc], params.local_edge_count); vMergeFollow[StartIdx + Offset] = VX_follow_array[StartIdx + Offset] * (1.0f - MergeRatio) + NeighbourFollow * MergeRatio; vMergeFollow[StartIdx + Offset] = normalize(vMergeFollow[StartIdx + Offset]); } } } #endif // 0 AttractorFactory::AttractorFactory() : m_all_attractors{ nullptr } { } AttractorFactory::~AttractorFactory() { Destroy(); } void AttractorFactory::Create() { m_all_attractors[eAttractor_Lorentz] = new LorenzAttractor; m_all_attractors[eAttractor_Aizawa] = new AizawaAttractor; m_all_attractors[eAttractor_TSUCS2] = new TSUCS2Attractor; m_all_attractors[eAttractor_Arneodo] = new ArneodoAttractor; m_all_attractors[eAttractor_ChenLee] = new ChenLeeAttractor; m_all_attractors[eAttractor_DequanLi] = new DequanLiAttractor; m_all_attractors[eAttractor_LorentzMod2] = new LorentzMod2Attractor; m_all_attractors[eAttractor_Hadley] = new HadleyAttractor; m_all_attractors[eAttractor_LorentzMod1] = new LorentzMod1Attractor; m_all_attractors[eAttractor_LotkaVolterra] = new LotkaVolterraAttractor; m_all_attractors[eAttractor_Halvorsen] = new HalvorsenAttractor; m_all_attractors[eAttractor_TSUCS1] = new TSUCS1Attractor; m_all_attractors[eAttractor_SpiralTest] = new SpiralTestAttractor; } void AttractorFactory::Destroy() { for( StrangeAttractor*& attractor : m_all_attractors ) { if( attractor ) delete attractor; attractor = nullptr; } } StrangeAttractor* AttractorFactory::CreateAttractorType(String const& attractor_name) { for( StrangeAttractor* attractor : m_all_attractors ) { if( attractor && (attractor_name == attractor->GetClassName()) ) return attractor->NewClassObject(); } return nullptr; } StrangeAttractor* AttractorFactory::CreateAttractorType(eAttractorType attractor_type) { if( m_all_attractors[attractor_type] ) return m_all_attractors[attractor_type]->NewClassObject(); return nullptr; } void AttractorFactory::GetAttractorTypeList(Array<String>& attractor_names) { for( StrangeAttractor* attractor : m_all_attractors ) { if( attractor ) attractor_names.push_back(attractor->GetClassName()); } } void SAUtils::ComputeBounds(const Array<vec3>& line_points, float margin, Array<AABB>& bounds) { int nb_bounds = (line_points.size() + points_in_bound - 1) / points_in_bound; bounds.resize(nb_bounds); for (int b = 0; b < nb_bounds; b++) { vec3 min = vec3(FLT_MAX, FLT_MAX, FLT_MAX); vec3 max = vec3(-FLT_MAX, -FLT_MAX, -FLT_MAX); //int start, end; //GetBoundPointIndices(b, start, end); int start = b * SAUtils::points_in_bound; int end = bigball::min(start + SAUtils::points_in_bound, line_points.size()); for (int p_idx = start; p_idx < end; p_idx++) { min = bigball::min(line_points[p_idx], min); max = bigball::max(line_points[p_idx], max); } bounds[b].min = min + vec3(-margin); bounds[b].max = max + vec3(margin); } } bool AABB::BoundsIntersect(AABB const& a, AABB const& b) { if (a.max.x < b.min.x || a.max.y < b.min.y || a.max.z < b.min.z || b.max.x < a.min.x || b.max.y < a.min.y || b.max.z < a.min.z) return false; return true; } void SAGrid::InitGrid(const Array<vec3>& line_points, int max_cell) { // compute grid bound vec3 min = vec3(FLT_MAX, FLT_MAX, FLT_MAX); vec3 max = vec3(-FLT_MAX, -FLT_MAX, -FLT_MAX); const int nb_points = line_points.size(); for (int p_idx = 0; p_idx < nb_points; p_idx++) { min = bigball::min(line_points[p_idx], min); max = bigball::max(line_points[p_idx], max); } grid_bound.min = min; grid_bound.max = max; vec3 diff = max - min; cell_unit = bigball::pow((diff.x * diff.y * diff.z) / max_cell, 0.33333333f); grid_dim.x = (int)(diff.x / cell_unit + 0.99999f); grid_dim.y = (int)(diff.y / cell_unit + 0.99999f); grid_dim.z = (int)(diff.z / cell_unit + 0.99999f); int real_max_cell = grid_dim.x * grid_dim.y * grid_dim.z; // init grid cells.resize(real_max_cell); seg_bary_array.clear(); seg_bary_array.resize(nb_points, INDEX_NONE); // insert segments into grid // assume that segments are stored into cells by their first point, even if second point is in another cell for (int p_idx = 0; p_idx < nb_points - 1; p_idx++) { int cell_id = GetCellIdx(line_points[p_idx]); cells[cell_id].segs.push_back(p_idx); } } SABaryResult SAGrid::FindBaryCenterSeg(int seg_idx, vec3 p_0/*, vec3 p_1*/, float max_dist) { //Array<SACell> cells; //Array<SABarycenterRef> bary_points; //Array<int> bary_chains; //Array<int> seg_bary_array; //float cell_unit; //ivec3 grid_dim; //AABB grid_bound; int i = (int)((p_0.x - grid_bound.min.x) / cell_unit); int j = (int)((p_0.y - grid_bound.min.y) / cell_unit); int k = (int)((p_0.z - grid_bound.min.z) / cell_unit); int i0 = max(0, i - 1); int i1 = min(grid_dim.x - 1, i + 1); int j0 = max(0, j - 1); int j1 = min(grid_dim.y - 1, j + 1); int k0 = max(0, k - 1); int k1 = min(grid_dim.z - 1, k + 1); const float sq_max_dist = max_dist * max_dist; // search 3x3x3 cells in neighborhood SABaryResult found_bary = { INDEX_NONE, INDEX_NONE }; //int min_bary_idx = INDEX_NONE; float sq_min_dist = sq_max_dist; for (int z = k0; z <= k1; z++) { for (int y = j0; y <= j1; y++) { for (int x = i0; x <= i1; x++) { int cell_id = x + grid_dim.x * y + grid_dim.x * grid_dim.y * z; SACell const& cell = cells[cell_id]; for (int bary_it = 0; bary_it < cell.barys.size(); bary_it++) { int bary_idx = cell.barys[bary_it]; SABarycenterRef const& b_0 = bary_points[bary_idx]; if (b_0.is_last_in_chain) continue; SABarycenterRef const& b_1 = bary_points[bary_idx + 1]; //vec3 b_vec = b_1.pos - b_0.pos; float t_seg; float sq_dist = SquaredDistancePointSegment_Unclamped(p_0, b_0.pos, b_1.pos, t_seg); if (sq_dist < sq_min_dist) { if (t_seg >= 0.f && t_seg < 1.f) { sq_min_dist = sq_dist; found_bary.cell_id = cell_id; found_bary.bary_in_array_idx = bary_it; } } } } } } return found_bary; } SASegResult SAGrid::FindNearestSeg(int p_idx, const Array<vec3>& line_points, float max_dist, int exclude_range) { vec3 p_0 = line_points[p_idx]; int i = (int)((p_0.x - grid_bound.min.x) / cell_unit); int j = (int)((p_0.y - grid_bound.min.y) / cell_unit); int k = (int)((p_0.z - grid_bound.min.z) / cell_unit); int i0 = max(0, i - 1); int i1 = min(grid_dim.x - 1, i + 1); int j0 = max(0, j - 1); int j1 = min(grid_dim.y - 1, j + 1); int k0 = max(0, k - 1); int k1 = min(grid_dim.z - 1, k + 1); const float sq_max_dist = max_dist * max_dist; // search 3x3x3 cells in neighborhood SASegResult found_seg = { INDEX_NONE, INDEX_NONE, 0.f, 0.f }; float sq_min_dist = sq_max_dist; for (int z = k0; z <= k1; z++) { for (int y = j0; y <= j1; y++) { for (int x = i0; x <= i1; x++) { int cell_id = x + grid_dim.x * y + grid_dim.x * grid_dim.y * z; SACell const& cell = cells[cell_id]; for (int seg_it = 0; seg_it < cell.segs.size(); seg_it++) { int seg_idx = cell.segs[seg_it]; if(seg_idx > p_idx - exclude_range && seg_idx < p_idx + exclude_range) continue; vec3 s_0 = line_points[seg_idx]; vec3 s_1 = line_points[seg_idx + 1]; float t_seg; float sq_dist = intersect::SquaredDistancePointSegment(p_0, s_0, s_1, t_seg); if (sq_dist < sq_min_dist) { if (t_seg >= 0.f && t_seg < 1.f) { sq_min_dist = sq_dist; found_seg.cell_id = cell_id; found_seg.seg_in_array_idx = seg_it; found_seg.t_seg = t_seg; found_seg.sq_dist = sq_dist; } } } } } } return found_seg; } int32 SAGrid::FindSegInRange(int32 bary_idx, int32 seg_idx, int32 range) { SABarycenterRef const& bary = bary_points[bary_idx]; int32 found_idx = INDEX_NONE; for( int32 s_idx = 0; s_idx < bary.seg_refs.size(); s_idx++) { int32 seg_ref = bary.seg_refs[s_idx]; if( seg_ref >= seg_idx - range && seg_ref <= seg_idx + range ) { found_idx = max(found_idx, seg_ref); } } return found_idx; } void SAGrid::MoveBary(SABaryResult const& bary_ref, vec3 bary_pos, int bary_idx) { int new_bary_cell_id = GetCellIdx(bary_pos); if (new_bary_cell_id != bary_ref.cell_id) { cells[bary_ref.cell_id].barys.erase(bary_ref.bary_in_array_idx); cells[new_bary_cell_id].barys.push_back(bary_idx); } } void SAGrid::MoveBary(vec3 old_bary_pos, vec3 bary_pos, int bary_idx) { int old_bary_cell_id = GetCellIdx(old_bary_pos); int new_bary_cell_id = GetCellIdx(bary_pos); if (new_bary_cell_id != old_bary_cell_id) { cells[old_bary_cell_id].barys.remove(bary_idx); cells[new_bary_cell_id].barys.push_back(bary_idx); } } void SAGrid::MovePoint(vec3 old_pos, vec3 new_pos, int pt_idx) { int old_cell_id = GetCellIdx(old_pos); int new_cell_id = GetCellIdx(new_pos); if (new_cell_id != old_cell_id) { cells[old_cell_id].segs.remove(pt_idx); cells[new_cell_id].segs.push_back(pt_idx); } } int SAGrid::GetCellIdx(vec3 p) const { int i = (int)((p.x - grid_bound.min.x) / cell_unit); int j = (int)((p.y - grid_bound.min.y) / cell_unit); int k = (int)((p.z - grid_bound.min.z) / cell_unit); int cell_id = i + grid_dim.x * j + grid_dim.x * grid_dim.y * k; return cell_id; } void AttractorShapeParams::Serialize(Archive& file) { int32 size = (int32)((int8*)&max_drift - (int8*)this); file.Serialize( this, size ); if( file.GetVersion() >= eSaeVersion_WithMergeSpan) file.SerializeRaw(merge_span); }
{ "content_hash": "1f9d28139d7f4b74f32321d9b1d1732d", "timestamp": "", "source": "github", "line_count": 2756, "max_line_length": 312, "avg_line_length": 41.65856313497823, "alnum_prop": 0.5187133637020843, "repo_name": "nsweb/sae", "id": "53680396089af743ef06772a9ec72cfb9bcab6f5", "size": "114811", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/engine/strangeattractors.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "352" }, { "name": "C++", "bytes": "233745" }, { "name": "GLSL", "bytes": "12226" }, { "name": "Lua", "bytes": "4926" } ], "symlink_target": "" }
#region About and License //======================================================================= // Copyright Andrew Szot 2015. // Distributed under the MIT License. // (See accompanying file LICENSE.txt) //======================================================================= #endregion using System; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace RenderingSystem.Graphics { /// <summary> /// Manages the lighting effects which are primarily flares. /// This is the post processing effect which is used in the post processing effect manager not the lens flare itself. /// </summary> class LightingEffectMgr : PostProcessingEffect { /// <summary> /// The scene supports a maximum number of flare effects at once. /// </summary> private const int MAX_FLARE_EFFECTS = 10; /// <summary> /// The number of lights which are using the flare effect the last update frame. /// </summary> private int i_frameLightCount; /// <summary> /// The list containing all lens flare effects for the scene. These are kept in sync with the lights using the lens flare effect. /// </summary> private List<LensFlareEffect> _lensFlareEffects = new List<LensFlareEffect>(); public LightingEffectMgr() : base("Lighting Effects") { } /// <summary> /// Load all resources which require the grahics device. /// </summary> /// <param name="device">The graphics device.</param> /// <param name="content">The content manager.</param> public override void LoadContent(GraphicsDevice device, Microsoft.Xna.Framework.Content.ContentManager content) { for (int i = 0; i < MAX_FLARE_EFFECTS; ++i) { LensFlareEffect lensFlareEffect = new LensFlareEffect(); lensFlareEffect.LoadContent(device); _lensFlareEffects.Add(lensFlareEffect); } } /// <summary> /// Update the flare effects based on this frames light batch. /// </summary> /// <param name="frameLights">The list of lights for this frame.</param> /// <param name="cam">The camera for this scene.</param> public override void SetFrameData(List<RendererImpl.GeneralLight> frameLights, ICamera cam) { IEnumerable<RenderingSystem.RendererImpl.GeneralLight> flareLights = from fl in frameLights where fl.FlareEnabled select fl; i_frameLightCount = Math.Min(MAX_FLARE_EFFECTS, flareLights.Count()); for (int i = 0; i < i_frameLightCount; ++i) { RenderingSystem.RendererImpl.GeneralLight light = flareLights.ElementAt(i); LensFlareEffect lfe = _lensFlareEffects.ElementAt(i); if (light.LightType == RendererImpl.GeneralLight.Type.Directional) { lfe.LightPos = Vector3.TransformNormal(Vector3.UnitZ, light.Transform); lfe.InfiniteViewPlane = true; } else { lfe.LightPos = light.Transform.Translation; lfe.InfiniteViewPlane = false; } lfe.GlowSize = light.GlowSize; lfe.QuerySize = light.QuerySize; } } /// <summary> /// Draw the geometry phase for this effect. /// THIS IS NECISSARY. /// </summary> /// <param name="view">The view for the camera.</param> /// <param name="proj">The projection for the camera.</param> /// <param name="device">The graphics device.</param> public override void DrawGeometryPhase(Matrix view, Matrix proj, GraphicsDevice device) { for (int i = 0; i < i_frameLightCount; ++i) { LensFlareEffect lfe = _lensFlareEffects.ElementAt(i); lfe.UpdateOcclusion(view, proj, device); } } /// <summary> /// Draw the effect using the input render target which should be the "back buffer" render target. /// </summary> /// <param name="device">The graphics device.</param> /// <param name="renderTarget">The final scene render target.</param> /// <param name="renderer">The scene renderer.</param> /// <returns></returns> public override RenderTarget2D DrawEffect(GraphicsDevice device, RenderTarget2D renderTarget, RenderingSystem.RendererImpl.Renderer renderer) { device.SetRenderTarget(renderTarget); for (int i = 0; i < i_frameLightCount; ++i) { LensFlareEffect lfe = _lensFlareEffects.ElementAt(i); lfe.Draw(device, p_spriteBatch); } return renderTarget; } } }
{ "content_hash": "4bc031b73514d4b1569d7d9af58a44c8", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 149, "avg_line_length": 37.68421052631579, "alnum_prop": 0.5804070231444534, "repo_name": "ASzot/Wumpus-XNA-Game-Engine", "id": "2dde73f1ce9e8d84d106aa77dbe908377a4796f3", "size": "5014", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HTW Game Engine/RenderingSystem/Graphics/Post Processing/LightingEffectMgr.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2506144" }, { "name": "HLSL", "bytes": "166647" }, { "name": "RPC", "bytes": "69838301" } ], "symlink_target": "" }
package com.tinkerpop.blueprints.util.wrappers.partition; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ @SuppressWarnings({ "rawtypes" }) public class PartitionEdge extends PartitionElement implements Edge { protected PartitionEdge(final Edge baseEdge, final PartitionGraph graph) { super(baseEdge, graph); } public Vertex getVertex(final Direction direction) throws IllegalArgumentException { final Vertex vertex = ((Edge) baseElement).getVertex(direction); return graph.isInPartition(vertex) ? new PartitionVertex(((Edge) baseElement).getVertex(direction), graph) : null; } public String getLabel() { return ((Edge) this.baseElement).getLabel(); } public Edge getBaseEdge() { return (Edge) this.baseElement; } }
{ "content_hash": "a82de44e40e39d94453dfb1ed27702f0", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 122, "avg_line_length": 32.172413793103445, "alnum_prop": 0.722400857449089, "repo_name": "mariusj/org.openntf.domino", "id": "c281b92c26e7b1c5ee165f5aa26569a2edc97c5c", "size": "933", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "domino/externals/tinkerpop/src/main/java/com/tinkerpop/blueprints/util/wrappers/partition/PartitionEdge.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11139" }, { "name": "HTML", "bytes": "2643162" }, { "name": "Java", "bytes": "16665599" }, { "name": "Ragel", "bytes": "2783" }, { "name": "Shell", "bytes": "1792" }, { "name": "XPages", "bytes": "20096" }, { "name": "XSLT", "bytes": "4288" } ], "symlink_target": "" }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * SSR Window 4.0.0-beta.2 * Better handling for window object in SSR environment * https://github.com/nolimits4web/ssr-window * * Copyright 2021, Vladimir Kharlampidi * * Licensed under MIT * * Released on: July 22, 2021 */ /* eslint-disable no-param-reassign */ function isObject$1(obj) { return obj !== null && typeof obj === 'object' && 'constructor' in obj && obj.constructor === Object; } function extend$1(target, src) { if (target === void 0) { target = {}; } if (src === void 0) { src = {}; } Object.keys(src).forEach(function (key) { if (typeof target[key] === 'undefined') target[key] = src[key];else if (isObject$1(src[key]) && isObject$1(target[key]) && Object.keys(src[key]).length > 0) { extend$1(target[key], src[key]); } }); } var ssrDocument = { body: {}, addEventListener: function addEventListener() {}, removeEventListener: function removeEventListener() {}, activeElement: { blur: function blur() {}, nodeName: '' }, querySelector: function querySelector() { return null; }, querySelectorAll: function querySelectorAll() { return []; }, getElementById: function getElementById() { return null; }, createEvent: function createEvent() { return { initEvent: function initEvent() {} }; }, createElement: function createElement() { return { children: [], childNodes: [], style: {}, setAttribute: function setAttribute() {}, getElementsByTagName: function getElementsByTagName() { return []; } }; }, createElementNS: function createElementNS() { return {}; }, importNode: function importNode() { return null; }, location: { hash: '', host: '', hostname: '', href: '', origin: '', pathname: '', protocol: '', search: '' } }; function getDocument() { var doc = typeof document !== 'undefined' ? document : {}; extend$1(doc, ssrDocument); return doc; } var ssrWindow = { document: ssrDocument, navigator: { userAgent: '' }, location: { hash: '', host: '', hostname: '', href: '', origin: '', pathname: '', protocol: '', search: '' }, history: { replaceState: function replaceState() {}, pushState: function pushState() {}, go: function go() {}, back: function back() {} }, CustomEvent: function CustomEvent() { return this; }, addEventListener: function addEventListener() {}, removeEventListener: function removeEventListener() {}, getComputedStyle: function getComputedStyle() { return { getPropertyValue: function getPropertyValue() { return ''; } }; }, Image: function Image() {}, Date: function Date() {}, screen: {}, setTimeout: function setTimeout() {}, clearTimeout: function clearTimeout() {}, matchMedia: function matchMedia() { return {}; }, requestAnimationFrame: function requestAnimationFrame(callback) { if (typeof setTimeout === 'undefined') { callback(); return null; } return setTimeout(callback, 0); }, cancelAnimationFrame: function cancelAnimationFrame(id) { if (typeof setTimeout === 'undefined') { return; } clearTimeout(id); } }; function getWindow() { var win = typeof window !== 'undefined' ? window : {}; extend$1(win, ssrWindow); return win; } /** * Dom7 4.0.0-beta.1 * Minimalistic JavaScript library for DOM manipulation, with a jQuery-compatible API * https://framework7.io/docs/dom7.html * * Copyright 2021, Vladimir Kharlampidi * * Licensed under MIT * * Released on: July 22, 2021 */ function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } /* eslint-disable no-proto */ function makeReactive(obj) { var proto = obj.__proto__; Object.defineProperty(obj, '__proto__', { get: function get() { return proto; }, set: function set(value) { proto.__proto__ = value; } }); } var Dom7 = /*#__PURE__*/function (_Array) { _inheritsLoose(Dom7, _Array); function Dom7(items) { var _this; _this = _Array.call.apply(_Array, [this].concat(items)) || this; makeReactive(_assertThisInitialized(_this)); return _this; } return Dom7; }( /*#__PURE__*/_wrapNativeSuper(Array)); function arrayFlat(arr) { if (arr === void 0) { arr = []; } var res = []; arr.forEach(function (el) { if (Array.isArray(el)) { res.push.apply(res, arrayFlat(el)); } else { res.push(el); } }); return res; } function arrayFilter(arr, callback) { return Array.prototype.filter.call(arr, callback); } function arrayUnique(arr) { var uniqueArray = []; for (var i = 0; i < arr.length; i += 1) { if (uniqueArray.indexOf(arr[i]) === -1) uniqueArray.push(arr[i]); } return uniqueArray; } function qsa(selector, context) { if (typeof selector !== 'string') { return [selector]; } var a = []; var res = context.querySelectorAll(selector); for (var i = 0; i < res.length; i += 1) { a.push(res[i]); } return a; } function $(selector, context) { var window = getWindow(); var document = getDocument(); var arr = []; if (!context && selector instanceof Dom7) { return selector; } if (!selector) { return new Dom7(arr); } if (typeof selector === 'string') { var html = selector.trim(); if (html.indexOf('<') >= 0 && html.indexOf('>') >= 0) { var toCreate = 'div'; if (html.indexOf('<li') === 0) toCreate = 'ul'; if (html.indexOf('<tr') === 0) toCreate = 'tbody'; if (html.indexOf('<td') === 0 || html.indexOf('<th') === 0) toCreate = 'tr'; if (html.indexOf('<tbody') === 0) toCreate = 'table'; if (html.indexOf('<option') === 0) toCreate = 'select'; var tempParent = document.createElement(toCreate); tempParent.innerHTML = html; for (var i = 0; i < tempParent.childNodes.length; i += 1) { arr.push(tempParent.childNodes[i]); } } else { arr = qsa(selector.trim(), context || document); } // arr = qsa(selector, document); } else if (selector.nodeType || selector === window || selector === document) { arr.push(selector); } else if (Array.isArray(selector)) { if (selector instanceof Dom7) return selector; arr = selector; } return new Dom7(arrayUnique(arr)); } $.fn = Dom7.prototype; // eslint-disable-next-line function addClass() { for (var _len = arguments.length, classes = new Array(_len), _key = 0; _key < _len; _key++) { classes[_key] = arguments[_key]; } var classNames = arrayFlat(classes.map(function (c) { return c.split(' '); })); this.forEach(function (el) { var _el$classList; (_el$classList = el.classList).add.apply(_el$classList, classNames); }); return this; } function removeClass() { for (var _len2 = arguments.length, classes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { classes[_key2] = arguments[_key2]; } var classNames = arrayFlat(classes.map(function (c) { return c.split(' '); })); this.forEach(function (el) { var _el$classList2; (_el$classList2 = el.classList).remove.apply(_el$classList2, classNames); }); return this; } function toggleClass() { for (var _len3 = arguments.length, classes = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { classes[_key3] = arguments[_key3]; } var classNames = arrayFlat(classes.map(function (c) { return c.split(' '); })); this.forEach(function (el) { classNames.forEach(function (className) { el.classList.toggle(className); }); }); } function hasClass() { for (var _len4 = arguments.length, classes = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { classes[_key4] = arguments[_key4]; } var classNames = arrayFlat(classes.map(function (c) { return c.split(' '); })); return arrayFilter(this, function (el) { return classNames.filter(function (className) { return el.classList.contains(className); }).length > 0; }).length > 0; } function attr(attrs, value) { if (arguments.length === 1 && typeof attrs === 'string') { // Get attr if (this[0]) return this[0].getAttribute(attrs); return undefined; } // Set attrs for (var i = 0; i < this.length; i += 1) { if (arguments.length === 2) { // String this[i].setAttribute(attrs, value); } else { // Object for (var attrName in attrs) { this[i][attrName] = attrs[attrName]; this[i].setAttribute(attrName, attrs[attrName]); } } } return this; } function removeAttr(attr) { for (var i = 0; i < this.length; i += 1) { this[i].removeAttribute(attr); } return this; } function transform(transform) { for (var i = 0; i < this.length; i += 1) { this[i].style.transform = transform; } return this; } function transition$1(duration) { for (var i = 0; i < this.length; i += 1) { this[i].style.transitionDuration = typeof duration !== 'string' ? duration + "ms" : duration; } return this; } function on() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } var eventType = args[0], targetSelector = args[1], listener = args[2], capture = args[3]; if (typeof args[1] === 'function') { eventType = args[0]; listener = args[1]; capture = args[2]; targetSelector = undefined; } if (!capture) capture = false; function handleLiveEvent(e) { var target = e.target; if (!target) return; var eventData = e.target.dom7EventData || []; if (eventData.indexOf(e) < 0) { eventData.unshift(e); } if ($(target).is(targetSelector)) listener.apply(target, eventData);else { var _parents = $(target).parents(); // eslint-disable-line for (var k = 0; k < _parents.length; k += 1) { if ($(_parents[k]).is(targetSelector)) listener.apply(_parents[k], eventData); } } } function handleEvent(e) { var eventData = e && e.target ? e.target.dom7EventData || [] : []; if (eventData.indexOf(e) < 0) { eventData.unshift(e); } listener.apply(this, eventData); } var events = eventType.split(' '); var j; for (var i = 0; i < this.length; i += 1) { var el = this[i]; if (!targetSelector) { for (j = 0; j < events.length; j += 1) { var event = events[j]; if (!el.dom7Listeners) el.dom7Listeners = {}; if (!el.dom7Listeners[event]) el.dom7Listeners[event] = []; el.dom7Listeners[event].push({ listener: listener, proxyListener: handleEvent }); el.addEventListener(event, handleEvent, capture); } } else { // Live events for (j = 0; j < events.length; j += 1) { var _event = events[j]; if (!el.dom7LiveListeners) el.dom7LiveListeners = {}; if (!el.dom7LiveListeners[_event]) el.dom7LiveListeners[_event] = []; el.dom7LiveListeners[_event].push({ listener: listener, proxyListener: handleLiveEvent }); el.addEventListener(_event, handleLiveEvent, capture); } } } return this; } function off() { for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } var eventType = args[0], targetSelector = args[1], listener = args[2], capture = args[3]; if (typeof args[1] === 'function') { eventType = args[0]; listener = args[1]; capture = args[2]; targetSelector = undefined; } if (!capture) capture = false; var events = eventType.split(' '); for (var i = 0; i < events.length; i += 1) { var event = events[i]; for (var j = 0; j < this.length; j += 1) { var el = this[j]; var handlers = void 0; if (!targetSelector && el.dom7Listeners) { handlers = el.dom7Listeners[event]; } else if (targetSelector && el.dom7LiveListeners) { handlers = el.dom7LiveListeners[event]; } if (handlers && handlers.length) { for (var k = handlers.length - 1; k >= 0; k -= 1) { var handler = handlers[k]; if (listener && handler.listener === listener) { el.removeEventListener(event, handler.proxyListener, capture); handlers.splice(k, 1); } else if (listener && handler.listener && handler.listener.dom7proxy && handler.listener.dom7proxy === listener) { el.removeEventListener(event, handler.proxyListener, capture); handlers.splice(k, 1); } else if (!listener) { el.removeEventListener(event, handler.proxyListener, capture); handlers.splice(k, 1); } } } } } return this; } function trigger() { var window = getWindow(); for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { args[_key9] = arguments[_key9]; } var events = args[0].split(' '); var eventData = args[1]; for (var i = 0; i < events.length; i += 1) { var event = events[i]; for (var j = 0; j < this.length; j += 1) { var el = this[j]; if (window.CustomEvent) { var evt = new window.CustomEvent(event, { detail: eventData, bubbles: true, cancelable: true }); el.dom7EventData = args.filter(function (data, dataIndex) { return dataIndex > 0; }); el.dispatchEvent(evt); el.dom7EventData = []; delete el.dom7EventData; } } } return this; } function transitionEnd$1(callback) { var dom = this; function fireCallBack(e) { if (e.target !== this) return; callback.call(this, e); dom.off('transitionend', fireCallBack); } if (callback) { dom.on('transitionend', fireCallBack); } return this; } function outerWidth(includeMargins) { if (this.length > 0) { if (includeMargins) { var _styles = this.styles(); return this[0].offsetWidth + parseFloat(_styles.getPropertyValue('margin-right')) + parseFloat(_styles.getPropertyValue('margin-left')); } return this[0].offsetWidth; } return null; } function outerHeight(includeMargins) { if (this.length > 0) { if (includeMargins) { var _styles2 = this.styles(); return this[0].offsetHeight + parseFloat(_styles2.getPropertyValue('margin-top')) + parseFloat(_styles2.getPropertyValue('margin-bottom')); } return this[0].offsetHeight; } return null; } function offset() { if (this.length > 0) { var window = getWindow(); var document = getDocument(); var el = this[0]; var box = el.getBoundingClientRect(); var body = document.body; var clientTop = el.clientTop || body.clientTop || 0; var clientLeft = el.clientLeft || body.clientLeft || 0; var scrollTop = el === window ? window.scrollY : el.scrollTop; var scrollLeft = el === window ? window.scrollX : el.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; } return null; } function styles() { var window = getWindow(); if (this[0]) return window.getComputedStyle(this[0], null); return {}; } function css(props, value) { var window = getWindow(); var i; if (arguments.length === 1) { if (typeof props === 'string') { // .css('width') if (this[0]) return window.getComputedStyle(this[0], null).getPropertyValue(props); } else { // .css({ width: '100px' }) for (i = 0; i < this.length; i += 1) { for (var _prop in props) { this[i].style[_prop] = props[_prop]; } } return this; } } if (arguments.length === 2 && typeof props === 'string') { // .css('width', '100px') for (i = 0; i < this.length; i += 1) { this[i].style[props] = value; } return this; } return this; } function each(callback) { if (!callback) return this; this.forEach(function (el, index) { callback.apply(el, [el, index]); }); return this; } function filter(callback) { var result = arrayFilter(this, callback); return $(result); } function html(html) { if (typeof html === 'undefined') { return this[0] ? this[0].innerHTML : null; } for (var i = 0; i < this.length; i += 1) { this[i].innerHTML = html; } return this; } function text(text) { if (typeof text === 'undefined') { return this[0] ? this[0].textContent.trim() : null; } for (var i = 0; i < this.length; i += 1) { this[i].textContent = text; } return this; } function is(selector) { var window = getWindow(); var document = getDocument(); var el = this[0]; var compareWith; var i; if (!el || typeof selector === 'undefined') return false; if (typeof selector === 'string') { if (el.matches) return el.matches(selector); if (el.webkitMatchesSelector) return el.webkitMatchesSelector(selector); if (el.msMatchesSelector) return el.msMatchesSelector(selector); compareWith = $(selector); for (i = 0; i < compareWith.length; i += 1) { if (compareWith[i] === el) return true; } return false; } if (selector === document) { return el === document; } if (selector === window) { return el === window; } if (selector.nodeType || selector instanceof Dom7) { compareWith = selector.nodeType ? [selector] : selector; for (i = 0; i < compareWith.length; i += 1) { if (compareWith[i] === el) return true; } return false; } return false; } function index() { var child = this[0]; var i; if (child) { i = 0; // eslint-disable-next-line while ((child = child.previousSibling) !== null) { if (child.nodeType === 1) i += 1; } return i; } return undefined; } function eq(index) { if (typeof index === 'undefined') return this; var length = this.length; if (index > length - 1) { return $([]); } if (index < 0) { var returnIndex = length + index; if (returnIndex < 0) return $([]); return $([this[returnIndex]]); } return $([this[index]]); } function append() { var newChild; var document = getDocument(); for (var k = 0; k < arguments.length; k += 1) { newChild = k < 0 || arguments.length <= k ? undefined : arguments[k]; for (var i = 0; i < this.length; i += 1) { if (typeof newChild === 'string') { var tempDiv = document.createElement('div'); tempDiv.innerHTML = newChild; while (tempDiv.firstChild) { this[i].appendChild(tempDiv.firstChild); } } else if (newChild instanceof Dom7) { for (var j = 0; j < newChild.length; j += 1) { this[i].appendChild(newChild[j]); } } else { this[i].appendChild(newChild); } } } return this; } function prepend(newChild) { var document = getDocument(); var i; var j; for (i = 0; i < this.length; i += 1) { if (typeof newChild === 'string') { var tempDiv = document.createElement('div'); tempDiv.innerHTML = newChild; for (j = tempDiv.childNodes.length - 1; j >= 0; j -= 1) { this[i].insertBefore(tempDiv.childNodes[j], this[i].childNodes[0]); } } else if (newChild instanceof Dom7) { for (j = 0; j < newChild.length; j += 1) { this[i].insertBefore(newChild[j], this[i].childNodes[0]); } } else { this[i].insertBefore(newChild, this[i].childNodes[0]); } } return this; } function next(selector) { if (this.length > 0) { if (selector) { if (this[0].nextElementSibling && $(this[0].nextElementSibling).is(selector)) { return $([this[0].nextElementSibling]); } return $([]); } if (this[0].nextElementSibling) return $([this[0].nextElementSibling]); return $([]); } return $([]); } function nextAll(selector) { var nextEls = []; var el = this[0]; if (!el) return $([]); while (el.nextElementSibling) { var _next = el.nextElementSibling; // eslint-disable-line if (selector) { if ($(_next).is(selector)) nextEls.push(_next); } else nextEls.push(_next); el = _next; } return $(nextEls); } function prev(selector) { if (this.length > 0) { var el = this[0]; if (selector) { if (el.previousElementSibling && $(el.previousElementSibling).is(selector)) { return $([el.previousElementSibling]); } return $([]); } if (el.previousElementSibling) return $([el.previousElementSibling]); return $([]); } return $([]); } function prevAll(selector) { var prevEls = []; var el = this[0]; if (!el) return $([]); while (el.previousElementSibling) { var _prev = el.previousElementSibling; // eslint-disable-line if (selector) { if ($(_prev).is(selector)) prevEls.push(_prev); } else prevEls.push(_prev); el = _prev; } return $(prevEls); } function parent(selector) { var parents = []; // eslint-disable-line for (var i = 0; i < this.length; i += 1) { if (this[i].parentNode !== null) { if (selector) { if ($(this[i].parentNode).is(selector)) parents.push(this[i].parentNode); } else { parents.push(this[i].parentNode); } } } return $(parents); } function parents(selector) { var parents = []; // eslint-disable-line for (var i = 0; i < this.length; i += 1) { var _parent = this[i].parentNode; // eslint-disable-line while (_parent) { if (selector) { if ($(_parent).is(selector)) parents.push(_parent); } else { parents.push(_parent); } _parent = _parent.parentNode; } } return $(parents); } function closest(selector) { var closest = this; // eslint-disable-line if (typeof selector === 'undefined') { return $([]); } if (!closest.is(selector)) { closest = closest.parents(selector).eq(0); } return closest; } function find(selector) { var foundElements = []; for (var i = 0; i < this.length; i += 1) { var found = this[i].querySelectorAll(selector); for (var j = 0; j < found.length; j += 1) { foundElements.push(found[j]); } } return $(foundElements); } function children(selector) { var children = []; // eslint-disable-line for (var i = 0; i < this.length; i += 1) { var childNodes = this[i].children; for (var j = 0; j < childNodes.length; j += 1) { if (!selector || $(childNodes[j]).is(selector)) { children.push(childNodes[j]); } } } return $(children); } function remove() { for (var i = 0; i < this.length; i += 1) { if (this[i].parentNode) this[i].parentNode.removeChild(this[i]); } return this; } var Methods = { addClass: addClass, removeClass: removeClass, hasClass: hasClass, toggleClass: toggleClass, attr: attr, removeAttr: removeAttr, transform: transform, transition: transition$1, on: on, off: off, trigger: trigger, transitionEnd: transitionEnd$1, outerWidth: outerWidth, outerHeight: outerHeight, styles: styles, offset: offset, css: css, each: each, html: html, text: text, is: is, index: index, eq: eq, append: append, prepend: prepend, next: next, nextAll: nextAll, prev: prev, prevAll: prevAll, parent: parent, parents: parents, closest: closest, find: find, children: children, filter: filter, remove: remove }; Object.keys(Methods).forEach(function (methodName) { Object.defineProperty($.fn, methodName, { value: Methods[methodName], writable: true }); }); function deleteProps(obj) { var object = obj; Object.keys(object).forEach(function (key) { try { object[key] = null; } catch (e) {// no getter for object } try { delete object[key]; } catch (e) {// something got wrong } }); } function nextTick(callback, delay) { if (delay === void 0) { delay = 0; } return setTimeout(callback, delay); } function now() { return Date.now(); } function getComputedStyle$1(el) { var window = getWindow(); var style; if (window.getComputedStyle) { style = window.getComputedStyle(el, null); } if (!style && el.currentStyle) { style = el.currentStyle; } if (!style) { style = el.style; } return style; } function getTranslate(el, axis) { if (axis === void 0) { axis = 'x'; } var window = getWindow(); var matrix; var curTransform; var transformMatrix; var curStyle = getComputedStyle$1(el); if (window.WebKitCSSMatrix) { curTransform = curStyle.transform || curStyle.webkitTransform; if (curTransform.split(',').length > 6) { curTransform = curTransform.split(', ').map(function (a) { return a.replace(',', '.'); }).join(', '); } // Some old versions of Webkit choke when 'none' is passed; pass // empty string instead in this case transformMatrix = new window.WebKitCSSMatrix(curTransform === 'none' ? '' : curTransform); } else { transformMatrix = curStyle.MozTransform || curStyle.OTransform || curStyle.MsTransform || curStyle.msTransform || curStyle.transform || curStyle.getPropertyValue('transform').replace('translate(', 'matrix(1, 0, 0, 1,'); matrix = transformMatrix.toString().split(','); } if (axis === 'x') { // Latest Chrome and webkits Fix if (window.WebKitCSSMatrix) curTransform = transformMatrix.m41; // Crazy IE10 Matrix else if (matrix.length === 16) curTransform = parseFloat(matrix[12]); // Normal Browsers else curTransform = parseFloat(matrix[4]); } if (axis === 'y') { // Latest Chrome and webkits Fix if (window.WebKitCSSMatrix) curTransform = transformMatrix.m42; // Crazy IE10 Matrix else if (matrix.length === 16) curTransform = parseFloat(matrix[13]); // Normal Browsers else curTransform = parseFloat(matrix[5]); } return curTransform || 0; } function isObject(o) { return typeof o === 'object' && o !== null && o.constructor && Object.prototype.toString.call(o).slice(8, -1) === 'Object'; } function isNode(node) { // eslint-disable-next-line if (typeof window !== 'undefined' && typeof window.HTMLElement !== 'undefined') { return node instanceof HTMLElement; } return node && (node.nodeType === 1 || node.nodeType === 11); } function extend() { var to = Object(arguments.length <= 0 ? undefined : arguments[0]); var noExtend = ['__proto__', 'constructor', 'prototype']; for (var i = 1; i < arguments.length; i += 1) { var nextSource = i < 0 || arguments.length <= i ? undefined : arguments[i]; if (nextSource !== undefined && nextSource !== null && !isNode(nextSource)) { var keysArray = Object.keys(Object(nextSource)).filter(function (key) { return noExtend.indexOf(key) < 0; }); for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex += 1) { var nextKey = keysArray[nextIndex]; var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey); if (desc !== undefined && desc.enumerable) { if (isObject(to[nextKey]) && isObject(nextSource[nextKey])) { if (nextSource[nextKey].__swiper__) { to[nextKey] = nextSource[nextKey]; } else { extend(to[nextKey], nextSource[nextKey]); } } else if (!isObject(to[nextKey]) && isObject(nextSource[nextKey])) { to[nextKey] = {}; if (nextSource[nextKey].__swiper__) { to[nextKey] = nextSource[nextKey]; } else { extend(to[nextKey], nextSource[nextKey]); } } else { to[nextKey] = nextSource[nextKey]; } } } } } return to; } function classesToSelector(classes) { if (classes === void 0) { classes = ''; } return "." + classes.trim().replace(/([\.:\/])/g, '\\$1') // eslint-disable-line .replace(/ /g, '.'); } function createElementIfNotDefined($container, params, createElements, checkProps) { var document = getDocument(); if (createElements) { Object.keys(checkProps).forEach(function (key) { if (!params[key] && params.auto === true) { var element = document.createElement('div'); element.className = checkProps[key]; $container.append(element); params[key] = element; } }); } return params; } var support; function calcSupport() { var window = getWindow(); var document = getDocument(); return { touch: !!('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch), passiveListener: function checkPassiveListener() { var supportsPassive = false; try { var opts = Object.defineProperty({}, 'passive', { // eslint-disable-next-line get: function get() { supportsPassive = true; } }); window.addEventListener('testPassiveListener', null, opts); } catch (e) {// No support } return supportsPassive; }(), gestures: function checkGestures() { return 'ongesturestart' in window; }() }; } function getSupport() { if (!support) { support = calcSupport(); } return support; } var deviceCached; function calcDevice(_temp) { var _ref = _temp === void 0 ? {} : _temp, userAgent = _ref.userAgent; var support = getSupport(); var window = getWindow(); var platform = window.navigator.platform; var ua = userAgent || window.navigator.userAgent; var device = { ios: false, android: false }; var screenWidth = window.screen.width; var screenHeight = window.screen.height; var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/); // eslint-disable-line var ipad = ua.match(/(iPad).*OS\s([\d_]+)/); var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/); var iphone = !ipad && ua.match(/(iPhone\sOS|iOS)\s([\d_]+)/); var windows = platform === 'Win32'; var macos = platform === 'MacIntel'; // iPadOs 13 fix var iPadScreens = ['1024x1366', '1366x1024', '834x1194', '1194x834', '834x1112', '1112x834', '768x1024', '1024x768', '820x1180', '1180x820', '810x1080', '1080x810']; if (!ipad && macos && support.touch && iPadScreens.indexOf(screenWidth + "x" + screenHeight) >= 0) { ipad = ua.match(/(Version)\/([\d.]+)/); if (!ipad) ipad = [0, 1, '13_0_0']; macos = false; } // Android if (android && !windows) { device.os = 'android'; device.android = true; } if (ipad || iphone || ipod) { device.os = 'ios'; device.ios = true; } // Export object return device; } function getDevice(overrides) { if (overrides === void 0) { overrides = {}; } if (!deviceCached) { deviceCached = calcDevice(overrides); } return deviceCached; } var browser; function calcBrowser() { var window = getWindow(); function isSafari() { var ua = window.navigator.userAgent.toLowerCase(); return ua.indexOf('safari') >= 0 && ua.indexOf('chrome') < 0 && ua.indexOf('android') < 0; } return { isEdge: !!window.navigator.userAgent.match(/Edge/g), isSafari: isSafari(), isWebView: /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(window.navigator.userAgent) }; } function getBrowser() { if (!browser) { browser = calcBrowser(); } return browser; } function Resize(_ref) { var swiper = _ref.swiper, on = _ref.on, emit = _ref.emit; var window = getWindow(); var observer = null; var resizeHandler = function resizeHandler() { if (!swiper || swiper.destroyed || !swiper.initialized) return; emit('beforeResize'); emit('resize'); }; var createObserver = function createObserver() { if (!swiper || swiper.destroyed || !swiper.initialized) return; observer = new ResizeObserver(function (entries) { var width = swiper.width, height = swiper.height; var newWidth = width; var newHeight = height; entries.forEach(function (_ref2) { var contentBoxSize = _ref2.contentBoxSize, contentRect = _ref2.contentRect, target = _ref2.target; if (target && target !== swiper.el) return; newWidth = contentRect ? contentRect.width : (contentBoxSize[0] || contentBoxSize).inlineSize; newHeight = contentRect ? contentRect.height : (contentBoxSize[0] || contentBoxSize).blockSize; }); if (newWidth !== width || newHeight !== height) { resizeHandler(); } }); observer.observe(swiper.el); }; var removeObserver = function removeObserver() { if (observer && observer.unobserve && swiper.el) { observer.unobserve(swiper.el); observer = null; } }; var orientationChangeHandler = function orientationChangeHandler() { if (!swiper || swiper.destroyed || !swiper.initialized) return; emit('orientationchange'); }; on('init', function () { if (swiper.params.resizeObserver && typeof window.ResizeObserver !== 'undefined') { createObserver(); return; } window.addEventListener('resize', resizeHandler); window.addEventListener('orientationchange', orientationChangeHandler); }); on('destroy', function () { removeObserver(); window.removeEventListener('resize', resizeHandler); window.removeEventListener('orientationchange', orientationChangeHandler); }); } function Observer(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on, emit = _ref.emit; var observers = []; var window = getWindow(); var attach = function attach(target, options) { if (options === void 0) { options = {}; } var ObserverFunc = window.MutationObserver || window.WebkitMutationObserver; var observer = new ObserverFunc(function (mutations) { // The observerUpdate event should only be triggered // once despite the number of mutations. Additional // triggers are redundant and are very costly if (mutations.length === 1) { emit('observerUpdate', mutations[0]); return; } var observerUpdate = function observerUpdate() { emit('observerUpdate', mutations[0]); }; if (window.requestAnimationFrame) { window.requestAnimationFrame(observerUpdate); } else { window.setTimeout(observerUpdate, 0); } }); observer.observe(target, { attributes: typeof options.attributes === 'undefined' ? true : options.attributes, childList: typeof options.childList === 'undefined' ? true : options.childList, characterData: typeof options.characterData === 'undefined' ? true : options.characterData }); observers.push(observer); }; var init = function init() { if (!swiper.params.observer) return; if (swiper.params.observeParents) { var containerParents = swiper.$el.parents(); for (var i = 0; i < containerParents.length; i += 1) { attach(containerParents[i]); } } // Observe container attach(swiper.$el[0], { childList: swiper.params.observeSlideChildren }); // Observe wrapper attach(swiper.$wrapperEl[0], { attributes: false }); }; var destroy = function destroy() { observers.forEach(function (observer) { observer.disconnect(); }); observers.splice(0, observers.length); }; extendParams({ observer: false, observeParents: false, observeSlideChildren: false }); on('init', init); on('destroy', destroy); } /* eslint-disable no-underscore-dangle */ var eventsEmitter = { on: function on(events, handler, priority) { var self = this; if (typeof handler !== 'function') return self; var method = priority ? 'unshift' : 'push'; events.split(' ').forEach(function (event) { if (!self.eventsListeners[event]) self.eventsListeners[event] = []; self.eventsListeners[event][method](handler); }); return self; }, once: function once(events, handler, priority) { var self = this; if (typeof handler !== 'function') return self; function onceHandler() { self.off(events, onceHandler); if (onceHandler.__emitterProxy) { delete onceHandler.__emitterProxy; } for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } handler.apply(self, args); } onceHandler.__emitterProxy = handler; return self.on(events, onceHandler, priority); }, onAny: function onAny(handler, priority) { var self = this; if (typeof handler !== 'function') return self; var method = priority ? 'unshift' : 'push'; if (self.eventsAnyListeners.indexOf(handler) < 0) { self.eventsAnyListeners[method](handler); } return self; }, offAny: function offAny(handler) { var self = this; if (!self.eventsAnyListeners) return self; var index = self.eventsAnyListeners.indexOf(handler); if (index >= 0) { self.eventsAnyListeners.splice(index, 1); } return self; }, off: function off(events, handler) { var self = this; if (!self.eventsListeners) return self; events.split(' ').forEach(function (event) { if (typeof handler === 'undefined') { self.eventsListeners[event] = []; } else if (self.eventsListeners[event]) { self.eventsListeners[event].forEach(function (eventHandler, index) { if (eventHandler === handler || eventHandler.__emitterProxy && eventHandler.__emitterProxy === handler) { self.eventsListeners[event].splice(index, 1); } }); } }); return self; }, emit: function emit() { var self = this; if (!self.eventsListeners) return self; var events; var data; var context; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (typeof args[0] === 'string' || Array.isArray(args[0])) { events = args[0]; data = args.slice(1, args.length); context = self; } else { events = args[0].events; data = args[0].data; context = args[0].context || self; } data.unshift(context); var eventsArray = Array.isArray(events) ? events : events.split(' '); eventsArray.forEach(function (event) { if (self.eventsAnyListeners && self.eventsAnyListeners.length) { self.eventsAnyListeners.forEach(function (eventHandler) { eventHandler.apply(context, [event].concat(data)); }); } if (self.eventsListeners && self.eventsListeners[event]) { self.eventsListeners[event].forEach(function (eventHandler) { eventHandler.apply(context, data); }); } }); return self; } }; function updateSize() { var swiper = this; var width; var height; var $el = swiper.$el; if (typeof swiper.params.width !== 'undefined' && swiper.params.width !== null) { width = swiper.params.width; } else { width = $el[0].clientWidth; } if (typeof swiper.params.height !== 'undefined' && swiper.params.height !== null) { height = swiper.params.height; } else { height = $el[0].clientHeight; } if (width === 0 && swiper.isHorizontal() || height === 0 && swiper.isVertical()) { return; } // Subtract paddings width = width - parseInt($el.css('padding-left') || 0, 10) - parseInt($el.css('padding-right') || 0, 10); height = height - parseInt($el.css('padding-top') || 0, 10) - parseInt($el.css('padding-bottom') || 0, 10); if (Number.isNaN(width)) width = 0; if (Number.isNaN(height)) height = 0; Object.assign(swiper, { width: width, height: height, size: swiper.isHorizontal() ? width : height }); } function updateSlides() { var swiper = this; function getDirectionLabel(property) { if (swiper.isHorizontal()) { return property; } // prettier-ignore return { 'width': 'height', 'margin-top': 'margin-left', 'margin-bottom ': 'margin-right', 'margin-left': 'margin-top', 'margin-right': 'margin-bottom', 'padding-left': 'padding-top', 'padding-right': 'padding-bottom', 'marginRight': 'marginBottom' }[property]; } function getDirectionPropertyValue(node, label) { return parseFloat(node.getPropertyValue(getDirectionLabel(label)) || 0); } var params = swiper.params; var $wrapperEl = swiper.$wrapperEl, swiperSize = swiper.size, rtl = swiper.rtlTranslate, wrongRTL = swiper.wrongRTL; var isVirtual = swiper.virtual && params.virtual.enabled; var previousSlidesLength = isVirtual ? swiper.virtual.slides.length : swiper.slides.length; var slides = $wrapperEl.children("." + swiper.params.slideClass); var slidesLength = isVirtual ? swiper.virtual.slides.length : slides.length; var snapGrid = []; var slidesGrid = []; var slidesSizesGrid = []; var offsetBefore = params.slidesOffsetBefore; if (typeof offsetBefore === 'function') { offsetBefore = params.slidesOffsetBefore.call(swiper); } var offsetAfter = params.slidesOffsetAfter; if (typeof offsetAfter === 'function') { offsetAfter = params.slidesOffsetAfter.call(swiper); } var previousSnapGridLength = swiper.snapGrid.length; var previousSlidesGridLength = swiper.slidesGrid.length; var spaceBetween = params.spaceBetween; var slidePosition = -offsetBefore; var prevSlideSize = 0; var index = 0; if (typeof swiperSize === 'undefined') { return; } if (typeof spaceBetween === 'string' && spaceBetween.indexOf('%') >= 0) { spaceBetween = parseFloat(spaceBetween.replace('%', '')) / 100 * swiperSize; } swiper.virtualSize = -spaceBetween; // reset margins if (rtl) slides.css({ marginLeft: '', marginBottom: '', marginTop: '' });else slides.css({ marginRight: '', marginBottom: '', marginTop: '' }); var slidesNumberEvenToRows; if (params.slidesPerColumn > 1) { if (Math.floor(slidesLength / params.slidesPerColumn) === slidesLength / swiper.params.slidesPerColumn) { slidesNumberEvenToRows = slidesLength; } else { slidesNumberEvenToRows = Math.ceil(slidesLength / params.slidesPerColumn) * params.slidesPerColumn; } if (params.slidesPerView !== 'auto' && params.slidesPerColumnFill === 'row') { slidesNumberEvenToRows = Math.max(slidesNumberEvenToRows, params.slidesPerView * params.slidesPerColumn); } } // Calc slides var slideSize; var slidesPerColumn = params.slidesPerColumn; var slidesPerRow = slidesNumberEvenToRows / slidesPerColumn; var numFullColumns = Math.floor(slidesLength / params.slidesPerColumn); for (var i = 0; i < slidesLength; i += 1) { slideSize = 0; var slide = slides.eq(i); if (params.slidesPerColumn > 1) { // Set slides order var newSlideOrderIndex = void 0; var column = void 0; var row = void 0; if (params.slidesPerColumnFill === 'row' && params.slidesPerGroup > 1) { var groupIndex = Math.floor(i / (params.slidesPerGroup * params.slidesPerColumn)); var slideIndexInGroup = i - params.slidesPerColumn * params.slidesPerGroup * groupIndex; var columnsInGroup = groupIndex === 0 ? params.slidesPerGroup : Math.min(Math.ceil((slidesLength - groupIndex * slidesPerColumn * params.slidesPerGroup) / slidesPerColumn), params.slidesPerGroup); row = Math.floor(slideIndexInGroup / columnsInGroup); column = slideIndexInGroup - row * columnsInGroup + groupIndex * params.slidesPerGroup; newSlideOrderIndex = column + row * slidesNumberEvenToRows / slidesPerColumn; slide.css({ '-webkit-order': newSlideOrderIndex, order: newSlideOrderIndex }); } else if (params.slidesPerColumnFill === 'column') { column = Math.floor(i / slidesPerColumn); row = i - column * slidesPerColumn; if (column > numFullColumns || column === numFullColumns && row === slidesPerColumn - 1) { row += 1; if (row >= slidesPerColumn) { row = 0; column += 1; } } } else { row = Math.floor(i / slidesPerRow); column = i - row * slidesPerRow; } slide.css(getDirectionLabel('margin-top'), row !== 0 ? params.spaceBetween && params.spaceBetween + "px" : ''); } if (slide.css('display') === 'none') continue; // eslint-disable-line if (params.slidesPerView === 'auto') { var slideStyles = getComputedStyle(slide[0]); var currentTransform = slide[0].style.transform; var currentWebKitTransform = slide[0].style.webkitTransform; if (currentTransform) { slide[0].style.transform = 'none'; } if (currentWebKitTransform) { slide[0].style.webkitTransform = 'none'; } if (params.roundLengths) { slideSize = swiper.isHorizontal() ? slide.outerWidth(true) : slide.outerHeight(true); } else { // eslint-disable-next-line var width = getDirectionPropertyValue(slideStyles, 'width'); var paddingLeft = getDirectionPropertyValue(slideStyles, 'padding-left'); var paddingRight = getDirectionPropertyValue(slideStyles, 'padding-right'); var marginLeft = getDirectionPropertyValue(slideStyles, 'margin-left'); var marginRight = getDirectionPropertyValue(slideStyles, 'margin-right'); var boxSizing = slideStyles.getPropertyValue('box-sizing'); if (boxSizing && boxSizing === 'border-box') { slideSize = width + marginLeft + marginRight; } else { var _slide$ = slide[0], clientWidth = _slide$.clientWidth, offsetWidth = _slide$.offsetWidth; slideSize = width + paddingLeft + paddingRight + marginLeft + marginRight + (offsetWidth - clientWidth); } } if (currentTransform) { slide[0].style.transform = currentTransform; } if (currentWebKitTransform) { slide[0].style.webkitTransform = currentWebKitTransform; } if (params.roundLengths) slideSize = Math.floor(slideSize); } else { slideSize = (swiperSize - (params.slidesPerView - 1) * spaceBetween) / params.slidesPerView; if (params.roundLengths) slideSize = Math.floor(slideSize); if (slides[i]) { slides[i].style[getDirectionLabel('width')] = slideSize + "px"; } } if (slides[i]) { slides[i].swiperSlideSize = slideSize; } slidesSizesGrid.push(slideSize); if (params.centeredSlides) { slidePosition = slidePosition + slideSize / 2 + prevSlideSize / 2 + spaceBetween; if (prevSlideSize === 0 && i !== 0) slidePosition = slidePosition - swiperSize / 2 - spaceBetween; if (i === 0) slidePosition = slidePosition - swiperSize / 2 - spaceBetween; if (Math.abs(slidePosition) < 1 / 1000) slidePosition = 0; if (params.roundLengths) slidePosition = Math.floor(slidePosition); if (index % params.slidesPerGroup === 0) snapGrid.push(slidePosition); slidesGrid.push(slidePosition); } else { if (params.roundLengths) slidePosition = Math.floor(slidePosition); if ((index - Math.min(swiper.params.slidesPerGroupSkip, index)) % swiper.params.slidesPerGroup === 0) snapGrid.push(slidePosition); slidesGrid.push(slidePosition); slidePosition = slidePosition + slideSize + spaceBetween; } swiper.virtualSize += slideSize + spaceBetween; prevSlideSize = slideSize; index += 1; } swiper.virtualSize = Math.max(swiper.virtualSize, swiperSize) + offsetAfter; var newSlidesGrid; if (rtl && wrongRTL && (params.effect === 'slide' || params.effect === 'coverflow')) { $wrapperEl.css({ width: swiper.virtualSize + params.spaceBetween + "px" }); } if (params.setWrapperSize) { var _$wrapperEl$css; $wrapperEl.css((_$wrapperEl$css = {}, _$wrapperEl$css[getDirectionLabel('width')] = swiper.virtualSize + params.spaceBetween + "px", _$wrapperEl$css)); } if (params.slidesPerColumn > 1) { var _$wrapperEl$css2; swiper.virtualSize = (slideSize + params.spaceBetween) * slidesNumberEvenToRows; swiper.virtualSize = Math.ceil(swiper.virtualSize / params.slidesPerColumn) - params.spaceBetween; $wrapperEl.css((_$wrapperEl$css2 = {}, _$wrapperEl$css2[getDirectionLabel('width')] = swiper.virtualSize + params.spaceBetween + "px", _$wrapperEl$css2)); if (params.centeredSlides) { newSlidesGrid = []; for (var _i = 0; _i < snapGrid.length; _i += 1) { var slidesGridItem = snapGrid[_i]; if (params.roundLengths) slidesGridItem = Math.floor(slidesGridItem); if (snapGrid[_i] < swiper.virtualSize + snapGrid[0]) newSlidesGrid.push(slidesGridItem); } snapGrid = newSlidesGrid; } } // Remove last grid elements depending on width if (!params.centeredSlides) { newSlidesGrid = []; for (var _i2 = 0; _i2 < snapGrid.length; _i2 += 1) { var _slidesGridItem = snapGrid[_i2]; if (params.roundLengths) _slidesGridItem = Math.floor(_slidesGridItem); if (snapGrid[_i2] <= swiper.virtualSize - swiperSize) { newSlidesGrid.push(_slidesGridItem); } } snapGrid = newSlidesGrid; if (Math.floor(swiper.virtualSize - swiperSize) - Math.floor(snapGrid[snapGrid.length - 1]) > 1) { snapGrid.push(swiper.virtualSize - swiperSize); } } if (snapGrid.length === 0) snapGrid = [0]; if (params.spaceBetween !== 0) { var _slides$filter$css; var key = swiper.isHorizontal() && rtl ? 'marginLeft' : getDirectionLabel('marginRight'); slides.filter(function (_, slideIndex) { if (!params.cssMode) return true; if (slideIndex === slides.length - 1) { return false; } return true; }).css((_slides$filter$css = {}, _slides$filter$css[key] = spaceBetween + "px", _slides$filter$css)); } if (params.centeredSlides && params.centeredSlidesBounds) { var allSlidesSize = 0; slidesSizesGrid.forEach(function (slideSizeValue) { allSlidesSize += slideSizeValue + (params.spaceBetween ? params.spaceBetween : 0); }); allSlidesSize -= params.spaceBetween; var maxSnap = allSlidesSize - swiperSize; snapGrid = snapGrid.map(function (snap) { if (snap < 0) return -offsetBefore; if (snap > maxSnap) return maxSnap + offsetAfter; return snap; }); } if (params.centerInsufficientSlides) { var _allSlidesSize = 0; slidesSizesGrid.forEach(function (slideSizeValue) { _allSlidesSize += slideSizeValue + (params.spaceBetween ? params.spaceBetween : 0); }); _allSlidesSize -= params.spaceBetween; if (_allSlidesSize < swiperSize) { var allSlidesOffset = (swiperSize - _allSlidesSize) / 2; snapGrid.forEach(function (snap, snapIndex) { snapGrid[snapIndex] = snap - allSlidesOffset; }); slidesGrid.forEach(function (snap, snapIndex) { slidesGrid[snapIndex] = snap + allSlidesOffset; }); } } Object.assign(swiper, { slides: slides, snapGrid: snapGrid, slidesGrid: slidesGrid, slidesSizesGrid: slidesSizesGrid }); if (slidesLength !== previousSlidesLength) { swiper.emit('slidesLengthChange'); } if (snapGrid.length !== previousSnapGridLength) { if (swiper.params.watchOverflow) swiper.checkOverflow(); swiper.emit('snapGridLengthChange'); } if (slidesGrid.length !== previousSlidesGridLength) { swiper.emit('slidesGridLengthChange'); } if (params.watchSlidesProgress || params.watchSlidesVisibility) { swiper.updateSlidesOffset(); } } function updateAutoHeight(speed) { var swiper = this; var activeSlides = []; var isVirtual = swiper.virtual && swiper.params.virtual.enabled; var newHeight = 0; var i; if (typeof speed === 'number') { swiper.setTransition(speed); } else if (speed === true) { swiper.setTransition(swiper.params.speed); } var getSlideByIndex = function getSlideByIndex(index) { if (isVirtual) { return swiper.slides.filter(function (el) { return parseInt(el.getAttribute('data-swiper-slide-index'), 10) === index; })[0]; } return swiper.slides.eq(index)[0]; }; // Find slides currently in view if (swiper.params.slidesPerView !== 'auto' && swiper.params.slidesPerView > 1) { if (swiper.params.centeredSlides) { swiper.visibleSlides.each(function (slide) { activeSlides.push(slide); }); } else { for (i = 0; i < Math.ceil(swiper.params.slidesPerView); i += 1) { var index = swiper.activeIndex + i; if (index > swiper.slides.length && !isVirtual) break; activeSlides.push(getSlideByIndex(index)); } } } else { activeSlides.push(getSlideByIndex(swiper.activeIndex)); } // Find new height from highest slide in view for (i = 0; i < activeSlides.length; i += 1) { if (typeof activeSlides[i] !== 'undefined') { var height = activeSlides[i].offsetHeight; newHeight = height > newHeight ? height : newHeight; } } // Update Height if (newHeight) swiper.$wrapperEl.css('height', newHeight + "px"); } function updateSlidesOffset() { var swiper = this; var slides = swiper.slides; for (var i = 0; i < slides.length; i += 1) { slides[i].swiperSlideOffset = swiper.isHorizontal() ? slides[i].offsetLeft : slides[i].offsetTop; } } function updateSlidesProgress(translate) { if (translate === void 0) { translate = this && this.translate || 0; } var swiper = this; var params = swiper.params; var slides = swiper.slides, rtl = swiper.rtlTranslate; if (slides.length === 0) return; if (typeof slides[0].swiperSlideOffset === 'undefined') swiper.updateSlidesOffset(); var offsetCenter = -translate; if (rtl) offsetCenter = translate; // Visible Slides slides.removeClass(params.slideVisibleClass); swiper.visibleSlidesIndexes = []; swiper.visibleSlides = []; for (var i = 0; i < slides.length; i += 1) { var slide = slides[i]; var slideProgress = (offsetCenter + (params.centeredSlides ? swiper.minTranslate() : 0) - slide.swiperSlideOffset) / (slide.swiperSlideSize + params.spaceBetween); if (params.watchSlidesVisibility || params.centeredSlides && params.autoHeight) { var slideBefore = -(offsetCenter - slide.swiperSlideOffset); var slideAfter = slideBefore + swiper.slidesSizesGrid[i]; var isVisible = slideBefore >= 0 && slideBefore < swiper.size - 1 || slideAfter > 1 && slideAfter <= swiper.size || slideBefore <= 0 && slideAfter >= swiper.size; if (isVisible) { swiper.visibleSlides.push(slide); swiper.visibleSlidesIndexes.push(i); slides.eq(i).addClass(params.slideVisibleClass); } } slide.progress = rtl ? -slideProgress : slideProgress; } swiper.visibleSlides = $(swiper.visibleSlides); } function updateProgress(translate) { var swiper = this; if (typeof translate === 'undefined') { var multiplier = swiper.rtlTranslate ? -1 : 1; // eslint-disable-next-line translate = swiper && swiper.translate && swiper.translate * multiplier || 0; } var params = swiper.params; var translatesDiff = swiper.maxTranslate() - swiper.minTranslate(); var progress = swiper.progress, isBeginning = swiper.isBeginning, isEnd = swiper.isEnd; var wasBeginning = isBeginning; var wasEnd = isEnd; if (translatesDiff === 0) { progress = 0; isBeginning = true; isEnd = true; } else { progress = (translate - swiper.minTranslate()) / translatesDiff; isBeginning = progress <= 0; isEnd = progress >= 1; } Object.assign(swiper, { progress: progress, isBeginning: isBeginning, isEnd: isEnd }); if (params.watchSlidesProgress || params.watchSlidesVisibility || params.centeredSlides && params.autoHeight) swiper.updateSlidesProgress(translate); if (isBeginning && !wasBeginning) { swiper.emit('reachBeginning toEdge'); } if (isEnd && !wasEnd) { swiper.emit('reachEnd toEdge'); } if (wasBeginning && !isBeginning || wasEnd && !isEnd) { swiper.emit('fromEdge'); } swiper.emit('progress', progress); } function updateSlidesClasses() { var swiper = this; var slides = swiper.slides, params = swiper.params, $wrapperEl = swiper.$wrapperEl, activeIndex = swiper.activeIndex, realIndex = swiper.realIndex; var isVirtual = swiper.virtual && params.virtual.enabled; slides.removeClass(params.slideActiveClass + " " + params.slideNextClass + " " + params.slidePrevClass + " " + params.slideDuplicateActiveClass + " " + params.slideDuplicateNextClass + " " + params.slideDuplicatePrevClass); var activeSlide; if (isVirtual) { activeSlide = swiper.$wrapperEl.find("." + params.slideClass + "[data-swiper-slide-index=\"" + activeIndex + "\"]"); } else { activeSlide = slides.eq(activeIndex); } // Active classes activeSlide.addClass(params.slideActiveClass); if (params.loop) { // Duplicate to all looped slides if (activeSlide.hasClass(params.slideDuplicateClass)) { $wrapperEl.children("." + params.slideClass + ":not(." + params.slideDuplicateClass + ")[data-swiper-slide-index=\"" + realIndex + "\"]").addClass(params.slideDuplicateActiveClass); } else { $wrapperEl.children("." + params.slideClass + "." + params.slideDuplicateClass + "[data-swiper-slide-index=\"" + realIndex + "\"]").addClass(params.slideDuplicateActiveClass); } } // Next Slide var nextSlide = activeSlide.nextAll("." + params.slideClass).eq(0).addClass(params.slideNextClass); if (params.loop && nextSlide.length === 0) { nextSlide = slides.eq(0); nextSlide.addClass(params.slideNextClass); } // Prev Slide var prevSlide = activeSlide.prevAll("." + params.slideClass).eq(0).addClass(params.slidePrevClass); if (params.loop && prevSlide.length === 0) { prevSlide = slides.eq(-1); prevSlide.addClass(params.slidePrevClass); } if (params.loop) { // Duplicate to all looped slides if (nextSlide.hasClass(params.slideDuplicateClass)) { $wrapperEl.children("." + params.slideClass + ":not(." + params.slideDuplicateClass + ")[data-swiper-slide-index=\"" + nextSlide.attr('data-swiper-slide-index') + "\"]").addClass(params.slideDuplicateNextClass); } else { $wrapperEl.children("." + params.slideClass + "." + params.slideDuplicateClass + "[data-swiper-slide-index=\"" + nextSlide.attr('data-swiper-slide-index') + "\"]").addClass(params.slideDuplicateNextClass); } if (prevSlide.hasClass(params.slideDuplicateClass)) { $wrapperEl.children("." + params.slideClass + ":not(." + params.slideDuplicateClass + ")[data-swiper-slide-index=\"" + prevSlide.attr('data-swiper-slide-index') + "\"]").addClass(params.slideDuplicatePrevClass); } else { $wrapperEl.children("." + params.slideClass + "." + params.slideDuplicateClass + "[data-swiper-slide-index=\"" + prevSlide.attr('data-swiper-slide-index') + "\"]").addClass(params.slideDuplicatePrevClass); } } swiper.emitSlidesClasses(); } function updateActiveIndex(newActiveIndex) { var swiper = this; var translate = swiper.rtlTranslate ? swiper.translate : -swiper.translate; var slidesGrid = swiper.slidesGrid, snapGrid = swiper.snapGrid, params = swiper.params, previousIndex = swiper.activeIndex, previousRealIndex = swiper.realIndex, previousSnapIndex = swiper.snapIndex; var activeIndex = newActiveIndex; var snapIndex; if (typeof activeIndex === 'undefined') { for (var i = 0; i < slidesGrid.length; i += 1) { if (typeof slidesGrid[i + 1] !== 'undefined') { if (translate >= slidesGrid[i] && translate < slidesGrid[i + 1] - (slidesGrid[i + 1] - slidesGrid[i]) / 2) { activeIndex = i; } else if (translate >= slidesGrid[i] && translate < slidesGrid[i + 1]) { activeIndex = i + 1; } } else if (translate >= slidesGrid[i]) { activeIndex = i; } } // Normalize slideIndex if (params.normalizeSlideIndex) { if (activeIndex < 0 || typeof activeIndex === 'undefined') activeIndex = 0; } } if (snapGrid.indexOf(translate) >= 0) { snapIndex = snapGrid.indexOf(translate); } else { var skip = Math.min(params.slidesPerGroupSkip, activeIndex); snapIndex = skip + Math.floor((activeIndex - skip) / params.slidesPerGroup); } if (snapIndex >= snapGrid.length) snapIndex = snapGrid.length - 1; if (activeIndex === previousIndex) { if (snapIndex !== previousSnapIndex) { swiper.snapIndex = snapIndex; swiper.emit('snapIndexChange'); } return; } // Get real index var realIndex = parseInt(swiper.slides.eq(activeIndex).attr('data-swiper-slide-index') || activeIndex, 10); Object.assign(swiper, { snapIndex: snapIndex, realIndex: realIndex, previousIndex: previousIndex, activeIndex: activeIndex }); swiper.emit('activeIndexChange'); swiper.emit('snapIndexChange'); if (previousRealIndex !== realIndex) { swiper.emit('realIndexChange'); } if (swiper.initialized || swiper.params.runCallbacksOnInit) { swiper.emit('slideChange'); } } function updateClickedSlide(e) { var swiper = this; var params = swiper.params; var slide = $(e.target).closest("." + params.slideClass)[0]; var slideFound = false; var slideIndex; if (slide) { for (var i = 0; i < swiper.slides.length; i += 1) { if (swiper.slides[i] === slide) { slideFound = true; slideIndex = i; break; } } } if (slide && slideFound) { swiper.clickedSlide = slide; if (swiper.virtual && swiper.params.virtual.enabled) { swiper.clickedIndex = parseInt($(slide).attr('data-swiper-slide-index'), 10); } else { swiper.clickedIndex = slideIndex; } } else { swiper.clickedSlide = undefined; swiper.clickedIndex = undefined; return; } if (params.slideToClickedSlide && swiper.clickedIndex !== undefined && swiper.clickedIndex !== swiper.activeIndex) { swiper.slideToClickedSlide(); } } var update = { updateSize: updateSize, updateSlides: updateSlides, updateAutoHeight: updateAutoHeight, updateSlidesOffset: updateSlidesOffset, updateSlidesProgress: updateSlidesProgress, updateProgress: updateProgress, updateSlidesClasses: updateSlidesClasses, updateActiveIndex: updateActiveIndex, updateClickedSlide: updateClickedSlide }; function getSwiperTranslate(axis) { if (axis === void 0) { axis = this.isHorizontal() ? 'x' : 'y'; } var swiper = this; var params = swiper.params, rtl = swiper.rtlTranslate, translate = swiper.translate, $wrapperEl = swiper.$wrapperEl; if (params.virtualTranslate) { return rtl ? -translate : translate; } if (params.cssMode) { return translate; } var currentTranslate = getTranslate($wrapperEl[0], axis); if (rtl) currentTranslate = -currentTranslate; return currentTranslate || 0; } function setTranslate(translate, byController) { var swiper = this; var rtl = swiper.rtlTranslate, params = swiper.params, $wrapperEl = swiper.$wrapperEl, wrapperEl = swiper.wrapperEl, progress = swiper.progress; var x = 0; var y = 0; var z = 0; if (swiper.isHorizontal()) { x = rtl ? -translate : translate; } else { y = translate; } if (params.roundLengths) { x = Math.floor(x); y = Math.floor(y); } if (params.cssMode) { wrapperEl[swiper.isHorizontal() ? 'scrollLeft' : 'scrollTop'] = swiper.isHorizontal() ? -x : -y; } else if (!params.virtualTranslate) { $wrapperEl.transform("translate3d(" + x + "px, " + y + "px, " + z + "px)"); } swiper.previousTranslate = swiper.translate; swiper.translate = swiper.isHorizontal() ? x : y; // Check if we need to update progress var newProgress; var translatesDiff = swiper.maxTranslate() - swiper.minTranslate(); if (translatesDiff === 0) { newProgress = 0; } else { newProgress = (translate - swiper.minTranslate()) / translatesDiff; } if (newProgress !== progress) { swiper.updateProgress(translate); } swiper.emit('setTranslate', swiper.translate, byController); } function minTranslate() { return -this.snapGrid[0]; } function maxTranslate() { return -this.snapGrid[this.snapGrid.length - 1]; } function translateTo(translate, speed, runCallbacks, translateBounds, internal) { if (translate === void 0) { translate = 0; } if (speed === void 0) { speed = this.params.speed; } if (runCallbacks === void 0) { runCallbacks = true; } if (translateBounds === void 0) { translateBounds = true; } var swiper = this; var params = swiper.params, wrapperEl = swiper.wrapperEl; if (swiper.animating && params.preventInteractionOnTransition) { return false; } var minTranslate = swiper.minTranslate(); var maxTranslate = swiper.maxTranslate(); var newTranslate; if (translateBounds && translate > minTranslate) newTranslate = minTranslate;else if (translateBounds && translate < maxTranslate) newTranslate = maxTranslate;else newTranslate = translate; // Update progress swiper.updateProgress(newTranslate); if (params.cssMode) { var isH = swiper.isHorizontal(); if (speed === 0) { wrapperEl[isH ? 'scrollLeft' : 'scrollTop'] = -newTranslate; } else { // eslint-disable-next-line if (wrapperEl.scrollTo) { var _wrapperEl$scrollTo; wrapperEl.scrollTo((_wrapperEl$scrollTo = {}, _wrapperEl$scrollTo[isH ? 'left' : 'top'] = -newTranslate, _wrapperEl$scrollTo.behavior = 'smooth', _wrapperEl$scrollTo)); } else { wrapperEl[isH ? 'scrollLeft' : 'scrollTop'] = -newTranslate; } } return true; } if (speed === 0) { swiper.setTransition(0); swiper.setTranslate(newTranslate); if (runCallbacks) { swiper.emit('beforeTransitionStart', speed, internal); swiper.emit('transitionEnd'); } } else { swiper.setTransition(speed); swiper.setTranslate(newTranslate); if (runCallbacks) { swiper.emit('beforeTransitionStart', speed, internal); swiper.emit('transitionStart'); } if (!swiper.animating) { swiper.animating = true; if (!swiper.onTranslateToWrapperTransitionEnd) { swiper.onTranslateToWrapperTransitionEnd = function transitionEnd(e) { if (!swiper || swiper.destroyed) return; if (e.target !== this) return; swiper.$wrapperEl[0].removeEventListener('transitionend', swiper.onTranslateToWrapperTransitionEnd); swiper.$wrapperEl[0].removeEventListener('webkitTransitionEnd', swiper.onTranslateToWrapperTransitionEnd); swiper.onTranslateToWrapperTransitionEnd = null; delete swiper.onTranslateToWrapperTransitionEnd; if (runCallbacks) { swiper.emit('transitionEnd'); } }; } swiper.$wrapperEl[0].addEventListener('transitionend', swiper.onTranslateToWrapperTransitionEnd); swiper.$wrapperEl[0].addEventListener('webkitTransitionEnd', swiper.onTranslateToWrapperTransitionEnd); } } return true; } var translate = { getTranslate: getSwiperTranslate, setTranslate: setTranslate, minTranslate: minTranslate, maxTranslate: maxTranslate, translateTo: translateTo }; function setTransition(duration, byController) { var swiper = this; if (!swiper.params.cssMode) { swiper.$wrapperEl.transition(duration); } swiper.emit('setTransition', duration, byController); } function transitionStart(runCallbacks, direction) { if (runCallbacks === void 0) { runCallbacks = true; } var swiper = this; var activeIndex = swiper.activeIndex, params = swiper.params, previousIndex = swiper.previousIndex; if (params.cssMode) return; if (params.autoHeight) { swiper.updateAutoHeight(); } var dir = direction; if (!dir) { if (activeIndex > previousIndex) dir = 'next';else if (activeIndex < previousIndex) dir = 'prev';else dir = 'reset'; } swiper.emit('transitionStart'); if (runCallbacks && activeIndex !== previousIndex) { if (dir === 'reset') { swiper.emit('slideResetTransitionStart'); return; } swiper.emit('slideChangeTransitionStart'); if (dir === 'next') { swiper.emit('slideNextTransitionStart'); } else { swiper.emit('slidePrevTransitionStart'); } } } function transitionEnd(runCallbacks, direction) { if (runCallbacks === void 0) { runCallbacks = true; } var swiper = this; var activeIndex = swiper.activeIndex, previousIndex = swiper.previousIndex, params = swiper.params; swiper.animating = false; if (params.cssMode) return; swiper.setTransition(0); var dir = direction; if (!dir) { if (activeIndex > previousIndex) dir = 'next';else if (activeIndex < previousIndex) dir = 'prev';else dir = 'reset'; } swiper.emit('transitionEnd'); if (runCallbacks && activeIndex !== previousIndex) { if (dir === 'reset') { swiper.emit('slideResetTransitionEnd'); return; } swiper.emit('slideChangeTransitionEnd'); if (dir === 'next') { swiper.emit('slideNextTransitionEnd'); } else { swiper.emit('slidePrevTransitionEnd'); } } } var transition = { setTransition: setTransition, transitionStart: transitionStart, transitionEnd: transitionEnd }; function slideTo(index, speed, runCallbacks, internal, initial) { if (index === void 0) { index = 0; } if (speed === void 0) { speed = this.params.speed; } if (runCallbacks === void 0) { runCallbacks = true; } if (typeof index !== 'number' && typeof index !== 'string') { throw new Error("The 'index' argument cannot have type other than 'number' or 'string'. [" + typeof index + "] given."); } if (typeof index === 'string') { /** * The `index` argument converted from `string` to `number`. * @type {number} */ var indexAsNumber = parseInt(index, 10); /** * Determines whether the `index` argument is a valid `number` * after being converted from the `string` type. * @type {boolean} */ var isValidNumber = isFinite(indexAsNumber); if (!isValidNumber) { throw new Error("The passed-in 'index' (string) couldn't be converted to 'number'. [" + index + "] given."); } // Knowing that the converted `index` is a valid number, // we can update the original argument's value. index = indexAsNumber; } var swiper = this; var slideIndex = index; if (slideIndex < 0) slideIndex = 0; var params = swiper.params, snapGrid = swiper.snapGrid, slidesGrid = swiper.slidesGrid, previousIndex = swiper.previousIndex, activeIndex = swiper.activeIndex, rtl = swiper.rtlTranslate, wrapperEl = swiper.wrapperEl, enabled = swiper.enabled; if (swiper.animating && params.preventInteractionOnTransition || !enabled && !internal && !initial) { return false; } var skip = Math.min(swiper.params.slidesPerGroupSkip, slideIndex); var snapIndex = skip + Math.floor((slideIndex - skip) / swiper.params.slidesPerGroup); if (snapIndex >= snapGrid.length) snapIndex = snapGrid.length - 1; if ((activeIndex || params.initialSlide || 0) === (previousIndex || 0) && runCallbacks) { swiper.emit('beforeSlideChangeStart'); } var translate = -snapGrid[snapIndex]; // Update progress swiper.updateProgress(translate); // Normalize slideIndex if (params.normalizeSlideIndex) { for (var i = 0; i < slidesGrid.length; i += 1) { var normalizedTranslate = -Math.floor(translate * 100); var normalizedGird = Math.floor(slidesGrid[i] * 100); var normalizedGridNext = Math.floor(slidesGrid[i + 1] * 100); if (typeof slidesGrid[i + 1] !== 'undefined') { if (normalizedTranslate >= normalizedGird && normalizedTranslate < normalizedGridNext - (normalizedGridNext - normalizedGird) / 2) { slideIndex = i; } else if (normalizedTranslate >= normalizedGird && normalizedTranslate < normalizedGridNext) { slideIndex = i + 1; } } else if (normalizedTranslate >= normalizedGird) { slideIndex = i; } } } // Directions locks if (swiper.initialized && slideIndex !== activeIndex) { if (!swiper.allowSlideNext && translate < swiper.translate && translate < swiper.minTranslate()) { return false; } if (!swiper.allowSlidePrev && translate > swiper.translate && translate > swiper.maxTranslate()) { if ((activeIndex || 0) !== slideIndex) return false; } } var direction; if (slideIndex > activeIndex) direction = 'next';else if (slideIndex < activeIndex) direction = 'prev';else direction = 'reset'; // Update Index if (rtl && -translate === swiper.translate || !rtl && translate === swiper.translate) { swiper.updateActiveIndex(slideIndex); // Update Height if (params.autoHeight) { swiper.updateAutoHeight(); } swiper.updateSlidesClasses(); if (params.effect !== 'slide') { swiper.setTranslate(translate); } if (direction !== 'reset') { swiper.transitionStart(runCallbacks, direction); swiper.transitionEnd(runCallbacks, direction); } return false; } if (params.cssMode) { var isH = swiper.isHorizontal(); var t = -translate; if (rtl) { t = wrapperEl.scrollWidth - wrapperEl.offsetWidth - t; } if (speed === 0) { wrapperEl[isH ? 'scrollLeft' : 'scrollTop'] = t; } else { // eslint-disable-next-line if (wrapperEl.scrollTo) { var _wrapperEl$scrollTo; wrapperEl.scrollTo((_wrapperEl$scrollTo = {}, _wrapperEl$scrollTo[isH ? 'left' : 'top'] = t, _wrapperEl$scrollTo.behavior = 'smooth', _wrapperEl$scrollTo)); } else { wrapperEl[isH ? 'scrollLeft' : 'scrollTop'] = t; } } return true; } if (speed === 0) { swiper.setTransition(0); swiper.setTranslate(translate); swiper.updateActiveIndex(slideIndex); swiper.updateSlidesClasses(); swiper.emit('beforeTransitionStart', speed, internal); swiper.transitionStart(runCallbacks, direction); swiper.transitionEnd(runCallbacks, direction); } else { swiper.setTransition(speed); swiper.setTranslate(translate); swiper.updateActiveIndex(slideIndex); swiper.updateSlidesClasses(); swiper.emit('beforeTransitionStart', speed, internal); swiper.transitionStart(runCallbacks, direction); if (!swiper.animating) { swiper.animating = true; if (!swiper.onSlideToWrapperTransitionEnd) { swiper.onSlideToWrapperTransitionEnd = function transitionEnd(e) { if (!swiper || swiper.destroyed) return; if (e.target !== this) return; swiper.$wrapperEl[0].removeEventListener('transitionend', swiper.onSlideToWrapperTransitionEnd); swiper.$wrapperEl[0].removeEventListener('webkitTransitionEnd', swiper.onSlideToWrapperTransitionEnd); swiper.onSlideToWrapperTransitionEnd = null; delete swiper.onSlideToWrapperTransitionEnd; swiper.transitionEnd(runCallbacks, direction); }; } swiper.$wrapperEl[0].addEventListener('transitionend', swiper.onSlideToWrapperTransitionEnd); swiper.$wrapperEl[0].addEventListener('webkitTransitionEnd', swiper.onSlideToWrapperTransitionEnd); } } return true; } function slideToLoop(index, speed, runCallbacks, internal) { if (index === void 0) { index = 0; } if (speed === void 0) { speed = this.params.speed; } if (runCallbacks === void 0) { runCallbacks = true; } var swiper = this; var newIndex = index; if (swiper.params.loop) { newIndex += swiper.loopedSlides; } return swiper.slideTo(newIndex, speed, runCallbacks, internal); } /* eslint no-unused-vars: "off" */ function slideNext(speed, runCallbacks, internal) { if (speed === void 0) { speed = this.params.speed; } if (runCallbacks === void 0) { runCallbacks = true; } var swiper = this; var params = swiper.params, animating = swiper.animating, enabled = swiper.enabled; if (!enabled) return swiper; var increment = swiper.activeIndex < params.slidesPerGroupSkip ? 1 : params.slidesPerGroup; if (params.loop) { if (animating && params.loopPreventsSlide) return false; swiper.loopFix(); // eslint-disable-next-line swiper._clientLeft = swiper.$wrapperEl[0].clientLeft; } return swiper.slideTo(swiper.activeIndex + increment, speed, runCallbacks, internal); } /* eslint no-unused-vars: "off" */ function slidePrev(speed, runCallbacks, internal) { if (speed === void 0) { speed = this.params.speed; } if (runCallbacks === void 0) { runCallbacks = true; } var swiper = this; var params = swiper.params, animating = swiper.animating, snapGrid = swiper.snapGrid, slidesGrid = swiper.slidesGrid, rtlTranslate = swiper.rtlTranslate, enabled = swiper.enabled; if (!enabled) return swiper; if (params.loop) { if (animating && params.loopPreventsSlide) return false; swiper.loopFix(); // eslint-disable-next-line swiper._clientLeft = swiper.$wrapperEl[0].clientLeft; } var translate = rtlTranslate ? swiper.translate : -swiper.translate; function normalize(val) { if (val < 0) return -Math.floor(Math.abs(val)); return Math.floor(val); } var normalizedTranslate = normalize(translate); var normalizedSnapGrid = snapGrid.map(function (val) { return normalize(val); }); var prevSnap = snapGrid[normalizedSnapGrid.indexOf(normalizedTranslate) - 1]; if (typeof prevSnap === 'undefined' && params.cssMode) { snapGrid.forEach(function (snap) { if (!prevSnap && normalizedTranslate >= snap) prevSnap = snap; }); } var prevIndex; if (typeof prevSnap !== 'undefined') { prevIndex = slidesGrid.indexOf(prevSnap); if (prevIndex < 0) prevIndex = swiper.activeIndex - 1; } return swiper.slideTo(prevIndex, speed, runCallbacks, internal); } /* eslint no-unused-vars: "off" */ function slideReset(speed, runCallbacks, internal) { if (speed === void 0) { speed = this.params.speed; } if (runCallbacks === void 0) { runCallbacks = true; } var swiper = this; return swiper.slideTo(swiper.activeIndex, speed, runCallbacks, internal); } /* eslint no-unused-vars: "off" */ function slideToClosest(speed, runCallbacks, internal, threshold) { if (speed === void 0) { speed = this.params.speed; } if (runCallbacks === void 0) { runCallbacks = true; } if (threshold === void 0) { threshold = 0.5; } var swiper = this; var index = swiper.activeIndex; var skip = Math.min(swiper.params.slidesPerGroupSkip, index); var snapIndex = skip + Math.floor((index - skip) / swiper.params.slidesPerGroup); var translate = swiper.rtlTranslate ? swiper.translate : -swiper.translate; if (translate >= swiper.snapGrid[snapIndex]) { // The current translate is on or after the current snap index, so the choice // is between the current index and the one after it. var currentSnap = swiper.snapGrid[snapIndex]; var nextSnap = swiper.snapGrid[snapIndex + 1]; if (translate - currentSnap > (nextSnap - currentSnap) * threshold) { index += swiper.params.slidesPerGroup; } } else { // The current translate is before the current snap index, so the choice // is between the current index and the one before it. var prevSnap = swiper.snapGrid[snapIndex - 1]; var _currentSnap = swiper.snapGrid[snapIndex]; if (translate - prevSnap <= (_currentSnap - prevSnap) * threshold) { index -= swiper.params.slidesPerGroup; } } index = Math.max(index, 0); index = Math.min(index, swiper.slidesGrid.length - 1); return swiper.slideTo(index, speed, runCallbacks, internal); } function slideToClickedSlide() { var swiper = this; var params = swiper.params, $wrapperEl = swiper.$wrapperEl; var slidesPerView = params.slidesPerView === 'auto' ? swiper.slidesPerViewDynamic() : params.slidesPerView; var slideToIndex = swiper.clickedIndex; var realIndex; if (params.loop) { if (swiper.animating) return; realIndex = parseInt($(swiper.clickedSlide).attr('data-swiper-slide-index'), 10); if (params.centeredSlides) { if (slideToIndex < swiper.loopedSlides - slidesPerView / 2 || slideToIndex > swiper.slides.length - swiper.loopedSlides + slidesPerView / 2) { swiper.loopFix(); slideToIndex = $wrapperEl.children("." + params.slideClass + "[data-swiper-slide-index=\"" + realIndex + "\"]:not(." + params.slideDuplicateClass + ")").eq(0).index(); nextTick(function () { swiper.slideTo(slideToIndex); }); } else { swiper.slideTo(slideToIndex); } } else if (slideToIndex > swiper.slides.length - slidesPerView) { swiper.loopFix(); slideToIndex = $wrapperEl.children("." + params.slideClass + "[data-swiper-slide-index=\"" + realIndex + "\"]:not(." + params.slideDuplicateClass + ")").eq(0).index(); nextTick(function () { swiper.slideTo(slideToIndex); }); } else { swiper.slideTo(slideToIndex); } } else { swiper.slideTo(slideToIndex); } } var slide = { slideTo: slideTo, slideToLoop: slideToLoop, slideNext: slideNext, slidePrev: slidePrev, slideReset: slideReset, slideToClosest: slideToClosest, slideToClickedSlide: slideToClickedSlide }; function loopCreate() { var swiper = this; var document = getDocument(); var params = swiper.params, $wrapperEl = swiper.$wrapperEl; // Remove duplicated slides $wrapperEl.children("." + params.slideClass + "." + params.slideDuplicateClass).remove(); var slides = $wrapperEl.children("." + params.slideClass); if (params.loopFillGroupWithBlank) { var blankSlidesNum = params.slidesPerGroup - slides.length % params.slidesPerGroup; if (blankSlidesNum !== params.slidesPerGroup) { for (var i = 0; i < blankSlidesNum; i += 1) { var blankNode = $(document.createElement('div')).addClass(params.slideClass + " " + params.slideBlankClass); $wrapperEl.append(blankNode); } slides = $wrapperEl.children("." + params.slideClass); } } if (params.slidesPerView === 'auto' && !params.loopedSlides) params.loopedSlides = slides.length; swiper.loopedSlides = Math.ceil(parseFloat(params.loopedSlides || params.slidesPerView, 10)); swiper.loopedSlides += params.loopAdditionalSlides; if (swiper.loopedSlides > slides.length) { swiper.loopedSlides = slides.length; } var prependSlides = []; var appendSlides = []; slides.each(function (el, index) { var slide = $(el); if (index < swiper.loopedSlides) { appendSlides.push(el); } if (index < slides.length && index >= slides.length - swiper.loopedSlides) { prependSlides.push(el); } slide.attr('data-swiper-slide-index', index); }); for (var _i = 0; _i < appendSlides.length; _i += 1) { $wrapperEl.append($(appendSlides[_i].cloneNode(true)).addClass(params.slideDuplicateClass)); } for (var _i2 = prependSlides.length - 1; _i2 >= 0; _i2 -= 1) { $wrapperEl.prepend($(prependSlides[_i2].cloneNode(true)).addClass(params.slideDuplicateClass)); } } function loopFix() { var swiper = this; swiper.emit('beforeLoopFix'); var activeIndex = swiper.activeIndex, slides = swiper.slides, loopedSlides = swiper.loopedSlides, allowSlidePrev = swiper.allowSlidePrev, allowSlideNext = swiper.allowSlideNext, snapGrid = swiper.snapGrid, rtl = swiper.rtlTranslate; var newIndex; swiper.allowSlidePrev = true; swiper.allowSlideNext = true; var snapTranslate = -snapGrid[activeIndex]; var diff = snapTranslate - swiper.getTranslate(); // Fix For Negative Oversliding if (activeIndex < loopedSlides) { newIndex = slides.length - loopedSlides * 3 + activeIndex; newIndex += loopedSlides; var slideChanged = swiper.slideTo(newIndex, 0, false, true); if (slideChanged && diff !== 0) { swiper.setTranslate((rtl ? -swiper.translate : swiper.translate) - diff); } } else if (activeIndex >= slides.length - loopedSlides) { // Fix For Positive Oversliding newIndex = -slides.length + activeIndex + loopedSlides; newIndex += loopedSlides; var _slideChanged = swiper.slideTo(newIndex, 0, false, true); if (_slideChanged && diff !== 0) { swiper.setTranslate((rtl ? -swiper.translate : swiper.translate) - diff); } } swiper.allowSlidePrev = allowSlidePrev; swiper.allowSlideNext = allowSlideNext; swiper.emit('loopFix'); } function loopDestroy() { var swiper = this; var $wrapperEl = swiper.$wrapperEl, params = swiper.params, slides = swiper.slides; $wrapperEl.children("." + params.slideClass + "." + params.slideDuplicateClass + ",." + params.slideClass + "." + params.slideBlankClass).remove(); slides.removeAttr('data-swiper-slide-index'); } var loop = { loopCreate: loopCreate, loopFix: loopFix, loopDestroy: loopDestroy }; function setGrabCursor(moving) { var swiper = this; if (swiper.support.touch || !swiper.params.simulateTouch || swiper.params.watchOverflow && swiper.isLocked || swiper.params.cssMode) return; var el = swiper.params.touchEventsTarget === 'container' ? swiper.el : swiper.wrapperEl; el.style.cursor = 'move'; el.style.cursor = moving ? '-webkit-grabbing' : '-webkit-grab'; el.style.cursor = moving ? '-moz-grabbin' : '-moz-grab'; el.style.cursor = moving ? 'grabbing' : 'grab'; } function unsetGrabCursor() { var swiper = this; if (swiper.support.touch || swiper.params.watchOverflow && swiper.isLocked || swiper.params.cssMode) { return; } swiper.el.style.cursor = ''; } var grabCursor = { setGrabCursor: setGrabCursor, unsetGrabCursor: unsetGrabCursor }; function appendSlide(slides) { var swiper = this; var $wrapperEl = swiper.$wrapperEl, params = swiper.params; if (params.loop) { swiper.loopDestroy(); } if (typeof slides === 'object' && 'length' in slides) { for (var i = 0; i < slides.length; i += 1) { if (slides[i]) $wrapperEl.append(slides[i]); } } else { $wrapperEl.append(slides); } if (params.loop) { swiper.loopCreate(); } if (!params.observer) { swiper.update(); } } function prependSlide(slides) { var swiper = this; var params = swiper.params, $wrapperEl = swiper.$wrapperEl, activeIndex = swiper.activeIndex; if (params.loop) { swiper.loopDestroy(); } var newActiveIndex = activeIndex + 1; if (typeof slides === 'object' && 'length' in slides) { for (var i = 0; i < slides.length; i += 1) { if (slides[i]) $wrapperEl.prepend(slides[i]); } newActiveIndex = activeIndex + slides.length; } else { $wrapperEl.prepend(slides); } if (params.loop) { swiper.loopCreate(); } if (!params.observer) { swiper.update(); } swiper.slideTo(newActiveIndex, 0, false); } function addSlide(index, slides) { var swiper = this; var $wrapperEl = swiper.$wrapperEl, params = swiper.params, activeIndex = swiper.activeIndex; var activeIndexBuffer = activeIndex; if (params.loop) { activeIndexBuffer -= swiper.loopedSlides; swiper.loopDestroy(); swiper.slides = $wrapperEl.children("." + params.slideClass); } var baseLength = swiper.slides.length; if (index <= 0) { swiper.prependSlide(slides); return; } if (index >= baseLength) { swiper.appendSlide(slides); return; } var newActiveIndex = activeIndexBuffer > index ? activeIndexBuffer + 1 : activeIndexBuffer; var slidesBuffer = []; for (var i = baseLength - 1; i >= index; i -= 1) { var currentSlide = swiper.slides.eq(i); currentSlide.remove(); slidesBuffer.unshift(currentSlide); } if (typeof slides === 'object' && 'length' in slides) { for (var _i = 0; _i < slides.length; _i += 1) { if (slides[_i]) $wrapperEl.append(slides[_i]); } newActiveIndex = activeIndexBuffer > index ? activeIndexBuffer + slides.length : activeIndexBuffer; } else { $wrapperEl.append(slides); } for (var _i2 = 0; _i2 < slidesBuffer.length; _i2 += 1) { $wrapperEl.append(slidesBuffer[_i2]); } if (params.loop) { swiper.loopCreate(); } if (!params.observer) { swiper.update(); } if (params.loop) { swiper.slideTo(newActiveIndex + swiper.loopedSlides, 0, false); } else { swiper.slideTo(newActiveIndex, 0, false); } } function removeSlide(slidesIndexes) { var swiper = this; var params = swiper.params, $wrapperEl = swiper.$wrapperEl, activeIndex = swiper.activeIndex; var activeIndexBuffer = activeIndex; if (params.loop) { activeIndexBuffer -= swiper.loopedSlides; swiper.loopDestroy(); swiper.slides = $wrapperEl.children("." + params.slideClass); } var newActiveIndex = activeIndexBuffer; var indexToRemove; if (typeof slidesIndexes === 'object' && 'length' in slidesIndexes) { for (var i = 0; i < slidesIndexes.length; i += 1) { indexToRemove = slidesIndexes[i]; if (swiper.slides[indexToRemove]) swiper.slides.eq(indexToRemove).remove(); if (indexToRemove < newActiveIndex) newActiveIndex -= 1; } newActiveIndex = Math.max(newActiveIndex, 0); } else { indexToRemove = slidesIndexes; if (swiper.slides[indexToRemove]) swiper.slides.eq(indexToRemove).remove(); if (indexToRemove < newActiveIndex) newActiveIndex -= 1; newActiveIndex = Math.max(newActiveIndex, 0); } if (params.loop) { swiper.loopCreate(); } if (!params.observer) { swiper.update(); } if (params.loop) { swiper.slideTo(newActiveIndex + swiper.loopedSlides, 0, false); } else { swiper.slideTo(newActiveIndex, 0, false); } } function removeAllSlides() { var swiper = this; var slidesIndexes = []; for (var i = 0; i < swiper.slides.length; i += 1) { slidesIndexes.push(i); } swiper.removeSlide(slidesIndexes); } var manipulation = { appendSlide: appendSlide, prependSlide: prependSlide, addSlide: addSlide, removeSlide: removeSlide, removeAllSlides: removeAllSlides }; function closestElement(selector, base) { if (base === void 0) { base = this; } function __closestFrom(el) { if (!el || el === getDocument() || el === getWindow()) return null; if (el.assignedSlot) el = el.assignedSlot; var found = el.closest(selector); return found || __closestFrom(el.getRootNode().host); } return __closestFrom(base); } function onTouchStart(event) { var swiper = this; var document = getDocument(); var window = getWindow(); var data = swiper.touchEventsData; var params = swiper.params, touches = swiper.touches, enabled = swiper.enabled; if (!enabled) return; if (swiper.animating && params.preventInteractionOnTransition) { return; } var e = event; if (e.originalEvent) e = e.originalEvent; var $targetEl = $(e.target); if (params.touchEventsTarget === 'wrapper') { if (!$targetEl.closest(swiper.wrapperEl).length) return; } data.isTouchEvent = e.type === 'touchstart'; if (!data.isTouchEvent && 'which' in e && e.which === 3) return; if (!data.isTouchEvent && 'button' in e && e.button > 0) return; if (data.isTouched && data.isMoved) return; // change target el for shadow root component var swipingClassHasValue = !!params.noSwipingClass && params.noSwipingClass !== ''; if (swipingClassHasValue && e.target && e.target.shadowRoot && event.path && event.path[0]) { $targetEl = $(event.path[0]); } var noSwipingSelector = params.noSwipingSelector ? params.noSwipingSelector : "." + params.noSwipingClass; var isTargetShadow = !!(e.target && e.target.shadowRoot); // use closestElement for shadow root element to get the actual closest for nested shadow root element if (params.noSwiping && (isTargetShadow ? closestElement(noSwipingSelector, e.target) : $targetEl.closest(noSwipingSelector)[0])) { swiper.allowClick = true; return; } if (params.swipeHandler) { if (!$targetEl.closest(params.swipeHandler)[0]) return; } touches.currentX = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX; touches.currentY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY; var startX = touches.currentX; var startY = touches.currentY; // Do NOT start if iOS edge swipe is detected. Otherwise iOS app cannot swipe-to-go-back anymore var edgeSwipeDetection = params.edgeSwipeDetection || params.iOSEdgeSwipeDetection; var edgeSwipeThreshold = params.edgeSwipeThreshold || params.iOSEdgeSwipeThreshold; if (edgeSwipeDetection && (startX <= edgeSwipeThreshold || startX >= window.innerWidth - edgeSwipeThreshold)) { if (edgeSwipeDetection === 'prevent') { event.preventDefault(); } else { return; } } Object.assign(data, { isTouched: true, isMoved: false, allowTouchCallbacks: true, isScrolling: undefined, startMoving: undefined }); touches.startX = startX; touches.startY = startY; data.touchStartTime = now(); swiper.allowClick = true; swiper.updateSize(); swiper.swipeDirection = undefined; if (params.threshold > 0) data.allowThresholdMove = false; if (e.type !== 'touchstart') { var preventDefault = true; if ($targetEl.is(data.focusableElements)) preventDefault = false; if (document.activeElement && $(document.activeElement).is(data.focusableElements) && document.activeElement !== $targetEl[0]) { document.activeElement.blur(); } var shouldPreventDefault = preventDefault && swiper.allowTouchMove && params.touchStartPreventDefault; if ((params.touchStartForcePreventDefault || shouldPreventDefault) && !$targetEl[0].isContentEditable) { e.preventDefault(); } } swiper.emit('touchStart', e); } function onTouchMove(event) { var document = getDocument(); var swiper = this; var data = swiper.touchEventsData; var params = swiper.params, touches = swiper.touches, rtl = swiper.rtlTranslate, enabled = swiper.enabled; if (!enabled) return; var e = event; if (e.originalEvent) e = e.originalEvent; if (!data.isTouched) { if (data.startMoving && data.isScrolling) { swiper.emit('touchMoveOpposite', e); } return; } if (data.isTouchEvent && e.type !== 'touchmove') return; var targetTouch = e.type === 'touchmove' && e.targetTouches && (e.targetTouches[0] || e.changedTouches[0]); var pageX = e.type === 'touchmove' ? targetTouch.pageX : e.pageX; var pageY = e.type === 'touchmove' ? targetTouch.pageY : e.pageY; if (e.preventedByNestedSwiper) { touches.startX = pageX; touches.startY = pageY; return; } if (!swiper.allowTouchMove) { // isMoved = true; swiper.allowClick = false; if (data.isTouched) { Object.assign(touches, { startX: pageX, startY: pageY, currentX: pageX, currentY: pageY }); data.touchStartTime = now(); } return; } if (data.isTouchEvent && params.touchReleaseOnEdges && !params.loop) { if (swiper.isVertical()) { // Vertical if (pageY < touches.startY && swiper.translate <= swiper.maxTranslate() || pageY > touches.startY && swiper.translate >= swiper.minTranslate()) { data.isTouched = false; data.isMoved = false; return; } } else if (pageX < touches.startX && swiper.translate <= swiper.maxTranslate() || pageX > touches.startX && swiper.translate >= swiper.minTranslate()) { return; } } if (data.isTouchEvent && document.activeElement) { if (e.target === document.activeElement && $(e.target).is(data.focusableElements)) { data.isMoved = true; swiper.allowClick = false; return; } } if (data.allowTouchCallbacks) { swiper.emit('touchMove', e); } if (e.targetTouches && e.targetTouches.length > 1) return; touches.currentX = pageX; touches.currentY = pageY; var diffX = touches.currentX - touches.startX; var diffY = touches.currentY - touches.startY; if (swiper.params.threshold && Math.sqrt(Math.pow(diffX, 2) + Math.pow(diffY, 2)) < swiper.params.threshold) return; if (typeof data.isScrolling === 'undefined') { var touchAngle; if (swiper.isHorizontal() && touches.currentY === touches.startY || swiper.isVertical() && touches.currentX === touches.startX) { data.isScrolling = false; } else { // eslint-disable-next-line if (diffX * diffX + diffY * diffY >= 25) { touchAngle = Math.atan2(Math.abs(diffY), Math.abs(diffX)) * 180 / Math.PI; data.isScrolling = swiper.isHorizontal() ? touchAngle > params.touchAngle : 90 - touchAngle > params.touchAngle; } } } if (data.isScrolling) { swiper.emit('touchMoveOpposite', e); } if (typeof data.startMoving === 'undefined') { if (touches.currentX !== touches.startX || touches.currentY !== touches.startY) { data.startMoving = true; } } if (data.isScrolling) { data.isTouched = false; return; } if (!data.startMoving) { return; } swiper.allowClick = false; if (!params.cssMode && e.cancelable) { e.preventDefault(); } if (params.touchMoveStopPropagation && !params.nested) { e.stopPropagation(); } if (!data.isMoved) { if (params.loop) { swiper.loopFix(); } data.startTranslate = swiper.getTranslate(); swiper.setTransition(0); if (swiper.animating) { swiper.$wrapperEl.trigger('webkitTransitionEnd transitionend'); } data.allowMomentumBounce = false; // Grab Cursor if (params.grabCursor && (swiper.allowSlideNext === true || swiper.allowSlidePrev === true)) { swiper.setGrabCursor(true); } swiper.emit('sliderFirstMove', e); } swiper.emit('sliderMove', e); data.isMoved = true; var diff = swiper.isHorizontal() ? diffX : diffY; touches.diff = diff; diff *= params.touchRatio; if (rtl) diff = -diff; swiper.swipeDirection = diff > 0 ? 'prev' : 'next'; data.currentTranslate = diff + data.startTranslate; var disableParentSwiper = true; var resistanceRatio = params.resistanceRatio; if (params.touchReleaseOnEdges) { resistanceRatio = 0; } if (diff > 0 && data.currentTranslate > swiper.minTranslate()) { disableParentSwiper = false; if (params.resistance) data.currentTranslate = swiper.minTranslate() - 1 + Math.pow(-swiper.minTranslate() + data.startTranslate + diff, resistanceRatio); } else if (diff < 0 && data.currentTranslate < swiper.maxTranslate()) { disableParentSwiper = false; if (params.resistance) data.currentTranslate = swiper.maxTranslate() + 1 - Math.pow(swiper.maxTranslate() - data.startTranslate - diff, resistanceRatio); } if (disableParentSwiper) { e.preventedByNestedSwiper = true; } // Directions locks if (!swiper.allowSlideNext && swiper.swipeDirection === 'next' && data.currentTranslate < data.startTranslate) { data.currentTranslate = data.startTranslate; } if (!swiper.allowSlidePrev && swiper.swipeDirection === 'prev' && data.currentTranslate > data.startTranslate) { data.currentTranslate = data.startTranslate; } if (!swiper.allowSlidePrev && !swiper.allowSlideNext) { data.currentTranslate = data.startTranslate; } // Threshold if (params.threshold > 0) { if (Math.abs(diff) > params.threshold || data.allowThresholdMove) { if (!data.allowThresholdMove) { data.allowThresholdMove = true; touches.startX = touches.currentX; touches.startY = touches.currentY; data.currentTranslate = data.startTranslate; touches.diff = swiper.isHorizontal() ? touches.currentX - touches.startX : touches.currentY - touches.startY; return; } } else { data.currentTranslate = data.startTranslate; return; } } if (!params.followFinger || params.cssMode) return; // Update active index in free mode if (params.freeMode && params.freeMode.enabled || params.watchSlidesProgress || params.watchSlidesVisibility) { swiper.updateActiveIndex(); swiper.updateSlidesClasses(); } if (swiper.params.freeMode && params.freeMode.enabled) { swiper.freeMode.onTouchMove(); } // Update progress swiper.updateProgress(data.currentTranslate); // Update translate swiper.setTranslate(data.currentTranslate); } function onTouchEnd(event) { var swiper = this; var data = swiper.touchEventsData; var params = swiper.params, touches = swiper.touches, rtl = swiper.rtlTranslate, slidesGrid = swiper.slidesGrid, enabled = swiper.enabled; if (!enabled) return; var e = event; if (e.originalEvent) e = e.originalEvent; if (data.allowTouchCallbacks) { swiper.emit('touchEnd', e); } data.allowTouchCallbacks = false; if (!data.isTouched) { if (data.isMoved && params.grabCursor) { swiper.setGrabCursor(false); } data.isMoved = false; data.startMoving = false; return; } // Return Grab Cursor if (params.grabCursor && data.isMoved && data.isTouched && (swiper.allowSlideNext === true || swiper.allowSlidePrev === true)) { swiper.setGrabCursor(false); } // Time diff var touchEndTime = now(); var timeDiff = touchEndTime - data.touchStartTime; // Tap, doubleTap, Click if (swiper.allowClick) { swiper.updateClickedSlide(e); swiper.emit('tap click', e); if (timeDiff < 300 && touchEndTime - data.lastClickTime < 300) { swiper.emit('doubleTap doubleClick', e); } } data.lastClickTime = now(); nextTick(function () { if (!swiper.destroyed) swiper.allowClick = true; }); if (!data.isTouched || !data.isMoved || !swiper.swipeDirection || touches.diff === 0 || data.currentTranslate === data.startTranslate) { data.isTouched = false; data.isMoved = false; data.startMoving = false; return; } data.isTouched = false; data.isMoved = false; data.startMoving = false; var currentPos; if (params.followFinger) { currentPos = rtl ? swiper.translate : -swiper.translate; } else { currentPos = -data.currentTranslate; } if (params.cssMode) { return; } if (swiper.params.freeMode && params.freeMode.enabled) { swiper.freeMode.onTouchEnd({ currentPos: currentPos }); return; } // Find current slide var stopIndex = 0; var groupSize = swiper.slidesSizesGrid[0]; for (var i = 0; i < slidesGrid.length; i += i < params.slidesPerGroupSkip ? 1 : params.slidesPerGroup) { var _increment = i < params.slidesPerGroupSkip - 1 ? 1 : params.slidesPerGroup; if (typeof slidesGrid[i + _increment] !== 'undefined') { if (currentPos >= slidesGrid[i] && currentPos < slidesGrid[i + _increment]) { stopIndex = i; groupSize = slidesGrid[i + _increment] - slidesGrid[i]; } } else if (currentPos >= slidesGrid[i]) { stopIndex = i; groupSize = slidesGrid[slidesGrid.length - 1] - slidesGrid[slidesGrid.length - 2]; } } // Find current slide size var ratio = (currentPos - slidesGrid[stopIndex]) / groupSize; var increment = stopIndex < params.slidesPerGroupSkip - 1 ? 1 : params.slidesPerGroup; if (timeDiff > params.longSwipesMs) { // Long touches if (!params.longSwipes) { swiper.slideTo(swiper.activeIndex); return; } if (swiper.swipeDirection === 'next') { if (ratio >= params.longSwipesRatio) swiper.slideTo(stopIndex + increment);else swiper.slideTo(stopIndex); } if (swiper.swipeDirection === 'prev') { if (ratio > 1 - params.longSwipesRatio) swiper.slideTo(stopIndex + increment);else swiper.slideTo(stopIndex); } } else { // Short swipes if (!params.shortSwipes) { swiper.slideTo(swiper.activeIndex); return; } var isNavButtonTarget = swiper.navigation && (e.target === swiper.navigation.nextEl || e.target === swiper.navigation.prevEl); if (!isNavButtonTarget) { if (swiper.swipeDirection === 'next') { swiper.slideTo(stopIndex + increment); } if (swiper.swipeDirection === 'prev') { swiper.slideTo(stopIndex); } } else if (e.target === swiper.navigation.nextEl) { swiper.slideTo(stopIndex + increment); } else { swiper.slideTo(stopIndex); } } } function onResize() { var swiper = this; var params = swiper.params, el = swiper.el; if (el && el.offsetWidth === 0) return; // Breakpoints if (params.breakpoints) { swiper.setBreakpoint(); } // Save locks var allowSlideNext = swiper.allowSlideNext, allowSlidePrev = swiper.allowSlidePrev, snapGrid = swiper.snapGrid; // Disable locks on resize swiper.allowSlideNext = true; swiper.allowSlidePrev = true; swiper.updateSize(); swiper.updateSlides(); swiper.updateSlidesClasses(); if ((params.slidesPerView === 'auto' || params.slidesPerView > 1) && swiper.isEnd && !swiper.isBeginning && !swiper.params.centeredSlides) { swiper.slideTo(swiper.slides.length - 1, 0, false, true); } else { swiper.slideTo(swiper.activeIndex, 0, false, true); } if (swiper.autoplay && swiper.autoplay.running && swiper.autoplay.paused) { swiper.autoplay.run(); } // Return locks after resize swiper.allowSlidePrev = allowSlidePrev; swiper.allowSlideNext = allowSlideNext; if (swiper.params.watchOverflow && snapGrid !== swiper.snapGrid) { swiper.checkOverflow(); } } function onClick(e) { var swiper = this; if (!swiper.enabled) return; if (!swiper.allowClick) { if (swiper.params.preventClicks) e.preventDefault(); if (swiper.params.preventClicksPropagation && swiper.animating) { e.stopPropagation(); e.stopImmediatePropagation(); } } } function onScroll() { var swiper = this; var wrapperEl = swiper.wrapperEl, rtlTranslate = swiper.rtlTranslate, enabled = swiper.enabled; if (!enabled) return; swiper.previousTranslate = swiper.translate; if (swiper.isHorizontal()) { if (rtlTranslate) { swiper.translate = wrapperEl.scrollWidth - wrapperEl.offsetWidth - wrapperEl.scrollLeft; } else { swiper.translate = -wrapperEl.scrollLeft; } } else { swiper.translate = -wrapperEl.scrollTop; } // eslint-disable-next-line if (swiper.translate === -0) swiper.translate = 0; swiper.updateActiveIndex(); swiper.updateSlidesClasses(); var newProgress; var translatesDiff = swiper.maxTranslate() - swiper.minTranslate(); if (translatesDiff === 0) { newProgress = 0; } else { newProgress = (swiper.translate - swiper.minTranslate()) / translatesDiff; } if (newProgress !== swiper.progress) { swiper.updateProgress(rtlTranslate ? -swiper.translate : swiper.translate); } swiper.emit('setTranslate', swiper.translate, false); } var dummyEventAttached = false; function dummyEventListener() {} function attachEvents() { var swiper = this; var document = getDocument(); var params = swiper.params, touchEvents = swiper.touchEvents, el = swiper.el, wrapperEl = swiper.wrapperEl, device = swiper.device, support = swiper.support; swiper.onTouchStart = onTouchStart.bind(swiper); swiper.onTouchMove = onTouchMove.bind(swiper); swiper.onTouchEnd = onTouchEnd.bind(swiper); if (params.cssMode) { swiper.onScroll = onScroll.bind(swiper); } swiper.onClick = onClick.bind(swiper); var capture = !!params.nested; // Touch Events if (!support.touch) { el.addEventListener(touchEvents.start, swiper.onTouchStart, false); document.addEventListener(touchEvents.move, swiper.onTouchMove, capture); document.addEventListener(touchEvents.end, swiper.onTouchEnd, false); } else { var passiveListener = touchEvents.start === 'touchstart' && support.passiveListener && params.passiveListeners ? { passive: true, capture: false } : false; el.addEventListener(touchEvents.start, swiper.onTouchStart, passiveListener); el.addEventListener(touchEvents.move, swiper.onTouchMove, support.passiveListener ? { passive: false, capture: capture } : capture); el.addEventListener(touchEvents.end, swiper.onTouchEnd, passiveListener); if (touchEvents.cancel) { el.addEventListener(touchEvents.cancel, swiper.onTouchEnd, passiveListener); } if (!dummyEventAttached) { document.addEventListener('touchstart', dummyEventListener); dummyEventAttached = true; } } // Prevent Links Clicks if (params.preventClicks || params.preventClicksPropagation) { el.addEventListener('click', swiper.onClick, true); } if (params.cssMode) { wrapperEl.addEventListener('scroll', swiper.onScroll); } // Resize handler if (params.updateOnWindowResize) { swiper.on(device.ios || device.android ? 'resize orientationchange observerUpdate' : 'resize observerUpdate', onResize, true); } else { swiper.on('observerUpdate', onResize, true); } } function detachEvents() { var swiper = this; var document = getDocument(); var params = swiper.params, touchEvents = swiper.touchEvents, el = swiper.el, wrapperEl = swiper.wrapperEl, device = swiper.device, support = swiper.support; var capture = !!params.nested; // Touch Events if (!support.touch) { el.removeEventListener(touchEvents.start, swiper.onTouchStart, false); document.removeEventListener(touchEvents.move, swiper.onTouchMove, capture); document.removeEventListener(touchEvents.end, swiper.onTouchEnd, false); } else { var passiveListener = touchEvents.start === 'onTouchStart' && support.passiveListener && params.passiveListeners ? { passive: true, capture: false } : false; el.removeEventListener(touchEvents.start, swiper.onTouchStart, passiveListener); el.removeEventListener(touchEvents.move, swiper.onTouchMove, capture); el.removeEventListener(touchEvents.end, swiper.onTouchEnd, passiveListener); if (touchEvents.cancel) { el.removeEventListener(touchEvents.cancel, swiper.onTouchEnd, passiveListener); } } // Prevent Links Clicks if (params.preventClicks || params.preventClicksPropagation) { el.removeEventListener('click', swiper.onClick, true); } if (params.cssMode) { wrapperEl.removeEventListener('scroll', swiper.onScroll); } // Resize handler swiper.off(device.ios || device.android ? 'resize orientationchange observerUpdate' : 'resize observerUpdate', onResize); } var events = { attachEvents: attachEvents, detachEvents: detachEvents }; function setBreakpoint() { var swiper = this; var activeIndex = swiper.activeIndex, initialized = swiper.initialized, _swiper$loopedSlides = swiper.loopedSlides, loopedSlides = _swiper$loopedSlides === void 0 ? 0 : _swiper$loopedSlides, params = swiper.params, $el = swiper.$el; var breakpoints = params.breakpoints; if (!breakpoints || breakpoints && Object.keys(breakpoints).length === 0) return; // Get breakpoint for window width and update parameters var breakpoint = swiper.getBreakpoint(breakpoints, swiper.params.breakpointsBase, swiper.el); if (!breakpoint || swiper.currentBreakpoint === breakpoint) return; var breakpointOnlyParams = breakpoint in breakpoints ? breakpoints[breakpoint] : undefined; if (breakpointOnlyParams) { ['slidesPerView', 'spaceBetween', 'slidesPerGroup', 'slidesPerGroupSkip', 'slidesPerColumn'].forEach(function (param) { var paramValue = breakpointOnlyParams[param]; if (typeof paramValue === 'undefined') return; if (param === 'slidesPerView' && (paramValue === 'AUTO' || paramValue === 'auto')) { breakpointOnlyParams[param] = 'auto'; } else if (param === 'slidesPerView') { breakpointOnlyParams[param] = parseFloat(paramValue); } else { breakpointOnlyParams[param] = parseInt(paramValue, 10); } }); } var breakpointParams = breakpointOnlyParams || swiper.originalParams; var wasMultiRow = params.slidesPerColumn > 1; var isMultiRow = breakpointParams.slidesPerColumn > 1; var wasEnabled = params.enabled; if (wasMultiRow && !isMultiRow) { $el.removeClass(params.containerModifierClass + "multirow " + params.containerModifierClass + "multirow-column"); swiper.emitContainerClasses(); } else if (!wasMultiRow && isMultiRow) { $el.addClass(params.containerModifierClass + "multirow"); if (breakpointParams.slidesPerColumnFill && breakpointParams.slidesPerColumnFill === 'column' || !breakpointParams.slidesPerColumnFill && params.slidesPerColumnFill === 'column') { $el.addClass(params.containerModifierClass + "multirow-column"); } swiper.emitContainerClasses(); } var directionChanged = breakpointParams.direction && breakpointParams.direction !== params.direction; var needsReLoop = params.loop && (breakpointParams.slidesPerView !== params.slidesPerView || directionChanged); if (directionChanged && initialized) { swiper.changeDirection(); } extend(swiper.params, breakpointParams); var isEnabled = swiper.params.enabled; Object.assign(swiper, { allowTouchMove: swiper.params.allowTouchMove, allowSlideNext: swiper.params.allowSlideNext, allowSlidePrev: swiper.params.allowSlidePrev }); if (wasEnabled && !isEnabled) { swiper.disable(); } else if (!wasEnabled && isEnabled) { swiper.enable(); } swiper.currentBreakpoint = breakpoint; swiper.emit('_beforeBreakpoint', breakpointParams); if (needsReLoop && initialized) { swiper.loopDestroy(); swiper.loopCreate(); swiper.updateSlides(); swiper.slideTo(activeIndex - loopedSlides + swiper.loopedSlides, 0, false); } swiper.emit('breakpoint', breakpointParams); } function getBreakpoint(breakpoints, base, containerEl) { if (base === void 0) { base = 'window'; } if (!breakpoints || base === 'container' && !containerEl) return undefined; var breakpoint = false; var window = getWindow(); var currentHeight = base === 'window' ? window.innerHeight : containerEl.clientHeight; var points = Object.keys(breakpoints).map(function (point) { if (typeof point === 'string' && point.indexOf('@') === 0) { var minRatio = parseFloat(point.substr(1)); var value = currentHeight * minRatio; return { value: value, point: point }; } return { value: point, point: point }; }); points.sort(function (a, b) { return parseInt(a.value, 10) - parseInt(b.value, 10); }); for (var i = 0; i < points.length; i += 1) { var _points$i = points[i], point = _points$i.point, value = _points$i.value; if (base === 'window') { if (window.matchMedia("(min-width: " + value + "px)").matches) { breakpoint = point; } } else if (value <= containerEl.clientWidth) { breakpoint = point; } } return breakpoint || 'max'; } var breakpoints = { setBreakpoint: setBreakpoint, getBreakpoint: getBreakpoint }; function prepareClasses(entries, prefix) { var resultClasses = []; entries.forEach(function (item) { if (typeof item === 'object') { Object.keys(item).forEach(function (classNames) { if (item[classNames]) { resultClasses.push(prefix + classNames); } }); } else if (typeof item === 'string') { resultClasses.push(prefix + item); } }); return resultClasses; } function addClasses() { var swiper = this; var classNames = swiper.classNames, params = swiper.params, rtl = swiper.rtl, $el = swiper.$el, device = swiper.device, support = swiper.support; // prettier-ignore var suffixes = prepareClasses(['initialized', params.direction, { 'pointer-events': !support.touch }, { 'free-mode': swiper.params.freeMode && params.freeMode.enabled }, { 'autoheight': params.autoHeight }, { 'rtl': rtl }, { 'multirow': params.slidesPerColumn > 1 }, { 'multirow-column': params.slidesPerColumn > 1 && params.slidesPerColumnFill === 'column' }, { 'android': device.android }, { 'ios': device.ios }, { 'css-mode': params.cssMode }], params.containerModifierClass); classNames.push.apply(classNames, suffixes); $el.addClass([].concat(classNames).join(' ')); swiper.emitContainerClasses(); } function removeClasses() { var swiper = this; var $el = swiper.$el, classNames = swiper.classNames; $el.removeClass(classNames.join(' ')); swiper.emitContainerClasses(); } var classes = { addClasses: addClasses, removeClasses: removeClasses }; function loadImage(imageEl, src, srcset, sizes, checkForComplete, callback) { var window = getWindow(); var image; function onReady() { if (callback) callback(); } var isPicture = $(imageEl).parent('picture')[0]; if (!isPicture && (!imageEl.complete || !checkForComplete)) { if (src) { image = new window.Image(); image.onload = onReady; image.onerror = onReady; if (sizes) { image.sizes = sizes; } if (srcset) { image.srcset = srcset; } if (src) { image.src = src; } } else { onReady(); } } else { // image already loaded... onReady(); } } function preloadImages() { var swiper = this; swiper.imagesToLoad = swiper.$el.find('img'); function onReady() { if (typeof swiper === 'undefined' || swiper === null || !swiper || swiper.destroyed) return; if (swiper.imagesLoaded !== undefined) swiper.imagesLoaded += 1; if (swiper.imagesLoaded === swiper.imagesToLoad.length) { if (swiper.params.updateOnImagesReady) swiper.update(); swiper.emit('imagesReady'); } } for (var i = 0; i < swiper.imagesToLoad.length; i += 1) { var imageEl = swiper.imagesToLoad[i]; swiper.loadImage(imageEl, imageEl.currentSrc || imageEl.getAttribute('src'), imageEl.srcset || imageEl.getAttribute('srcset'), imageEl.sizes || imageEl.getAttribute('sizes'), true, onReady); } } var images = { loadImage: loadImage, preloadImages: preloadImages }; function checkOverflow() { var swiper = this; var params = swiper.params; var wasLocked = swiper.isLocked; var lastSlidePosition = swiper.slides.length > 0 && params.slidesOffsetBefore + params.spaceBetween * (swiper.slides.length - 1) + swiper.slides[0].offsetWidth * swiper.slides.length; if (params.slidesOffsetBefore && params.slidesOffsetAfter && lastSlidePosition) { swiper.isLocked = lastSlidePosition <= swiper.size; } else { swiper.isLocked = swiper.snapGrid.length === 1; } swiper.allowSlideNext = !swiper.isLocked; swiper.allowSlidePrev = !swiper.isLocked; // events if (wasLocked !== swiper.isLocked) swiper.emit(swiper.isLocked ? 'lock' : 'unlock'); if (wasLocked && wasLocked !== swiper.isLocked) { swiper.isEnd = false; if (swiper.navigation) swiper.navigation.update(); } } var checkOverflow$1 = { checkOverflow: checkOverflow }; var defaults = { init: true, direction: 'horizontal', touchEventsTarget: 'wrapper', initialSlide: 0, speed: 300, cssMode: false, updateOnWindowResize: true, resizeObserver: true, nested: false, createElements: false, enabled: true, focusableElements: 'input, select, option, textarea, button, video, label', // Overrides width: null, height: null, // preventInteractionOnTransition: false, // ssr userAgent: null, url: null, // To support iOS's swipe-to-go-back gesture (when being used in-app). edgeSwipeDetection: false, edgeSwipeThreshold: 20, // Autoheight autoHeight: false, // Set wrapper width setWrapperSize: false, // Virtual Translate virtualTranslate: false, // Effects effect: 'slide', // 'slide' or 'fade' or 'cube' or 'coverflow' or 'flip' // Breakpoints breakpoints: undefined, breakpointsBase: 'window', // Slides grid spaceBetween: 0, slidesPerView: 1, slidesPerColumn: 1, slidesPerColumnFill: 'column', slidesPerGroup: 1, slidesPerGroupSkip: 0, centeredSlides: false, centeredSlidesBounds: false, slidesOffsetBefore: 0, // in px slidesOffsetAfter: 0, // in px normalizeSlideIndex: true, centerInsufficientSlides: false, // Disable swiper and hide navigation when container not overflow watchOverflow: false, // Round length roundLengths: false, // Touches touchRatio: 1, touchAngle: 45, simulateTouch: true, shortSwipes: true, longSwipes: true, longSwipesRatio: 0.5, longSwipesMs: 300, followFinger: true, allowTouchMove: true, threshold: 0, touchMoveStopPropagation: false, touchStartPreventDefault: true, touchStartForcePreventDefault: false, touchReleaseOnEdges: false, // Unique Navigation Elements uniqueNavElements: true, // Resistance resistance: true, resistanceRatio: 0.85, // Progress watchSlidesProgress: false, watchSlidesVisibility: false, // Cursor grabCursor: false, // Clicks preventClicks: true, preventClicksPropagation: true, slideToClickedSlide: false, // Images preloadImages: true, updateOnImagesReady: true, // loop loop: false, loopAdditionalSlides: 0, loopedSlides: null, loopFillGroupWithBlank: false, loopPreventsSlide: true, // Swiping/no swiping allowSlidePrev: true, allowSlideNext: true, swipeHandler: null, // '.swipe-handler', noSwiping: true, noSwipingClass: 'swiper-no-swiping', noSwipingSelector: null, // Passive Listeners passiveListeners: true, // NS containerModifierClass: 'swiper-container-', // NEW slideClass: 'swiper-slide', slideBlankClass: 'swiper-slide-invisible-blank', slideActiveClass: 'swiper-slide-active', slideDuplicateActiveClass: 'swiper-slide-duplicate-active', slideVisibleClass: 'swiper-slide-visible', slideDuplicateClass: 'swiper-slide-duplicate', slideNextClass: 'swiper-slide-next', slideDuplicateNextClass: 'swiper-slide-duplicate-next', slidePrevClass: 'swiper-slide-prev', slideDuplicatePrevClass: 'swiper-slide-duplicate-prev', wrapperClass: 'swiper-wrapper', // Callbacks runCallbacksOnInit: true, // Internals _emitClasses: false }; function moduleExtendParams(params, allModulesParams) { return function extendParams(obj) { if (obj === void 0) { obj = {}; } var moduleParamName = Object.keys(obj)[0]; var moduleParams = obj[moduleParamName]; if (typeof moduleParams !== 'object' || moduleParams === null) { extend(allModulesParams, obj); return; } if (['navigation', 'pagination', 'scrollbar'].indexOf(moduleParamName) >= 0 && params[moduleParamName] === true) { params[moduleParamName] = { auto: true }; } if (!(moduleParamName in params && 'enabled' in moduleParams)) { extend(allModulesParams, obj); return; } if (params[moduleParamName] === true) { params[moduleParamName] = { enabled: true }; } if (typeof params[moduleParamName] === 'object' && !('enabled' in params[moduleParamName])) { params[moduleParamName].enabled = true; } if (!params[moduleParamName]) params[moduleParamName] = { enabled: false }; extend(allModulesParams, obj); }; } var prototypes = { eventsEmitter: eventsEmitter, update: update, translate: translate, transition: transition, slide: slide, loop: loop, grabCursor: grabCursor, manipulation: manipulation, events: events, breakpoints: breakpoints, checkOverflow: checkOverflow$1, classes: classes, images: images }; var extendedDefaults = {}; var Swiper = /*#__PURE__*/function () { function Swiper() { var el; var params; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args.length === 1 && args[0].constructor && Object.prototype.toString.call(args[0]).slice(8, -1) === 'Object') { params = args[0]; } else { el = args[0]; params = args[1]; } if (!params) params = {}; params = extend({}, params); if (el && !params.el) params.el = el; if (params.el && $(params.el).length > 1) { var swipers = []; $(params.el).each(function (containerEl) { var newParams = extend({}, params, { el: containerEl }); swipers.push(new Swiper(newParams)); }); return swipers; } // Swiper Instance var swiper = this; swiper.__swiper__ = true; swiper.support = getSupport(); swiper.device = getDevice({ userAgent: params.userAgent }); swiper.browser = getBrowser(); swiper.eventsListeners = {}; swiper.eventsAnyListeners = []; if (typeof swiper.modules === 'undefined') { swiper.modules = []; } if (params.modules && Array.isArray(params.modules)) { var _swiper$modules; (_swiper$modules = swiper.modules).push.apply(_swiper$modules, params.modules); } var allModulesParams = {}; swiper.modules.forEach(function (mod) { mod({ swiper: swiper, extendParams: moduleExtendParams(params, allModulesParams), on: swiper.on.bind(swiper), once: swiper.once.bind(swiper), off: swiper.off.bind(swiper), emit: swiper.emit.bind(swiper) }); }); // Extend defaults with modules params var swiperParams = extend({}, defaults, allModulesParams); // Extend defaults with passed params swiper.params = extend({}, swiperParams, extendedDefaults, params); swiper.originalParams = extend({}, swiper.params); swiper.passedParams = extend({}, params); // add event listeners if (swiper.params && swiper.params.on) { Object.keys(swiper.params.on).forEach(function (eventName) { swiper.on(eventName, swiper.params.on[eventName]); }); } if (swiper.params && swiper.params.onAny) { swiper.onAny(swiper.params.onAny); } // Save Dom lib swiper.$ = $; // Extend Swiper Object.assign(swiper, { enabled: swiper.params.enabled, el: el, // Classes classNames: [], // Slides slides: $(), slidesGrid: [], snapGrid: [], slidesSizesGrid: [], // isDirection isHorizontal: function isHorizontal() { return swiper.params.direction === 'horizontal'; }, isVertical: function isVertical() { return swiper.params.direction === 'vertical'; }, // Indexes activeIndex: 0, realIndex: 0, // isBeginning: true, isEnd: false, // Props translate: 0, previousTranslate: 0, progress: 0, velocity: 0, animating: false, // Locks allowSlideNext: swiper.params.allowSlideNext, allowSlidePrev: swiper.params.allowSlidePrev, // Touch Events touchEvents: function touchEvents() { var touch = ['touchstart', 'touchmove', 'touchend', 'touchcancel']; var desktop = ['pointerdown', 'pointermove', 'pointerup']; swiper.touchEventsTouch = { start: touch[0], move: touch[1], end: touch[2], cancel: touch[3] }; swiper.touchEventsDesktop = { start: desktop[0], move: desktop[1], end: desktop[2] }; return swiper.support.touch || !swiper.params.simulateTouch ? swiper.touchEventsTouch : swiper.touchEventsDesktop; }(), touchEventsData: { isTouched: undefined, isMoved: undefined, allowTouchCallbacks: undefined, touchStartTime: undefined, isScrolling: undefined, currentTranslate: undefined, startTranslate: undefined, allowThresholdMove: undefined, // Form elements to match focusableElements: swiper.params.focusableElements, // Last click time lastClickTime: now(), clickTimeout: undefined, // Velocities velocities: [], allowMomentumBounce: undefined, isTouchEvent: undefined, startMoving: undefined }, // Clicks allowClick: true, // Touches allowTouchMove: swiper.params.allowTouchMove, touches: { startX: 0, startY: 0, currentX: 0, currentY: 0, diff: 0 }, // Images imagesToLoad: [], imagesLoaded: 0 }); swiper.emit('_swiper'); // Init if (swiper.params.init) { swiper.init(); } // Return app instance return swiper; } var _proto = Swiper.prototype; _proto.enable = function enable() { var swiper = this; if (swiper.enabled) return; swiper.enabled = true; if (swiper.params.grabCursor) { swiper.setGrabCursor(); } swiper.emit('enable'); }; _proto.disable = function disable() { var swiper = this; if (!swiper.enabled) return; swiper.enabled = false; if (swiper.params.grabCursor) { swiper.unsetGrabCursor(); } swiper.emit('disable'); }; _proto.setProgress = function setProgress(progress, speed) { var swiper = this; progress = Math.min(Math.max(progress, 0), 1); var min = swiper.minTranslate(); var max = swiper.maxTranslate(); var current = (max - min) * progress + min; swiper.translateTo(current, typeof speed === 'undefined' ? 0 : speed); swiper.updateActiveIndex(); swiper.updateSlidesClasses(); }; _proto.emitContainerClasses = function emitContainerClasses() { var swiper = this; if (!swiper.params._emitClasses || !swiper.el) return; var cls = swiper.el.className.split(' ').filter(function (className) { return className.indexOf('swiper-container') === 0 || className.indexOf(swiper.params.containerModifierClass) === 0; }); swiper.emit('_containerClasses', cls.join(' ')); }; _proto.getSlideClasses = function getSlideClasses(slideEl) { var swiper = this; return slideEl.className.split(' ').filter(function (className) { return className.indexOf('swiper-slide') === 0 || className.indexOf(swiper.params.slideClass) === 0; }).join(' '); }; _proto.emitSlidesClasses = function emitSlidesClasses() { var swiper = this; if (!swiper.params._emitClasses || !swiper.el) return; var updates = []; swiper.slides.each(function (slideEl) { var classNames = swiper.getSlideClasses(slideEl); updates.push({ slideEl: slideEl, classNames: classNames }); swiper.emit('_slideClass', slideEl, classNames); }); swiper.emit('_slideClasses', updates); }; _proto.slidesPerViewDynamic = function slidesPerViewDynamic() { var swiper = this; var params = swiper.params, slides = swiper.slides, slidesGrid = swiper.slidesGrid, swiperSize = swiper.size, activeIndex = swiper.activeIndex; var spv = 1; if (params.centeredSlides) { var slideSize = slides[activeIndex].swiperSlideSize; var breakLoop; for (var i = activeIndex + 1; i < slides.length; i += 1) { if (slides[i] && !breakLoop) { slideSize += slides[i].swiperSlideSize; spv += 1; if (slideSize > swiperSize) breakLoop = true; } } for (var _i = activeIndex - 1; _i >= 0; _i -= 1) { if (slides[_i] && !breakLoop) { slideSize += slides[_i].swiperSlideSize; spv += 1; if (slideSize > swiperSize) breakLoop = true; } } } else { for (var _i2 = activeIndex + 1; _i2 < slides.length; _i2 += 1) { if (slidesGrid[_i2] - slidesGrid[activeIndex] < swiperSize) { spv += 1; } } } return spv; }; _proto.update = function update() { var swiper = this; if (!swiper || swiper.destroyed) return; var snapGrid = swiper.snapGrid, params = swiper.params; // Breakpoints if (params.breakpoints) { swiper.setBreakpoint(); } swiper.updateSize(); swiper.updateSlides(); swiper.updateProgress(); swiper.updateSlidesClasses(); function setTranslate() { var translateValue = swiper.rtlTranslate ? swiper.translate * -1 : swiper.translate; var newTranslate = Math.min(Math.max(translateValue, swiper.maxTranslate()), swiper.minTranslate()); swiper.setTranslate(newTranslate); swiper.updateActiveIndex(); swiper.updateSlidesClasses(); } var translated; if (swiper.params.freeMode && swiper.params.freeMode.enabled) { setTranslate(); if (swiper.params.autoHeight) { swiper.updateAutoHeight(); } } else { if ((swiper.params.slidesPerView === 'auto' || swiper.params.slidesPerView > 1) && swiper.isEnd && !swiper.params.centeredSlides) { translated = swiper.slideTo(swiper.slides.length - 1, 0, false, true); } else { translated = swiper.slideTo(swiper.activeIndex, 0, false, true); } if (!translated) { setTranslate(); } } if (params.watchOverflow && snapGrid !== swiper.snapGrid) { swiper.checkOverflow(); } swiper.emit('update'); }; _proto.changeDirection = function changeDirection(newDirection, needUpdate) { if (needUpdate === void 0) { needUpdate = true; } var swiper = this; var currentDirection = swiper.params.direction; if (!newDirection) { // eslint-disable-next-line newDirection = currentDirection === 'horizontal' ? 'vertical' : 'horizontal'; } if (newDirection === currentDirection || newDirection !== 'horizontal' && newDirection !== 'vertical') { return swiper; } swiper.$el.removeClass("" + swiper.params.containerModifierClass + currentDirection).addClass("" + swiper.params.containerModifierClass + newDirection); swiper.emitContainerClasses(); swiper.params.direction = newDirection; swiper.slides.each(function (slideEl) { if (newDirection === 'vertical') { slideEl.style.width = ''; } else { slideEl.style.height = ''; } }); swiper.emit('changeDirection'); if (needUpdate) swiper.update(); return swiper; }; _proto.mount = function mount(el) { var swiper = this; if (swiper.mounted) return true; // Find el var $el = $(el || swiper.params.el); el = $el[0]; if (!el) { return false; } el.swiper = swiper; var getWrapperSelector = function getWrapperSelector() { return "." + (swiper.params.wrapperClass || '').trim().split(' ').join('.'); }; var getWrapper = function getWrapper() { if (el && el.shadowRoot && el.shadowRoot.querySelector) { var res = $(el.shadowRoot.querySelector(getWrapperSelector())); // Children needs to return slot items res.children = function (options) { return $el.children(options); }; return res; } return $el.children(getWrapperSelector()); }; // Find Wrapper var $wrapperEl = getWrapper(); if ($wrapperEl.length === 0 && swiper.params.createElements) { var document = getDocument(); var wrapper = document.createElement('div'); $wrapperEl = $(wrapper); wrapper.className = swiper.params.wrapperClass; $el.append(wrapper); $el.children("." + swiper.params.slideClass).each(function (slideEl) { $wrapperEl.append(slideEl); }); } Object.assign(swiper, { $el: $el, el: el, $wrapperEl: $wrapperEl, wrapperEl: $wrapperEl[0], mounted: true, // RTL rtl: el.dir.toLowerCase() === 'rtl' || $el.css('direction') === 'rtl', rtlTranslate: swiper.params.direction === 'horizontal' && (el.dir.toLowerCase() === 'rtl' || $el.css('direction') === 'rtl'), wrongRTL: $wrapperEl.css('display') === '-webkit-box' }); return true; }; _proto.init = function init(el) { var swiper = this; if (swiper.initialized) return swiper; var mounted = swiper.mount(el); if (mounted === false) return swiper; swiper.emit('beforeInit'); // Set breakpoint if (swiper.params.breakpoints) { swiper.setBreakpoint(); } // Add Classes swiper.addClasses(); // Create loop if (swiper.params.loop) { swiper.loopCreate(); } // Update size swiper.updateSize(); // Update slides swiper.updateSlides(); if (swiper.params.watchOverflow) { swiper.checkOverflow(); } // Set Grab Cursor if (swiper.params.grabCursor && swiper.enabled) { swiper.setGrabCursor(); } if (swiper.params.preloadImages) { swiper.preloadImages(); } // Slide To Initial Slide if (swiper.params.loop) { swiper.slideTo(swiper.params.initialSlide + swiper.loopedSlides, 0, swiper.params.runCallbacksOnInit, false, true); } else { swiper.slideTo(swiper.params.initialSlide, 0, swiper.params.runCallbacksOnInit, false, true); } // Attach events swiper.attachEvents(); // Init Flag swiper.initialized = true; // Emit swiper.emit('init'); swiper.emit('afterInit'); return swiper; }; _proto.destroy = function destroy(deleteInstance, cleanStyles) { if (deleteInstance === void 0) { deleteInstance = true; } if (cleanStyles === void 0) { cleanStyles = true; } var swiper = this; var params = swiper.params, $el = swiper.$el, $wrapperEl = swiper.$wrapperEl, slides = swiper.slides; if (typeof swiper.params === 'undefined' || swiper.destroyed) { return null; } swiper.emit('beforeDestroy'); // Init Flag swiper.initialized = false; // Detach events swiper.detachEvents(); // Destroy loop if (params.loop) { swiper.loopDestroy(); } // Cleanup styles if (cleanStyles) { swiper.removeClasses(); $el.removeAttr('style'); $wrapperEl.removeAttr('style'); if (slides && slides.length) { slides.removeClass([params.slideVisibleClass, params.slideActiveClass, params.slideNextClass, params.slidePrevClass].join(' ')).removeAttr('style').removeAttr('data-swiper-slide-index'); } } swiper.emit('destroy'); // Detach emitter events Object.keys(swiper.eventsListeners).forEach(function (eventName) { swiper.off(eventName); }); if (deleteInstance !== false) { swiper.$el[0].swiper = null; deleteProps(swiper); } swiper.destroyed = true; return null; }; Swiper.extendDefaults = function extendDefaults(newDefaults) { extend(extendedDefaults, newDefaults); }; Swiper.installModule = function installModule(mod) { if (!Swiper.prototype.modules) Swiper.prototype.modules = []; var modules = Swiper.prototype.modules; if (typeof mod === 'function' && modules.indexOf(mod) < 0) { modules.push(mod); } }; Swiper.use = function use(module) { if (Array.isArray(module)) { module.forEach(function (m) { return Swiper.installModule(m); }); return Swiper; } Swiper.installModule(module); return Swiper; }; _createClass(Swiper, null, [{ key: "extendedDefaults", get: function get() { return extendedDefaults; } }, { key: "defaults", get: function get() { return defaults; } }]); return Swiper; }(); Object.keys(prototypes).forEach(function (prototypeGroup) { Object.keys(prototypes[prototypeGroup]).forEach(function (protoMethod) { Swiper.prototype[protoMethod] = prototypes[prototypeGroup][protoMethod]; }); }); Swiper.use([Resize, Observer]); function Virtual(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on; extendParams({ virtual: { enabled: false, slides: [], cache: true, renderSlide: null, renderExternal: null, renderExternalUpdate: true, addSlidesBefore: 0, addSlidesAfter: 0 } }); swiper.virtual = { cache: {}, from: null, to: null, slides: [], offset: 0, slidesGrid: [] }; function renderSlide(slide, index) { var params = swiper.params.virtual; if (params.cache && swiper.virtual.cache[index]) { return swiper.virtual.cache[index]; } var $slideEl = params.renderSlide ? $(params.renderSlide.call(swiper, slide, index)) : $("<div class=\"" + swiper.params.slideClass + "\" data-swiper-slide-index=\"" + index + "\">" + slide + "</div>"); if (!$slideEl.attr('data-swiper-slide-index')) $slideEl.attr('data-swiper-slide-index', index); if (params.cache) swiper.virtual.cache[index] = $slideEl; return $slideEl; } function update(force) { var _swiper$params = swiper.params, slidesPerView = _swiper$params.slidesPerView, slidesPerGroup = _swiper$params.slidesPerGroup, centeredSlides = _swiper$params.centeredSlides; var _swiper$params$virtua = swiper.params.virtual, addSlidesBefore = _swiper$params$virtua.addSlidesBefore, addSlidesAfter = _swiper$params$virtua.addSlidesAfter; var _swiper$virtual = swiper.virtual, previousFrom = _swiper$virtual.from, previousTo = _swiper$virtual.to, slides = _swiper$virtual.slides, previousSlidesGrid = _swiper$virtual.slidesGrid, previousOffset = _swiper$virtual.offset; swiper.updateActiveIndex(); var activeIndex = swiper.activeIndex || 0; var offsetProp; if (swiper.rtlTranslate) offsetProp = 'right';else offsetProp = swiper.isHorizontal() ? 'left' : 'top'; var slidesAfter; var slidesBefore; if (centeredSlides) { slidesAfter = Math.floor(slidesPerView / 2) + slidesPerGroup + addSlidesAfter; slidesBefore = Math.floor(slidesPerView / 2) + slidesPerGroup + addSlidesBefore; } else { slidesAfter = slidesPerView + (slidesPerGroup - 1) + addSlidesAfter; slidesBefore = slidesPerGroup + addSlidesBefore; } var from = Math.max((activeIndex || 0) - slidesBefore, 0); var to = Math.min((activeIndex || 0) + slidesAfter, slides.length - 1); var offset = (swiper.slidesGrid[from] || 0) - (swiper.slidesGrid[0] || 0); Object.assign(swiper.virtual, { from: from, to: to, offset: offset, slidesGrid: swiper.slidesGrid }); function onRendered() { swiper.updateSlides(); swiper.updateProgress(); swiper.updateSlidesClasses(); if (swiper.lazy && swiper.params.lazy.enabled) { swiper.lazy.load(); } } if (previousFrom === from && previousTo === to && !force) { if (swiper.slidesGrid !== previousSlidesGrid && offset !== previousOffset) { swiper.slides.css(offsetProp, offset + "px"); } swiper.updateProgress(); return; } if (swiper.params.virtual.renderExternal) { swiper.params.virtual.renderExternal.call(swiper, { offset: offset, from: from, to: to, slides: function getSlides() { var slidesToRender = []; for (var i = from; i <= to; i += 1) { slidesToRender.push(slides[i]); } return slidesToRender; }() }); if (swiper.params.virtual.renderExternalUpdate) { onRendered(); } return; } var prependIndexes = []; var appendIndexes = []; if (force) { swiper.$wrapperEl.find("." + swiper.params.slideClass).remove(); } else { for (var i = previousFrom; i <= previousTo; i += 1) { if (i < from || i > to) { swiper.$wrapperEl.find("." + swiper.params.slideClass + "[data-swiper-slide-index=\"" + i + "\"]").remove(); } } } for (var _i = 0; _i < slides.length; _i += 1) { if (_i >= from && _i <= to) { if (typeof previousTo === 'undefined' || force) { appendIndexes.push(_i); } else { if (_i > previousTo) appendIndexes.push(_i); if (_i < previousFrom) prependIndexes.push(_i); } } } appendIndexes.forEach(function (index) { swiper.$wrapperEl.append(renderSlide(slides[index], index)); }); prependIndexes.sort(function (a, b) { return b - a; }).forEach(function (index) { swiper.$wrapperEl.prepend(renderSlide(slides[index], index)); }); swiper.$wrapperEl.children('.swiper-slide').css(offsetProp, offset + "px"); onRendered(); } function appendSlide(slides) { if (typeof slides === 'object' && 'length' in slides) { for (var i = 0; i < slides.length; i += 1) { if (slides[i]) swiper.virtual.slides.push(slides[i]); } } else { swiper.virtual.slides.push(slides); } update(true); } function prependSlide(slides) { var activeIndex = swiper.activeIndex; var newActiveIndex = activeIndex + 1; var numberOfNewSlides = 1; if (Array.isArray(slides)) { for (var i = 0; i < slides.length; i += 1) { if (slides[i]) swiper.virtual.slides.unshift(slides[i]); } newActiveIndex = activeIndex + slides.length; numberOfNewSlides = slides.length; } else { swiper.virtual.slides.unshift(slides); } if (swiper.params.virtual.cache) { var cache = swiper.virtual.cache; var newCache = {}; Object.keys(cache).forEach(function (cachedIndex) { var $cachedEl = cache[cachedIndex]; var cachedElIndex = $cachedEl.attr('data-swiper-slide-index'); if (cachedElIndex) { $cachedEl.attr('data-swiper-slide-index', parseInt(cachedElIndex, 10) + 1); } newCache[parseInt(cachedIndex, 10) + numberOfNewSlides] = $cachedEl; }); swiper.virtual.cache = newCache; } update(true); swiper.slideTo(newActiveIndex, 0); } function removeSlide(slidesIndexes) { if (typeof slidesIndexes === 'undefined' || slidesIndexes === null) return; var activeIndex = swiper.activeIndex; if (Array.isArray(slidesIndexes)) { for (var i = slidesIndexes.length - 1; i >= 0; i -= 1) { swiper.virtual.slides.splice(slidesIndexes[i], 1); if (swiper.params.virtual.cache) { delete swiper.virtual.cache[slidesIndexes[i]]; } if (slidesIndexes[i] < activeIndex) activeIndex -= 1; activeIndex = Math.max(activeIndex, 0); } } else { swiper.virtual.slides.splice(slidesIndexes, 1); if (swiper.params.virtual.cache) { delete swiper.virtual.cache[slidesIndexes]; } if (slidesIndexes < activeIndex) activeIndex -= 1; activeIndex = Math.max(activeIndex, 0); } update(true); swiper.slideTo(activeIndex, 0); } function removeAllSlides() { swiper.virtual.slides = []; if (swiper.params.virtual.cache) { swiper.virtual.cache = {}; } update(true); swiper.slideTo(0, 0); } on('beforeInit', function () { if (!swiper.params.virtual.enabled) return; swiper.virtual.slides = swiper.params.virtual.slides; swiper.classNames.push(swiper.params.containerModifierClass + "virtual"); swiper.params.watchSlidesProgress = true; swiper.originalParams.watchSlidesProgress = true; if (!swiper.params.initialSlide) { update(); } }); on('setTranslate', function () { if (!swiper.params.virtual.enabled) return; update(); }); Object.assign(swiper.virtual, { appendSlide: appendSlide, prependSlide: prependSlide, removeSlide: removeSlide, removeAllSlides: removeAllSlides, update: update }); } /* eslint-disable consistent-return */ function Keyboard(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on, emit = _ref.emit; var document = getDocument(); var window = getWindow(); swiper.keyboard = { enabled: true }; extendParams({ keyboard: { enabled: false, onlyInViewport: true, pageUpDown: true } }); function handle(event) { if (!swiper.enabled) return; var rtl = swiper.rtlTranslate; var e = event; if (e.originalEvent) e = e.originalEvent; // jquery fix var kc = e.keyCode || e.charCode; var pageUpDown = swiper.params.keyboard.pageUpDown; var isPageUp = pageUpDown && kc === 33; var isPageDown = pageUpDown && kc === 34; var isArrowLeft = kc === 37; var isArrowRight = kc === 39; var isArrowUp = kc === 38; var isArrowDown = kc === 40; // Directions locks if (!swiper.allowSlideNext && (swiper.isHorizontal() && isArrowRight || swiper.isVertical() && isArrowDown || isPageDown)) { return false; } if (!swiper.allowSlidePrev && (swiper.isHorizontal() && isArrowLeft || swiper.isVertical() && isArrowUp || isPageUp)) { return false; } if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) { return undefined; } if (document.activeElement && document.activeElement.nodeName && (document.activeElement.nodeName.toLowerCase() === 'input' || document.activeElement.nodeName.toLowerCase() === 'textarea')) { return undefined; } if (swiper.params.keyboard.onlyInViewport && (isPageUp || isPageDown || isArrowLeft || isArrowRight || isArrowUp || isArrowDown)) { var inView = false; // Check that swiper should be inside of visible area of window if (swiper.$el.parents("." + swiper.params.slideClass).length > 0 && swiper.$el.parents("." + swiper.params.slideActiveClass).length === 0) { return undefined; } var $el = swiper.$el; var swiperWidth = $el[0].clientWidth; var swiperHeight = $el[0].clientHeight; var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; var swiperOffset = swiper.$el.offset(); if (rtl) swiperOffset.left -= swiper.$el[0].scrollLeft; var swiperCoord = [[swiperOffset.left, swiperOffset.top], [swiperOffset.left + swiperWidth, swiperOffset.top], [swiperOffset.left, swiperOffset.top + swiperHeight], [swiperOffset.left + swiperWidth, swiperOffset.top + swiperHeight]]; for (var i = 0; i < swiperCoord.length; i += 1) { var point = swiperCoord[i]; if (point[0] >= 0 && point[0] <= windowWidth && point[1] >= 0 && point[1] <= windowHeight) { if (point[0] === 0 && point[1] === 0) continue; // eslint-disable-line inView = true; } } if (!inView) return undefined; } if (swiper.isHorizontal()) { if (isPageUp || isPageDown || isArrowLeft || isArrowRight) { if (e.preventDefault) e.preventDefault();else e.returnValue = false; } if ((isPageDown || isArrowRight) && !rtl || (isPageUp || isArrowLeft) && rtl) swiper.slideNext(); if ((isPageUp || isArrowLeft) && !rtl || (isPageDown || isArrowRight) && rtl) swiper.slidePrev(); } else { if (isPageUp || isPageDown || isArrowUp || isArrowDown) { if (e.preventDefault) e.preventDefault();else e.returnValue = false; } if (isPageDown || isArrowDown) swiper.slideNext(); if (isPageUp || isArrowUp) swiper.slidePrev(); } emit('keyPress', kc); return undefined; } function enable() { if (swiper.keyboard.enabled) return; $(document).on('keydown', handle); swiper.keyboard.enabled = true; } function disable() { if (!swiper.keyboard.enabled) return; $(document).off('keydown', handle); swiper.keyboard.enabled = false; } on('init', function () { if (swiper.params.keyboard.enabled) { enable(); } }); on('destroy', function () { if (swiper.keyboard.enabled) { disable(); } }); Object.assign(swiper.keyboard, { enable: enable, disable: disable }); } /* eslint-disable consistent-return */ function Mousewheel(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on, emit = _ref.emit; var window = getWindow(); extendParams({ mousewheel: { enabled: false, releaseOnEdges: false, invert: false, forceToAxis: false, sensitivity: 1, eventsTarget: 'container', thresholdDelta: null, thresholdTime: null } }); swiper.mousewheel = { enabled: false }; var timeout; var lastScrollTime = now(); var lastEventBeforeSnap; var recentWheelEvents = []; function normalize(e) { // Reasonable defaults var PIXEL_STEP = 10; var LINE_HEIGHT = 40; var PAGE_HEIGHT = 800; var sX = 0; var sY = 0; // spinX, spinY var pX = 0; var pY = 0; // pixelX, pixelY // Legacy if ('detail' in e) { sY = e.detail; } if ('wheelDelta' in e) { sY = -e.wheelDelta / 120; } if ('wheelDeltaY' in e) { sY = -e.wheelDeltaY / 120; } if ('wheelDeltaX' in e) { sX = -e.wheelDeltaX / 120; } // side scrolling on FF with DOMMouseScroll if ('axis' in e && e.axis === e.HORIZONTAL_AXIS) { sX = sY; sY = 0; } pX = sX * PIXEL_STEP; pY = sY * PIXEL_STEP; if ('deltaY' in e) { pY = e.deltaY; } if ('deltaX' in e) { pX = e.deltaX; } if (e.shiftKey && !pX) { // if user scrolls with shift he wants horizontal scroll pX = pY; pY = 0; } if ((pX || pY) && e.deltaMode) { if (e.deltaMode === 1) { // delta in LINE units pX *= LINE_HEIGHT; pY *= LINE_HEIGHT; } else { // delta in PAGE units pX *= PAGE_HEIGHT; pY *= PAGE_HEIGHT; } } // Fall-back if spin cannot be determined if (pX && !sX) { sX = pX < 1 ? -1 : 1; } if (pY && !sY) { sY = pY < 1 ? -1 : 1; } return { spinX: sX, spinY: sY, pixelX: pX, pixelY: pY }; } function handleMouseEnter() { if (!swiper.enabled) return; swiper.mouseEntered = true; } function handleMouseLeave() { if (!swiper.enabled) return; swiper.mouseEntered = false; } function animateSlider(newEvent) { if (swiper.params.mousewheel.thresholdDelta && newEvent.delta < swiper.params.mousewheel.thresholdDelta) { // Prevent if delta of wheel scroll delta is below configured threshold return false; } if (swiper.params.mousewheel.thresholdTime && now() - lastScrollTime < swiper.params.mousewheel.thresholdTime) { // Prevent if time between scrolls is below configured threshold return false; } // If the movement is NOT big enough and // if the last time the user scrolled was too close to the current one (avoid continuously triggering the slider): // Don't go any further (avoid insignificant scroll movement). if (newEvent.delta >= 6 && now() - lastScrollTime < 60) { // Return false as a default return true; } // If user is scrolling towards the end: // If the slider hasn't hit the latest slide or // if the slider is a loop and // if the slider isn't moving right now: // Go to next slide and // emit a scroll event. // Else (the user is scrolling towards the beginning) and // if the slider hasn't hit the first slide or // if the slider is a loop and // if the slider isn't moving right now: // Go to prev slide and // emit a scroll event. if (newEvent.direction < 0) { if ((!swiper.isEnd || swiper.params.loop) && !swiper.animating) { swiper.slideNext(); emit('scroll', newEvent.raw); } } else if ((!swiper.isBeginning || swiper.params.loop) && !swiper.animating) { swiper.slidePrev(); emit('scroll', newEvent.raw); } // If you got here is because an animation has been triggered so store the current time lastScrollTime = new window.Date().getTime(); // Return false as a default return false; } function releaseScroll(newEvent) { var params = swiper.params.mousewheel; if (newEvent.direction < 0) { if (swiper.isEnd && !swiper.params.loop && params.releaseOnEdges) { // Return true to animate scroll on edges return true; } } else if (swiper.isBeginning && !swiper.params.loop && params.releaseOnEdges) { // Return true to animate scroll on edges return true; } return false; } function handle(event) { var e = event; var disableParentSwiper = true; if (!swiper.enabled) return; var params = swiper.params.mousewheel; if (swiper.params.cssMode) { e.preventDefault(); } var target = swiper.$el; if (swiper.params.mousewheel.eventsTarget !== 'container') { target = $(swiper.params.mousewheel.eventsTarget); } if (!swiper.mouseEntered && !target[0].contains(e.target) && !params.releaseOnEdges) return true; if (e.originalEvent) e = e.originalEvent; // jquery fix var delta = 0; var rtlFactor = swiper.rtlTranslate ? -1 : 1; var data = normalize(e); if (params.forceToAxis) { if (swiper.isHorizontal()) { if (Math.abs(data.pixelX) > Math.abs(data.pixelY)) delta = -data.pixelX * rtlFactor;else return true; } else if (Math.abs(data.pixelY) > Math.abs(data.pixelX)) delta = -data.pixelY;else return true; } else { delta = Math.abs(data.pixelX) > Math.abs(data.pixelY) ? -data.pixelX * rtlFactor : -data.pixelY; } if (delta === 0) return true; if (params.invert) delta = -delta; // Get the scroll positions var positions = swiper.getTranslate() + delta * params.sensitivity; if (positions >= swiper.minTranslate()) positions = swiper.minTranslate(); if (positions <= swiper.maxTranslate()) positions = swiper.maxTranslate(); // When loop is true: // the disableParentSwiper will be true. // When loop is false: // if the scroll positions is not on edge, // then the disableParentSwiper will be true. // if the scroll on edge positions, // then the disableParentSwiper will be false. disableParentSwiper = swiper.params.loop ? true : !(positions === swiper.minTranslate() || positions === swiper.maxTranslate()); if (disableParentSwiper && swiper.params.nested) e.stopPropagation(); if (!swiper.params.freeMode || !swiper.params.freeMode.enabled) { // Register the new event in a variable which stores the relevant data var newEvent = { time: now(), delta: Math.abs(delta), direction: Math.sign(delta), raw: event }; // Keep the most recent events if (recentWheelEvents.length >= 2) { recentWheelEvents.shift(); // only store the last N events } var prevEvent = recentWheelEvents.length ? recentWheelEvents[recentWheelEvents.length - 1] : undefined; recentWheelEvents.push(newEvent); // If there is at least one previous recorded event: // If direction has changed or // if the scroll is quicker than the previous one: // Animate the slider. // Else (this is the first time the wheel is moved): // Animate the slider. if (prevEvent) { if (newEvent.direction !== prevEvent.direction || newEvent.delta > prevEvent.delta || newEvent.time > prevEvent.time + 150) { animateSlider(newEvent); } } else { animateSlider(newEvent); } // If it's time to release the scroll: // Return now so you don't hit the preventDefault. if (releaseScroll(newEvent)) { return true; } } else { // Freemode or scrollContainer: // If we recently snapped after a momentum scroll, then ignore wheel events // to give time for the deceleration to finish. Stop ignoring after 500 msecs // or if it's a new scroll (larger delta or inverse sign as last event before // an end-of-momentum snap). var _newEvent = { time: now(), delta: Math.abs(delta), direction: Math.sign(delta) }; var ignoreWheelEvents = lastEventBeforeSnap && _newEvent.time < lastEventBeforeSnap.time + 500 && _newEvent.delta <= lastEventBeforeSnap.delta && _newEvent.direction === lastEventBeforeSnap.direction; if (!ignoreWheelEvents) { lastEventBeforeSnap = undefined; if (swiper.params.loop) { swiper.loopFix(); } var position = swiper.getTranslate() + delta * params.sensitivity; var wasBeginning = swiper.isBeginning; var wasEnd = swiper.isEnd; if (position >= swiper.minTranslate()) position = swiper.minTranslate(); if (position <= swiper.maxTranslate()) position = swiper.maxTranslate(); swiper.setTransition(0); swiper.setTranslate(position); swiper.updateProgress(); swiper.updateActiveIndex(); swiper.updateSlidesClasses(); if (!wasBeginning && swiper.isBeginning || !wasEnd && swiper.isEnd) { swiper.updateSlidesClasses(); } if (swiper.params.freeMode.sticky) { // When wheel scrolling starts with sticky (aka snap) enabled, then detect // the end of a momentum scroll by storing recent (N=15?) wheel events. // 1. do all N events have decreasing or same (absolute value) delta? // 2. did all N events arrive in the last M (M=500?) msecs? // 3. does the earliest event have an (absolute value) delta that's // at least P (P=1?) larger than the most recent event's delta? // 4. does the latest event have a delta that's smaller than Q (Q=6?) pixels? // If 1-4 are "yes" then we're near the end of a momentum scroll deceleration. // Snap immediately and ignore remaining wheel events in this scroll. // See comment above for "remaining wheel events in this scroll" determination. // If 1-4 aren't satisfied, then wait to snap until 500ms after the last event. clearTimeout(timeout); timeout = undefined; if (recentWheelEvents.length >= 15) { recentWheelEvents.shift(); // only store the last N events } var _prevEvent = recentWheelEvents.length ? recentWheelEvents[recentWheelEvents.length - 1] : undefined; var firstEvent = recentWheelEvents[0]; recentWheelEvents.push(_newEvent); if (_prevEvent && (_newEvent.delta > _prevEvent.delta || _newEvent.direction !== _prevEvent.direction)) { // Increasing or reverse-sign delta means the user started scrolling again. Clear the wheel event log. recentWheelEvents.splice(0); } else if (recentWheelEvents.length >= 15 && _newEvent.time - firstEvent.time < 500 && firstEvent.delta - _newEvent.delta >= 1 && _newEvent.delta <= 6) { // We're at the end of the deceleration of a momentum scroll, so there's no need // to wait for more events. Snap ASAP on the next tick. // Also, because there's some remaining momentum we'll bias the snap in the // direction of the ongoing scroll because it's better UX for the scroll to snap // in the same direction as the scroll instead of reversing to snap. Therefore, // if it's already scrolled more than 20% in the current direction, keep going. var snapToThreshold = delta > 0 ? 0.8 : 0.2; lastEventBeforeSnap = _newEvent; recentWheelEvents.splice(0); timeout = nextTick(function () { swiper.slideToClosest(swiper.params.speed, true, undefined, snapToThreshold); }, 0); // no delay; move on next tick } if (!timeout) { // if we get here, then we haven't detected the end of a momentum scroll, so // we'll consider a scroll "complete" when there haven't been any wheel events // for 500ms. timeout = nextTick(function () { var snapToThreshold = 0.5; lastEventBeforeSnap = _newEvent; recentWheelEvents.splice(0); swiper.slideToClosest(swiper.params.speed, true, undefined, snapToThreshold); }, 500); } } // Emit event if (!ignoreWheelEvents) emit('scroll', e); // Stop autoplay if (swiper.params.autoplay && swiper.params.autoplayDisableOnInteraction) swiper.autoplay.stop(); // Return page scroll on edge positions if (position === swiper.minTranslate() || position === swiper.maxTranslate()) return true; } } if (e.preventDefault) e.preventDefault();else e.returnValue = false; return false; } function events(method) { var target = swiper.$el; if (swiper.params.mousewheel.eventsTarget !== 'container') { target = $(swiper.params.mousewheel.eventsTarget); } target[method]('mouseenter', handleMouseEnter); target[method]('mouseleave', handleMouseLeave); target[method]('wheel', handle); } function enable() { if (swiper.params.cssMode) { swiper.wrapperEl.removeEventListener('wheel', handle); return true; } if (swiper.mousewheel.enabled) return false; events('on'); swiper.mousewheel.enabled = true; return true; } function disable() { if (swiper.params.cssMode) { swiper.wrapperEl.addEventListener(event, handle); return true; } if (!swiper.mousewheel.enabled) return false; events('off'); swiper.mousewheel.enabled = false; return true; } on('init', function () { if (!swiper.params.mousewheel.enabled && swiper.params.cssMode) { disable(); } if (swiper.params.mousewheel.enabled) enable(); }); on('destroy', function () { if (swiper.params.cssMode) { enable(); } if (swiper.mousewheel.enabled) disable(); }); Object.assign(swiper.mousewheel, { enable: enable, disable: disable }); } function Navigation(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on, emit = _ref.emit; extendParams({ navigation: { nextEl: null, prevEl: null, hideOnClick: false, disabledClass: 'swiper-button-disabled', hiddenClass: 'swiper-button-hidden', lockClass: 'swiper-button-lock' } }); swiper.navigation = { nextEl: null, $nextEl: null, prevEl: null, $prevEl: null }; function getEl(el) { var $el; if (el) { $el = $(el); if (swiper.params.uniqueNavElements && typeof el === 'string' && $el.length > 1 && swiper.$el.find(el).length === 1) { $el = swiper.$el.find(el); } } return $el; } function toggleEl($el, disabled) { var params = swiper.params.navigation; if ($el && $el.length > 0) { $el[disabled ? 'addClass' : 'removeClass'](params.disabledClass); if ($el[0] && $el[0].tagName === 'BUTTON') $el[0].disabled = disabled; if (swiper.params.watchOverflow && swiper.enabled) { $el[swiper.isLocked ? 'addClass' : 'removeClass'](params.lockClass); } } } function update() { // Update Navigation Buttons if (swiper.params.loop) return; var _swiper$navigation = swiper.navigation, $nextEl = _swiper$navigation.$nextEl, $prevEl = _swiper$navigation.$prevEl; toggleEl($prevEl, swiper.isBeginning); toggleEl($nextEl, swiper.isEnd); } function onPrevClick(e) { e.preventDefault(); if (swiper.isBeginning && !swiper.params.loop) return; swiper.slidePrev(); } function onNextClick(e) { e.preventDefault(); if (swiper.isEnd && !swiper.params.loop) return; swiper.slideNext(); } function init() { var params = swiper.params.navigation; swiper.params.navigation = createElementIfNotDefined(swiper.$el, swiper.params.navigation, swiper.params.createElements, { nextEl: 'swiper-button-next', prevEl: 'swiper-button-prev' }); if (!(params.nextEl || params.prevEl)) return; var $nextEl = getEl(params.nextEl); var $prevEl = getEl(params.prevEl); if ($nextEl && $nextEl.length > 0) { $nextEl.on('click', onNextClick); } if ($prevEl && $prevEl.length > 0) { $prevEl.on('click', onPrevClick); } Object.assign(swiper.navigation, { $nextEl: $nextEl, nextEl: $nextEl && $nextEl[0], $prevEl: $prevEl, prevEl: $prevEl && $prevEl[0] }); if (!swiper.enabled) { if ($nextEl) $nextEl.addClass(params.lockClass); if ($prevEl) $prevEl.addClass(params.lockClass); } } function destroy() { var _swiper$navigation2 = swiper.navigation, $nextEl = _swiper$navigation2.$nextEl, $prevEl = _swiper$navigation2.$prevEl; if ($nextEl && $nextEl.length) { $nextEl.off('click', onNextClick); $nextEl.removeClass(swiper.params.navigation.disabledClass); } if ($prevEl && $prevEl.length) { $prevEl.off('click', onPrevClick); $prevEl.removeClass(swiper.params.navigation.disabledClass); } } on('init', function () { init(); update(); }); on('toEdge', function () { update(); }); on('fromEdge', function () { update(); }); on('destroy', function () { destroy(); }); on('enable disable', function () { var _swiper$navigation3 = swiper.navigation, $nextEl = _swiper$navigation3.$nextEl, $prevEl = _swiper$navigation3.$prevEl; if ($nextEl) { $nextEl[swiper.enabled ? 'removeClass' : 'addClass'](swiper.params.navigation.lockClass); } if ($prevEl) { $prevEl[swiper.enabled ? 'removeClass' : 'addClass'](swiper.params.navigation.lockClass); } }); on('click', function (_s, e) { var _swiper$navigation4 = swiper.navigation, $nextEl = _swiper$navigation4.$nextEl, $prevEl = _swiper$navigation4.$prevEl; var targetEl = e.target; if (swiper.params.navigation.hideOnClick && !$(targetEl).is($prevEl) && !$(targetEl).is($nextEl)) { if (swiper.pagination && swiper.params.pagination && swiper.params.pagination.clickable && (swiper.pagination.el === targetEl || swiper.pagination.el.contains(targetEl))) return; var isHidden; if ($nextEl) { isHidden = $nextEl.hasClass(swiper.params.navigation.hiddenClass); } else if ($prevEl) { isHidden = $prevEl.hasClass(swiper.params.navigation.hiddenClass); } if (isHidden === true) { emit('navigationShow'); } else { emit('navigationHide'); } if ($nextEl) { $nextEl.toggleClass(swiper.params.navigation.hiddenClass); } if ($prevEl) { $prevEl.toggleClass(swiper.params.navigation.hiddenClass); } } }); Object.assign(swiper.navigation, { update: update, init: init, destroy: destroy }); } function Pagination(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on, emit = _ref.emit; var pfx = 'swiper-pagination'; extendParams({ pagination: { el: null, bulletElement: 'span', clickable: false, hideOnClick: false, renderBullet: null, renderProgressbar: null, renderFraction: null, renderCustom: null, progressbarOpposite: false, type: 'bullets', // 'bullets' or 'progressbar' or 'fraction' or 'custom' dynamicBullets: false, dynamicMainBullets: 1, formatFractionCurrent: function formatFractionCurrent(number) { return number; }, formatFractionTotal: function formatFractionTotal(number) { return number; }, bulletClass: pfx + "-bullet", bulletActiveClass: pfx + "-bullet-active", modifierClass: pfx + "-", currentClass: pfx + "-current", totalClass: pfx + "-total", hiddenClass: pfx + "-hidden", progressbarFillClass: pfx + "-progressbar-fill", progressbarOppositeClass: pfx + "-progressbar-opposite", clickableClass: pfx + "-clickable", lockClass: pfx + "-lock" } }); swiper.pagination = { el: null, $el: null, bullets: [] }; var bulletSize; var dynamicBulletIndex = 0; function isPaginationDisabled() { return !swiper.params.pagination.el || !swiper.pagination.el || !swiper.pagination.$el || swiper.pagination.$el.length === 0; } function setSideBullets($bulletEl, position) { var bulletActiveClass = swiper.params.pagination.bulletActiveClass; $bulletEl[position]().addClass(bulletActiveClass + "-" + position)[position]().addClass(bulletActiveClass + "-" + position + "-" + position); } function update() { // Render || Update Pagination bullets/items var rtl = swiper.rtl; var params = swiper.params.pagination; if (isPaginationDisabled()) return; var slidesLength = swiper.virtual && swiper.params.virtual.enabled ? swiper.virtual.slides.length : swiper.slides.length; var $el = swiper.pagination.$el; // Current/Total var current; var total = swiper.params.loop ? Math.ceil((slidesLength - swiper.loopedSlides * 2) / swiper.params.slidesPerGroup) : swiper.snapGrid.length; if (swiper.params.loop) { current = Math.ceil((swiper.activeIndex - swiper.loopedSlides) / swiper.params.slidesPerGroup); if (current > slidesLength - 1 - swiper.loopedSlides * 2) { current -= slidesLength - swiper.loopedSlides * 2; } if (current > total - 1) current -= total; if (current < 0 && swiper.params.paginationType !== 'bullets') current = total + current; } else if (typeof swiper.snapIndex !== 'undefined') { current = swiper.snapIndex; } else { current = swiper.activeIndex || 0; } // Types if (params.type === 'bullets' && swiper.pagination.bullets && swiper.pagination.bullets.length > 0) { var bullets = swiper.pagination.bullets; var firstIndex; var lastIndex; var midIndex; if (params.dynamicBullets) { bulletSize = bullets.eq(0)[swiper.isHorizontal() ? 'outerWidth' : 'outerHeight'](true); $el.css(swiper.isHorizontal() ? 'width' : 'height', bulletSize * (params.dynamicMainBullets + 4) + "px"); if (params.dynamicMainBullets > 1 && swiper.previousIndex !== undefined) { dynamicBulletIndex += current - swiper.previousIndex; if (dynamicBulletIndex > params.dynamicMainBullets - 1) { dynamicBulletIndex = params.dynamicMainBullets - 1; } else if (dynamicBulletIndex < 0) { dynamicBulletIndex = 0; } } firstIndex = current - dynamicBulletIndex; lastIndex = firstIndex + (Math.min(bullets.length, params.dynamicMainBullets) - 1); midIndex = (lastIndex + firstIndex) / 2; } bullets.removeClass(['', '-next', '-next-next', '-prev', '-prev-prev', '-main'].map(function (suffix) { return "" + params.bulletActiveClass + suffix; }).join(' ')); if ($el.length > 1) { bullets.each(function (bullet) { var $bullet = $(bullet); var bulletIndex = $bullet.index(); if (bulletIndex === current) { $bullet.addClass(params.bulletActiveClass); } if (params.dynamicBullets) { if (bulletIndex >= firstIndex && bulletIndex <= lastIndex) { $bullet.addClass(params.bulletActiveClass + "-main"); } if (bulletIndex === firstIndex) { setSideBullets($bullet, 'prev'); } if (bulletIndex === lastIndex) { setSideBullets($bullet, 'next'); } } }); } else { var $bullet = bullets.eq(current); var bulletIndex = $bullet.index(); $bullet.addClass(params.bulletActiveClass); if (params.dynamicBullets) { var $firstDisplayedBullet = bullets.eq(firstIndex); var $lastDisplayedBullet = bullets.eq(lastIndex); for (var i = firstIndex; i <= lastIndex; i += 1) { bullets.eq(i).addClass(params.bulletActiveClass + "-main"); } if (swiper.params.loop) { if (bulletIndex >= bullets.length - params.dynamicMainBullets) { for (var _i = params.dynamicMainBullets; _i >= 0; _i -= 1) { bullets.eq(bullets.length - _i).addClass(params.bulletActiveClass + "-main"); } bullets.eq(bullets.length - params.dynamicMainBullets - 1).addClass(params.bulletActiveClass + "-prev"); } else { setSideBullets($firstDisplayedBullet, 'prev'); setSideBullets($lastDisplayedBullet, 'next'); } } else { setSideBullets($firstDisplayedBullet, 'prev'); setSideBullets($lastDisplayedBullet, 'next'); } } } if (params.dynamicBullets) { var dynamicBulletsLength = Math.min(bullets.length, params.dynamicMainBullets + 4); var bulletsOffset = (bulletSize * dynamicBulletsLength - bulletSize) / 2 - midIndex * bulletSize; var offsetProp = rtl ? 'right' : 'left'; bullets.css(swiper.isHorizontal() ? offsetProp : 'top', bulletsOffset + "px"); } } if (params.type === 'fraction') { $el.find(classesToSelector(params.currentClass)).text(params.formatFractionCurrent(current + 1)); $el.find(classesToSelector(params.totalClass)).text(params.formatFractionTotal(total)); } if (params.type === 'progressbar') { var progressbarDirection; if (params.progressbarOpposite) { progressbarDirection = swiper.isHorizontal() ? 'vertical' : 'horizontal'; } else { progressbarDirection = swiper.isHorizontal() ? 'horizontal' : 'vertical'; } var scale = (current + 1) / total; var scaleX = 1; var scaleY = 1; if (progressbarDirection === 'horizontal') { scaleX = scale; } else { scaleY = scale; } $el.find(classesToSelector(params.progressbarFillClass)).transform("translate3d(0,0,0) scaleX(" + scaleX + ") scaleY(" + scaleY + ")").transition(swiper.params.speed); } if (params.type === 'custom' && params.renderCustom) { $el.html(params.renderCustom(swiper, current + 1, total)); emit('paginationRender', $el[0]); } else { emit('paginationUpdate', $el[0]); } if (swiper.params.watchOverflow && swiper.enabled) { $el[swiper.isLocked ? 'addClass' : 'removeClass'](params.lockClass); } } function render() { // Render Container var params = swiper.params.pagination; if (isPaginationDisabled()) return; var slidesLength = swiper.virtual && swiper.params.virtual.enabled ? swiper.virtual.slides.length : swiper.slides.length; var $el = swiper.pagination.$el; var paginationHTML = ''; if (params.type === 'bullets') { var numberOfBullets = swiper.params.loop ? Math.ceil((slidesLength - swiper.loopedSlides * 2) / swiper.params.slidesPerGroup) : swiper.snapGrid.length; if (swiper.params.freeMode && swiper.params.freeMode.enabled && !swiper.params.loop && numberOfBullets > slidesLength) { numberOfBullets = slidesLength; } for (var i = 0; i < numberOfBullets; i += 1) { if (params.renderBullet) { paginationHTML += params.renderBullet.call(swiper, i, params.bulletClass); } else { paginationHTML += "<" + params.bulletElement + " class=\"" + params.bulletClass + "\"></" + params.bulletElement + ">"; } } $el.html(paginationHTML); swiper.pagination.bullets = $el.find(classesToSelector(params.bulletClass)); } if (params.type === 'fraction') { if (params.renderFraction) { paginationHTML = params.renderFraction.call(swiper, params.currentClass, params.totalClass); } else { paginationHTML = "<span class=\"" + params.currentClass + "\"></span>" + ' / ' + ("<span class=\"" + params.totalClass + "\"></span>"); } $el.html(paginationHTML); } if (params.type === 'progressbar') { if (params.renderProgressbar) { paginationHTML = params.renderProgressbar.call(swiper, params.progressbarFillClass); } else { paginationHTML = "<span class=\"" + params.progressbarFillClass + "\"></span>"; } $el.html(paginationHTML); } if (params.type !== 'custom') { emit('paginationRender', swiper.pagination.$el[0]); } } function init() { swiper.params.pagination = createElementIfNotDefined(swiper.$el, swiper.params.pagination, swiper.params.createElements, { el: 'swiper-pagination' }); var params = swiper.params.pagination; if (!params.el) return; var $el = $(params.el); if ($el.length === 0) return; if (swiper.params.uniqueNavElements && typeof params.el === 'string' && $el.length > 1) { $el = swiper.$el.find(params.el); } if (params.type === 'bullets' && params.clickable) { $el.addClass(params.clickableClass); } $el.addClass(params.modifierClass + params.type); if (params.type === 'bullets' && params.dynamicBullets) { $el.addClass("" + params.modifierClass + params.type + "-dynamic"); dynamicBulletIndex = 0; if (params.dynamicMainBullets < 1) { params.dynamicMainBullets = 1; } } if (params.type === 'progressbar' && params.progressbarOpposite) { $el.addClass(params.progressbarOppositeClass); } if (params.clickable) { $el.on('click', classesToSelector(params.bulletClass), function onClick(e) { e.preventDefault(); var index = $(this).index() * swiper.params.slidesPerGroup; if (swiper.params.loop) index += swiper.loopedSlides; swiper.slideTo(index); }); } Object.assign(swiper.pagination, { $el: $el, el: $el[0] }); if (!swiper.enabled) { $el.addClass(params.lockClass); } } function destroy() { var params = swiper.params.pagination; if (isPaginationDisabled()) return; var $el = swiper.pagination.$el; $el.removeClass(params.hiddenClass); $el.removeClass(params.modifierClass + params.type); if (swiper.pagination.bullets) swiper.pagination.bullets.removeClass(params.bulletActiveClass); if (params.clickable) { $el.off('click', classesToSelector(params.bulletClass)); } } on('init', function () { init(); render(); update(); }); on('activeIndexChange', function () { if (swiper.params.loop) { update(); } else if (typeof swiper.snapIndex === 'undefined') { update(); } }); on('snapIndexChange', function () { if (!swiper.params.loop) { update(); } }); on('slidesLengthChange', function () { if (swiper.params.loop) { render(); update(); } }); on('snapGridLengthChange', function () { if (!swiper.params.loop) { render(); update(); } }); on('destroy', function () { destroy(); }); on('enable disable', function () { var $el = swiper.pagination.$el; if ($el) { $el[swiper.enabled ? 'removeClass' : 'addClass'](swiper.params.pagination.lockClass); } }); on('click', function (_s, e) { var targetEl = e.target; var $el = swiper.pagination.$el; if (swiper.params.pagination.el && swiper.params.pagination.hideOnClick && $el.length > 0 && !$(targetEl).hasClass(swiper.params.pagination.bulletClass)) { if (swiper.navigation && (swiper.navigation.nextEl && targetEl === swiper.navigation.nextEl || swiper.navigation.prevEl && targetEl === swiper.navigation.prevEl)) return; var isHidden = $el.hasClass(swiper.params.pagination.hiddenClass); if (isHidden === true) { emit('paginationShow'); } else { emit('paginationHide'); } $el.toggleClass(swiper.params.pagination.hiddenClass); } }); Object.assign(swiper.pagination, { render: render, update: update, init: init, destroy: destroy }); } function Scrollbar(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on, emit = _ref.emit; var document = getDocument(); var isTouched = false; var timeout = null; var dragTimeout = null; var dragStartPos; var dragSize; var trackSize; var divider; extendParams({ scrollbar: { el: null, dragSize: 'auto', hide: false, draggable: false, snapOnRelease: true, lockClass: 'swiper-scrollbar-lock', dragClass: 'swiper-scrollbar-drag' } }); swiper.scrollbar = { el: null, dragEl: null, $el: null, $dragEl: null }; function setTranslate() { if (!swiper.params.scrollbar.el || !swiper.scrollbar.el) return; var scrollbar = swiper.scrollbar, rtl = swiper.rtlTranslate, progress = swiper.progress; var $dragEl = scrollbar.$dragEl, $el = scrollbar.$el; var params = swiper.params.scrollbar; var newSize = dragSize; var newPos = (trackSize - dragSize) * progress; if (rtl) { newPos = -newPos; if (newPos > 0) { newSize = dragSize - newPos; newPos = 0; } else if (-newPos + dragSize > trackSize) { newSize = trackSize + newPos; } } else if (newPos < 0) { newSize = dragSize + newPos; newPos = 0; } else if (newPos + dragSize > trackSize) { newSize = trackSize - newPos; } if (swiper.isHorizontal()) { $dragEl.transform("translate3d(" + newPos + "px, 0, 0)"); $dragEl[0].style.width = newSize + "px"; } else { $dragEl.transform("translate3d(0px, " + newPos + "px, 0)"); $dragEl[0].style.height = newSize + "px"; } if (params.hide) { clearTimeout(timeout); $el[0].style.opacity = 1; timeout = setTimeout(function () { $el[0].style.opacity = 0; $el.transition(400); }, 1000); } } function setTransition(duration) { if (!swiper.params.scrollbar.el || !swiper.scrollbar.el) return; swiper.scrollbar.$dragEl.transition(duration); } function updateSize() { if (!swiper.params.scrollbar.el || !swiper.scrollbar.el) return; var scrollbar = swiper.scrollbar; var $dragEl = scrollbar.$dragEl, $el = scrollbar.$el; $dragEl[0].style.width = ''; $dragEl[0].style.height = ''; trackSize = swiper.isHorizontal() ? $el[0].offsetWidth : $el[0].offsetHeight; divider = swiper.size / swiper.virtualSize; if (swiper.params.scrollbar.dragSize === 'auto') { dragSize = trackSize * divider; } else { dragSize = parseInt(swiper.params.scrollbar.dragSize, 10); } if (swiper.isHorizontal()) { $dragEl[0].style.width = dragSize + "px"; } else { $dragEl[0].style.height = dragSize + "px"; } if (divider >= 1) { $el[0].style.display = 'none'; } else { $el[0].style.display = ''; } if (swiper.params.scrollbar.hide) { $el[0].style.opacity = 0; } if (swiper.params.watchOverflow && swiper.enabled) { scrollbar.$el[swiper.isLocked ? 'addClass' : 'removeClass'](swiper.params.scrollbar.lockClass); } } function getPointerPosition(e) { if (swiper.isHorizontal()) { return e.type === 'touchstart' || e.type === 'touchmove' ? e.targetTouches[0].clientX : e.clientX; } return e.type === 'touchstart' || e.type === 'touchmove' ? e.targetTouches[0].clientY : e.clientY; } function setDragPosition(e) { var scrollbar = swiper.scrollbar, rtl = swiper.rtlTranslate; var $el = scrollbar.$el; var positionRatio; positionRatio = (getPointerPosition(e) - $el.offset()[swiper.isHorizontal() ? 'left' : 'top'] - (dragStartPos !== null ? dragStartPos : dragSize / 2)) / (trackSize - dragSize); positionRatio = Math.max(Math.min(positionRatio, 1), 0); if (rtl) { positionRatio = 1 - positionRatio; } var position = swiper.minTranslate() + (swiper.maxTranslate() - swiper.minTranslate()) * positionRatio; swiper.updateProgress(position); swiper.setTranslate(position); swiper.updateActiveIndex(); swiper.updateSlidesClasses(); } function onDragStart(e) { var params = swiper.params.scrollbar; var scrollbar = swiper.scrollbar, $wrapperEl = swiper.$wrapperEl; var $el = scrollbar.$el, $dragEl = scrollbar.$dragEl; isTouched = true; dragStartPos = e.target === $dragEl[0] || e.target === $dragEl ? getPointerPosition(e) - e.target.getBoundingClientRect()[swiper.isHorizontal() ? 'left' : 'top'] : null; e.preventDefault(); e.stopPropagation(); $wrapperEl.transition(100); $dragEl.transition(100); setDragPosition(e); clearTimeout(dragTimeout); $el.transition(0); if (params.hide) { $el.css('opacity', 1); } if (swiper.params.cssMode) { swiper.$wrapperEl.css('scroll-snap-type', 'none'); } emit('scrollbarDragStart', e); } function onDragMove(e) { var scrollbar = swiper.scrollbar, $wrapperEl = swiper.$wrapperEl; var $el = scrollbar.$el, $dragEl = scrollbar.$dragEl; if (!isTouched) return; if (e.preventDefault) e.preventDefault();else e.returnValue = false; setDragPosition(e); $wrapperEl.transition(0); $el.transition(0); $dragEl.transition(0); emit('scrollbarDragMove', e); } function onDragEnd(e) { var params = swiper.params.scrollbar; var scrollbar = swiper.scrollbar, $wrapperEl = swiper.$wrapperEl; var $el = scrollbar.$el; if (!isTouched) return; isTouched = false; if (swiper.params.cssMode) { swiper.$wrapperEl.css('scroll-snap-type', ''); $wrapperEl.transition(''); } if (params.hide) { clearTimeout(dragTimeout); dragTimeout = nextTick(function () { $el.css('opacity', 0); $el.transition(400); }, 1000); } emit('scrollbarDragEnd', e); if (params.snapOnRelease) { swiper.slideToClosest(); } } function events(method) { var scrollbar = swiper.scrollbar, touchEventsTouch = swiper.touchEventsTouch, touchEventsDesktop = swiper.touchEventsDesktop, params = swiper.params, support = swiper.support; var $el = scrollbar.$el; var target = $el[0]; var activeListener = support.passiveListener && params.passiveListeners ? { passive: false, capture: false } : false; var passiveListener = support.passiveListener && params.passiveListeners ? { passive: true, capture: false } : false; if (!target) return; var eventMethod = method === 'on' ? 'addEventListener' : 'removeEventListener'; if (!support.touch) { target[eventMethod](touchEventsDesktop.start, onDragStart, activeListener); document[eventMethod](touchEventsDesktop.move, onDragMove, activeListener); document[eventMethod](touchEventsDesktop.end, onDragEnd, passiveListener); } else { target[eventMethod](touchEventsTouch.start, onDragStart, activeListener); target[eventMethod](touchEventsTouch.move, onDragMove, activeListener); target[eventMethod](touchEventsTouch.end, onDragEnd, passiveListener); } } function enableDraggable() { if (!swiper.params.scrollbar.el) return; events('on'); } function disableDraggable() { if (!swiper.params.scrollbar.el) return; events('off'); } function init() { var scrollbar = swiper.scrollbar, $swiperEl = swiper.$el; swiper.params.scrollbar = createElementIfNotDefined($swiperEl, swiper.params.scrollbar, swiper.params.createElements, { el: 'swiper-scrollbar' }); var params = swiper.params.scrollbar; if (!params.el) return; var $el = $(params.el); if (swiper.params.uniqueNavElements && typeof params.el === 'string' && $el.length > 1 && $swiperEl.find(params.el).length === 1) { $el = $swiperEl.find(params.el); } var $dragEl = $el.find("." + swiper.params.scrollbar.dragClass); if ($dragEl.length === 0) { $dragEl = $("<div class=\"" + swiper.params.scrollbar.dragClass + "\"></div>"); $el.append($dragEl); } Object.assign(scrollbar, { $el: $el, el: $el[0], $dragEl: $dragEl, dragEl: $dragEl[0] }); if (params.draggable) { enableDraggable(); } if ($el) { $el[swiper.enabled ? 'removeClass' : 'addClass'](swiper.params.scrollbar.lockClass); } } function destroy() { disableDraggable(); } on('init', function () { init(); updateSize(); setTranslate(); }); on('update resize observerUpdate', function () { updateSize(); }); on('resize', function () { updateSize(); }); on('observerUpdate', function () { updateSize(); }); on('setTranslate', function () { setTranslate(); }); on('setTransition', function (_s, duration) { setTransition(duration); }); on('enable disable', function () { var $el = swiper.scrollbar.$el; if ($el) { $el[swiper.enabled ? 'removeClass' : 'addClass'](swiper.params.scrollbar.lockClass); } }); on('destroy', function () { destroy(); }); Object.assign(swiper.scrollbar, { updateSize: updateSize, setTranslate: setTranslate, init: init, destroy: destroy }); } function Parallax(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on; extendParams({ parallax: { enabled: false } }); var setTransform = function setTransform(el, progress) { var rtl = swiper.rtl; var $el = $(el); var rtlFactor = rtl ? -1 : 1; var p = $el.attr('data-swiper-parallax') || '0'; var x = $el.attr('data-swiper-parallax-x'); var y = $el.attr('data-swiper-parallax-y'); var scale = $el.attr('data-swiper-parallax-scale'); var opacity = $el.attr('data-swiper-parallax-opacity'); if (x || y) { x = x || '0'; y = y || '0'; } else if (swiper.isHorizontal()) { x = p; y = '0'; } else { y = p; x = '0'; } if (x.indexOf('%') >= 0) { x = parseInt(x, 10) * progress * rtlFactor + "%"; } else { x = x * progress * rtlFactor + "px"; } if (y.indexOf('%') >= 0) { y = parseInt(y, 10) * progress + "%"; } else { y = y * progress + "px"; } if (typeof opacity !== 'undefined' && opacity !== null) { var currentOpacity = opacity - (opacity - 1) * (1 - Math.abs(progress)); $el[0].style.opacity = currentOpacity; } if (typeof scale === 'undefined' || scale === null) { $el.transform("translate3d(" + x + ", " + y + ", 0px)"); } else { var currentScale = scale - (scale - 1) * (1 - Math.abs(progress)); $el.transform("translate3d(" + x + ", " + y + ", 0px) scale(" + currentScale + ")"); } }; var setTranslate = function setTranslate() { var $el = swiper.$el, slides = swiper.slides, progress = swiper.progress, snapGrid = swiper.snapGrid; $el.children('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y], [data-swiper-parallax-opacity], [data-swiper-parallax-scale]').each(function (el) { setTransform(el, progress); }); slides.each(function (slideEl, slideIndex) { var slideProgress = slideEl.progress; if (swiper.params.slidesPerGroup > 1 && swiper.params.slidesPerView !== 'auto') { slideProgress += Math.ceil(slideIndex / 2) - progress * (snapGrid.length - 1); } slideProgress = Math.min(Math.max(slideProgress, -1), 1); $(slideEl).find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y], [data-swiper-parallax-opacity], [data-swiper-parallax-scale]').each(function (el) { setTransform(el, slideProgress); }); }); }; var setTransition = function setTransition(duration) { if (duration === void 0) { duration = swiper.params.speed; } var $el = swiper.$el; $el.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y], [data-swiper-parallax-opacity], [data-swiper-parallax-scale]').each(function (parallaxEl) { var $parallaxEl = $(parallaxEl); var parallaxDuration = parseInt($parallaxEl.attr('data-swiper-parallax-duration'), 10) || duration; if (duration === 0) parallaxDuration = 0; $parallaxEl.transition(parallaxDuration); }); }; on('beforeInit', function () { if (!swiper.params.parallax.enabled) return; swiper.params.watchSlidesProgress = true; swiper.originalParams.watchSlidesProgress = true; }); on('init', function () { if (!swiper.params.parallax.enabled) return; setTranslate(); }); on('setTranslate', function () { if (!swiper.params.parallax.enabled) return; setTranslate(); }); on('setTransition', function (_swiper, duration) { if (!swiper.params.parallax.enabled) return; setTransition(duration); }); } function Zoom(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on, emit = _ref.emit; var window = getWindow(); extendParams({ zoom: { enabled: false, maxRatio: 3, minRatio: 1, toggle: true, containerClass: 'swiper-zoom-container', zoomedSlideClass: 'swiper-slide-zoomed' } }); swiper.zoom = { enabled: false }; var currentScale = 1; var isScaling = false; var gesturesEnabled; var fakeGestureTouched; var fakeGestureMoved; var gesture = { $slideEl: undefined, slideWidth: undefined, slideHeight: undefined, $imageEl: undefined, $imageWrapEl: undefined, maxRatio: 3 }; var image = { isTouched: undefined, isMoved: undefined, currentX: undefined, currentY: undefined, minX: undefined, minY: undefined, maxX: undefined, maxY: undefined, width: undefined, height: undefined, startX: undefined, startY: undefined, touchesStart: {}, touchesCurrent: {} }; var velocity = { x: undefined, y: undefined, prevPositionX: undefined, prevPositionY: undefined, prevTime: undefined }; var scale = 1; Object.defineProperty(swiper.zoom, 'scale', { get: function get() { return scale; }, set: function set(value) { if (scale !== value) { var imageEl = gesture.$imageEl ? gesture.$imageEl[0] : undefined; var slideEl = gesture.$slideEl ? gesture.$slideEl[0] : undefined; emit('zoomChange', value, imageEl, slideEl); } scale = value; } }); function getDistanceBetweenTouches(e) { if (e.targetTouches.length < 2) return 1; var x1 = e.targetTouches[0].pageX; var y1 = e.targetTouches[0].pageY; var x2 = e.targetTouches[1].pageX; var y2 = e.targetTouches[1].pageY; var distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); return distance; } // Events function onGestureStart(e) { var support = swiper.support; var params = swiper.params.zoom; fakeGestureTouched = false; fakeGestureMoved = false; if (!support.gestures) { if (e.type !== 'touchstart' || e.type === 'touchstart' && e.targetTouches.length < 2) { return; } fakeGestureTouched = true; gesture.scaleStart = getDistanceBetweenTouches(e); } if (!gesture.$slideEl || !gesture.$slideEl.length) { gesture.$slideEl = $(e.target).closest("." + swiper.params.slideClass); if (gesture.$slideEl.length === 0) gesture.$slideEl = swiper.slides.eq(swiper.activeIndex); gesture.$imageEl = gesture.$slideEl.find('img, svg, canvas, picture, .swiper-zoom-target'); gesture.$imageWrapEl = gesture.$imageEl.parent("." + params.containerClass); gesture.maxRatio = gesture.$imageWrapEl.attr('data-swiper-zoom') || params.maxRatio; if (gesture.$imageWrapEl.length === 0) { gesture.$imageEl = undefined; return; } } if (gesture.$imageEl) { gesture.$imageEl.transition(0); } isScaling = true; } function onGestureChange(e) { var support = swiper.support; var params = swiper.params.zoom; var zoom = swiper.zoom; if (!support.gestures) { if (e.type !== 'touchmove' || e.type === 'touchmove' && e.targetTouches.length < 2) { return; } fakeGestureMoved = true; gesture.scaleMove = getDistanceBetweenTouches(e); } if (!gesture.$imageEl || gesture.$imageEl.length === 0) { if (e.type === 'gesturechange') onGestureStart(e); return; } if (support.gestures) { zoom.scale = e.scale * currentScale; } else { zoom.scale = gesture.scaleMove / gesture.scaleStart * currentScale; } if (zoom.scale > gesture.maxRatio) { zoom.scale = gesture.maxRatio - 1 + Math.pow(zoom.scale - gesture.maxRatio + 1, 0.5); } if (zoom.scale < params.minRatio) { zoom.scale = params.minRatio + 1 - Math.pow(params.minRatio - zoom.scale + 1, 0.5); } gesture.$imageEl.transform("translate3d(0,0,0) scale(" + zoom.scale + ")"); } function onGestureEnd(e) { var device = swiper.device; var support = swiper.support; var params = swiper.params.zoom; var zoom = swiper.zoom; if (!support.gestures) { if (!fakeGestureTouched || !fakeGestureMoved) { return; } if (e.type !== 'touchend' || e.type === 'touchend' && e.changedTouches.length < 2 && !device.android) { return; } fakeGestureTouched = false; fakeGestureMoved = false; } if (!gesture.$imageEl || gesture.$imageEl.length === 0) return; zoom.scale = Math.max(Math.min(zoom.scale, gesture.maxRatio), params.minRatio); gesture.$imageEl.transition(swiper.params.speed).transform("translate3d(0,0,0) scale(" + zoom.scale + ")"); currentScale = zoom.scale; isScaling = false; if (zoom.scale === 1) gesture.$slideEl = undefined; } function onTouchStart(e) { var device = swiper.device; if (!gesture.$imageEl || gesture.$imageEl.length === 0) return; if (image.isTouched) return; if (device.android && e.cancelable) e.preventDefault(); image.isTouched = true; image.touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX; image.touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY; } function onTouchMove(e) { var zoom = swiper.zoom; if (!gesture.$imageEl || gesture.$imageEl.length === 0) return; swiper.allowClick = false; if (!image.isTouched || !gesture.$slideEl) return; if (!image.isMoved) { image.width = gesture.$imageEl[0].offsetWidth; image.height = gesture.$imageEl[0].offsetHeight; image.startX = getTranslate(gesture.$imageWrapEl[0], 'x') || 0; image.startY = getTranslate(gesture.$imageWrapEl[0], 'y') || 0; gesture.slideWidth = gesture.$slideEl[0].offsetWidth; gesture.slideHeight = gesture.$slideEl[0].offsetHeight; gesture.$imageWrapEl.transition(0); } // Define if we need image drag var scaledWidth = image.width * zoom.scale; var scaledHeight = image.height * zoom.scale; if (scaledWidth < gesture.slideWidth && scaledHeight < gesture.slideHeight) return; image.minX = Math.min(gesture.slideWidth / 2 - scaledWidth / 2, 0); image.maxX = -image.minX; image.minY = Math.min(gesture.slideHeight / 2 - scaledHeight / 2, 0); image.maxY = -image.minY; image.touchesCurrent.x = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX; image.touchesCurrent.y = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY; if (!image.isMoved && !isScaling) { if (swiper.isHorizontal() && (Math.floor(image.minX) === Math.floor(image.startX) && image.touchesCurrent.x < image.touchesStart.x || Math.floor(image.maxX) === Math.floor(image.startX) && image.touchesCurrent.x > image.touchesStart.x)) { image.isTouched = false; return; } if (!swiper.isHorizontal() && (Math.floor(image.minY) === Math.floor(image.startY) && image.touchesCurrent.y < image.touchesStart.y || Math.floor(image.maxY) === Math.floor(image.startY) && image.touchesCurrent.y > image.touchesStart.y)) { image.isTouched = false; return; } } if (e.cancelable) { e.preventDefault(); } e.stopPropagation(); image.isMoved = true; image.currentX = image.touchesCurrent.x - image.touchesStart.x + image.startX; image.currentY = image.touchesCurrent.y - image.touchesStart.y + image.startY; if (image.currentX < image.minX) { image.currentX = image.minX + 1 - Math.pow(image.minX - image.currentX + 1, 0.8); } if (image.currentX > image.maxX) { image.currentX = image.maxX - 1 + Math.pow(image.currentX - image.maxX + 1, 0.8); } if (image.currentY < image.minY) { image.currentY = image.minY + 1 - Math.pow(image.minY - image.currentY + 1, 0.8); } if (image.currentY > image.maxY) { image.currentY = image.maxY - 1 + Math.pow(image.currentY - image.maxY + 1, 0.8); } // Velocity if (!velocity.prevPositionX) velocity.prevPositionX = image.touchesCurrent.x; if (!velocity.prevPositionY) velocity.prevPositionY = image.touchesCurrent.y; if (!velocity.prevTime) velocity.prevTime = Date.now(); velocity.x = (image.touchesCurrent.x - velocity.prevPositionX) / (Date.now() - velocity.prevTime) / 2; velocity.y = (image.touchesCurrent.y - velocity.prevPositionY) / (Date.now() - velocity.prevTime) / 2; if (Math.abs(image.touchesCurrent.x - velocity.prevPositionX) < 2) velocity.x = 0; if (Math.abs(image.touchesCurrent.y - velocity.prevPositionY) < 2) velocity.y = 0; velocity.prevPositionX = image.touchesCurrent.x; velocity.prevPositionY = image.touchesCurrent.y; velocity.prevTime = Date.now(); gesture.$imageWrapEl.transform("translate3d(" + image.currentX + "px, " + image.currentY + "px,0)"); } function onTouchEnd() { var zoom = swiper.zoom; if (!gesture.$imageEl || gesture.$imageEl.length === 0) return; if (!image.isTouched || !image.isMoved) { image.isTouched = false; image.isMoved = false; return; } image.isTouched = false; image.isMoved = false; var momentumDurationX = 300; var momentumDurationY = 300; var momentumDistanceX = velocity.x * momentumDurationX; var newPositionX = image.currentX + momentumDistanceX; var momentumDistanceY = velocity.y * momentumDurationY; var newPositionY = image.currentY + momentumDistanceY; // Fix duration if (velocity.x !== 0) momentumDurationX = Math.abs((newPositionX - image.currentX) / velocity.x); if (velocity.y !== 0) momentumDurationY = Math.abs((newPositionY - image.currentY) / velocity.y); var momentumDuration = Math.max(momentumDurationX, momentumDurationY); image.currentX = newPositionX; image.currentY = newPositionY; // Define if we need image drag var scaledWidth = image.width * zoom.scale; var scaledHeight = image.height * zoom.scale; image.minX = Math.min(gesture.slideWidth / 2 - scaledWidth / 2, 0); image.maxX = -image.minX; image.minY = Math.min(gesture.slideHeight / 2 - scaledHeight / 2, 0); image.maxY = -image.minY; image.currentX = Math.max(Math.min(image.currentX, image.maxX), image.minX); image.currentY = Math.max(Math.min(image.currentY, image.maxY), image.minY); gesture.$imageWrapEl.transition(momentumDuration).transform("translate3d(" + image.currentX + "px, " + image.currentY + "px,0)"); } function onTransitionEnd() { var zoom = swiper.zoom; if (gesture.$slideEl && swiper.previousIndex !== swiper.activeIndex) { if (gesture.$imageEl) { gesture.$imageEl.transform('translate3d(0,0,0) scale(1)'); } if (gesture.$imageWrapEl) { gesture.$imageWrapEl.transform('translate3d(0,0,0)'); } zoom.scale = 1; currentScale = 1; gesture.$slideEl = undefined; gesture.$imageEl = undefined; gesture.$imageWrapEl = undefined; } } function zoomIn(e) { var zoom = swiper.zoom; var params = swiper.params.zoom; if (!gesture.$slideEl) { if (e && e.target) { gesture.$slideEl = $(e.target).closest("." + swiper.params.slideClass); } if (!gesture.$slideEl) { if (swiper.params.virtual && swiper.params.virtual.enabled && swiper.virtual) { gesture.$slideEl = swiper.$wrapperEl.children("." + swiper.params.slideActiveClass); } else { gesture.$slideEl = swiper.slides.eq(swiper.activeIndex); } } gesture.$imageEl = gesture.$slideEl.find('img, svg, canvas, picture, .swiper-zoom-target'); gesture.$imageWrapEl = gesture.$imageEl.parent("." + params.containerClass); } if (!gesture.$imageEl || gesture.$imageEl.length === 0 || !gesture.$imageWrapEl || gesture.$imageWrapEl.length === 0) return; gesture.$slideEl.addClass("" + params.zoomedSlideClass); var touchX; var touchY; var offsetX; var offsetY; var diffX; var diffY; var translateX; var translateY; var imageWidth; var imageHeight; var scaledWidth; var scaledHeight; var translateMinX; var translateMinY; var translateMaxX; var translateMaxY; var slideWidth; var slideHeight; if (typeof image.touchesStart.x === 'undefined' && e) { touchX = e.type === 'touchend' ? e.changedTouches[0].pageX : e.pageX; touchY = e.type === 'touchend' ? e.changedTouches[0].pageY : e.pageY; } else { touchX = image.touchesStart.x; touchY = image.touchesStart.y; } zoom.scale = gesture.$imageWrapEl.attr('data-swiper-zoom') || params.maxRatio; currentScale = gesture.$imageWrapEl.attr('data-swiper-zoom') || params.maxRatio; if (e) { slideWidth = gesture.$slideEl[0].offsetWidth; slideHeight = gesture.$slideEl[0].offsetHeight; offsetX = gesture.$slideEl.offset().left + window.scrollX; offsetY = gesture.$slideEl.offset().top + window.scrollY; diffX = offsetX + slideWidth / 2 - touchX; diffY = offsetY + slideHeight / 2 - touchY; imageWidth = gesture.$imageEl[0].offsetWidth; imageHeight = gesture.$imageEl[0].offsetHeight; scaledWidth = imageWidth * zoom.scale; scaledHeight = imageHeight * zoom.scale; translateMinX = Math.min(slideWidth / 2 - scaledWidth / 2, 0); translateMinY = Math.min(slideHeight / 2 - scaledHeight / 2, 0); translateMaxX = -translateMinX; translateMaxY = -translateMinY; translateX = diffX * zoom.scale; translateY = diffY * zoom.scale; if (translateX < translateMinX) { translateX = translateMinX; } if (translateX > translateMaxX) { translateX = translateMaxX; } if (translateY < translateMinY) { translateY = translateMinY; } if (translateY > translateMaxY) { translateY = translateMaxY; } } else { translateX = 0; translateY = 0; } gesture.$imageWrapEl.transition(300).transform("translate3d(" + translateX + "px, " + translateY + "px,0)"); gesture.$imageEl.transition(300).transform("translate3d(0,0,0) scale(" + zoom.scale + ")"); } function zoomOut() { var zoom = swiper.zoom; var params = swiper.params.zoom; if (!gesture.$slideEl) { if (swiper.params.virtual && swiper.params.virtual.enabled && swiper.virtual) { gesture.$slideEl = swiper.$wrapperEl.children("." + swiper.params.slideActiveClass); } else { gesture.$slideEl = swiper.slides.eq(swiper.activeIndex); } gesture.$imageEl = gesture.$slideEl.find('img, svg, canvas, picture, .swiper-zoom-target'); gesture.$imageWrapEl = gesture.$imageEl.parent("." + params.containerClass); } if (!gesture.$imageEl || gesture.$imageEl.length === 0 || !gesture.$imageWrapEl || gesture.$imageWrapEl.length === 0) return; zoom.scale = 1; currentScale = 1; gesture.$imageWrapEl.transition(300).transform('translate3d(0,0,0)'); gesture.$imageEl.transition(300).transform('translate3d(0,0,0) scale(1)'); gesture.$slideEl.removeClass("" + params.zoomedSlideClass); gesture.$slideEl = undefined; } // Toggle Zoom function zoomToggle(e) { var zoom = swiper.zoom; if (zoom.scale && zoom.scale !== 1) { // Zoom Out zoomOut(); } else { // Zoom In zoomIn(e); } } function getListeners() { var support = swiper.support; var passiveListener = swiper.touchEvents.start === 'touchstart' && support.passiveListener && swiper.params.passiveListeners ? { passive: true, capture: false } : false; var activeListenerWithCapture = support.passiveListener ? { passive: false, capture: true } : true; return { passiveListener: passiveListener, activeListenerWithCapture: activeListenerWithCapture }; } function getSlideSelector() { return "." + swiper.params.slideClass; } function toggleGestures(method) { var _getListeners = getListeners(), passiveListener = _getListeners.passiveListener; var slideSelector = getSlideSelector(); swiper.$wrapperEl[method]('gesturestart', slideSelector, onGestureStart, passiveListener); swiper.$wrapperEl[method]('gesturechange', slideSelector, onGestureChange, passiveListener); swiper.$wrapperEl[method]('gestureend', slideSelector, onGestureEnd, passiveListener); } function enableGestures() { if (gesturesEnabled) return; gesturesEnabled = true; toggleGestures('on'); } function disableGestures() { if (!gesturesEnabled) return; gesturesEnabled = false; toggleGestures('off'); } // Attach/Detach Events function enable() { var zoom = swiper.zoom; if (zoom.enabled) return; zoom.enabled = true; var support = swiper.support; var _getListeners2 = getListeners(), passiveListener = _getListeners2.passiveListener, activeListenerWithCapture = _getListeners2.activeListenerWithCapture; var slideSelector = getSlideSelector(); // Scale image if (support.gestures) { swiper.$wrapperEl.on(swiper.touchEvents.start, enableGestures, passiveListener); swiper.$wrapperEl.on(swiper.touchEvents.end, disableGestures, passiveListener); } else if (swiper.touchEvents.start === 'touchstart') { swiper.$wrapperEl.on(swiper.touchEvents.start, slideSelector, onGestureStart, passiveListener); swiper.$wrapperEl.on(swiper.touchEvents.move, slideSelector, onGestureChange, activeListenerWithCapture); swiper.$wrapperEl.on(swiper.touchEvents.end, slideSelector, onGestureEnd, passiveListener); if (swiper.touchEvents.cancel) { swiper.$wrapperEl.on(swiper.touchEvents.cancel, slideSelector, onGestureEnd, passiveListener); } } // Move image swiper.$wrapperEl.on(swiper.touchEvents.move, "." + swiper.params.zoom.containerClass, onTouchMove, activeListenerWithCapture); } function disable() { var zoom = swiper.zoom; if (!zoom.enabled) return; var support = swiper.support; zoom.enabled = false; var _getListeners3 = getListeners(), passiveListener = _getListeners3.passiveListener, activeListenerWithCapture = _getListeners3.activeListenerWithCapture; var slideSelector = getSlideSelector(); // Scale image if (support.gestures) { swiper.$wrapperEl.off(swiper.touchEvents.start, enableGestures, passiveListener); swiper.$wrapperEl.off(swiper.touchEvents.end, disableGestures, passiveListener); } else if (swiper.touchEvents.start === 'touchstart') { swiper.$wrapperEl.off(swiper.touchEvents.start, slideSelector, onGestureStart, passiveListener); swiper.$wrapperEl.off(swiper.touchEvents.move, slideSelector, onGestureChange, activeListenerWithCapture); swiper.$wrapperEl.off(swiper.touchEvents.end, slideSelector, onGestureEnd, passiveListener); if (swiper.touchEvents.cancel) { swiper.$wrapperEl.off(swiper.touchEvents.cancel, slideSelector, onGestureEnd, passiveListener); } } // Move image swiper.$wrapperEl.off(swiper.touchEvents.move, "." + swiper.params.zoom.containerClass, onTouchMove, activeListenerWithCapture); } on('init', function () { if (swiper.params.zoom.enabled) { enable(); } }); on('destroy', function () { disable(); }); on('touchStart', function (_s, e) { if (!swiper.zoom.enabled) return; onTouchStart(e); }); on('touchEnd', function (_s, e) { if (!swiper.zoom.enabled) return; onTouchEnd(); }); on('doubleTap', function (_s, e) { if (!swiper.animating && swiper.params.zoom.enabled && swiper.zoom.enabled && swiper.params.zoom.toggle) { zoomToggle(e); } }); on('transitionEnd', function () { if (swiper.zoom.enabled && swiper.params.zoom.enabled) { onTransitionEnd(); } }); on('slideChange', function () { if (swiper.zoom.enabled && swiper.params.zoom.enabled && swiper.params.cssMode) { onTransitionEnd(); } }); Object.assign(swiper.zoom, { enable: enable, disable: disable, in: zoomIn, out: zoomOut, toggle: zoomToggle }); } function Lazy(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on, emit = _ref.emit; extendParams({ lazy: { checkInView: false, enabled: false, loadPrevNext: false, loadPrevNextAmount: 1, loadOnTransitionStart: false, scrollingElement: '', elementClass: 'swiper-lazy', loadingClass: 'swiper-lazy-loading', loadedClass: 'swiper-lazy-loaded', preloaderClass: 'swiper-lazy-preloader' } }); swiper.lazy = {}; var scrollHandlerAttached = false; var initialImageLoaded = false; function loadInSlide(index, loadInDuplicate) { if (loadInDuplicate === void 0) { loadInDuplicate = true; } var params = swiper.params.lazy; if (typeof index === 'undefined') return; if (swiper.slides.length === 0) return; var isVirtual = swiper.virtual && swiper.params.virtual.enabled; var $slideEl = isVirtual ? swiper.$wrapperEl.children("." + swiper.params.slideClass + "[data-swiper-slide-index=\"" + index + "\"]") : swiper.slides.eq(index); var $images = $slideEl.find("." + params.elementClass + ":not(." + params.loadedClass + "):not(." + params.loadingClass + ")"); if ($slideEl.hasClass(params.elementClass) && !$slideEl.hasClass(params.loadedClass) && !$slideEl.hasClass(params.loadingClass)) { $images.push($slideEl[0]); } if ($images.length === 0) return; $images.each(function (imageEl) { var $imageEl = $(imageEl); $imageEl.addClass(params.loadingClass); var background = $imageEl.attr('data-background'); var src = $imageEl.attr('data-src'); var srcset = $imageEl.attr('data-srcset'); var sizes = $imageEl.attr('data-sizes'); var $pictureEl = $imageEl.parent('picture'); swiper.loadImage($imageEl[0], src || background, srcset, sizes, false, function () { if (typeof swiper === 'undefined' || swiper === null || !swiper || swiper && !swiper.params || swiper.destroyed) return; if (background) { $imageEl.css('background-image', "url(\"" + background + "\")"); $imageEl.removeAttr('data-background'); } else { if (srcset) { $imageEl.attr('srcset', srcset); $imageEl.removeAttr('data-srcset'); } if (sizes) { $imageEl.attr('sizes', sizes); $imageEl.removeAttr('data-sizes'); } if ($pictureEl.length) { $pictureEl.children('source').each(function (sourceEl) { var $source = $(sourceEl); if ($source.attr('data-srcset')) { $source.attr('srcset', $source.attr('data-srcset')); $source.removeAttr('data-srcset'); } }); } if (src) { $imageEl.attr('src', src); $imageEl.removeAttr('data-src'); } } $imageEl.addClass(params.loadedClass).removeClass(params.loadingClass); $slideEl.find("." + params.preloaderClass).remove(); if (swiper.params.loop && loadInDuplicate) { var slideOriginalIndex = $slideEl.attr('data-swiper-slide-index'); if ($slideEl.hasClass(swiper.params.slideDuplicateClass)) { var originalSlide = swiper.$wrapperEl.children("[data-swiper-slide-index=\"" + slideOriginalIndex + "\"]:not(." + swiper.params.slideDuplicateClass + ")"); loadInSlide(originalSlide.index(), false); } else { var duplicatedSlide = swiper.$wrapperEl.children("." + swiper.params.slideDuplicateClass + "[data-swiper-slide-index=\"" + slideOriginalIndex + "\"]"); loadInSlide(duplicatedSlide.index(), false); } } emit('lazyImageReady', $slideEl[0], $imageEl[0]); if (swiper.params.autoHeight) { swiper.updateAutoHeight(); } }); emit('lazyImageLoad', $slideEl[0], $imageEl[0]); }); } function load() { var $wrapperEl = swiper.$wrapperEl, swiperParams = swiper.params, slides = swiper.slides, activeIndex = swiper.activeIndex; var isVirtual = swiper.virtual && swiperParams.virtual.enabled; var params = swiperParams.lazy; var slidesPerView = swiperParams.slidesPerView; if (slidesPerView === 'auto') { slidesPerView = 0; } function slideExist(index) { if (isVirtual) { if ($wrapperEl.children("." + swiperParams.slideClass + "[data-swiper-slide-index=\"" + index + "\"]").length) { return true; } } else if (slides[index]) return true; return false; } function slideIndex(slideEl) { if (isVirtual) { return $(slideEl).attr('data-swiper-slide-index'); } return $(slideEl).index(); } if (!initialImageLoaded) initialImageLoaded = true; if (swiper.params.watchSlidesVisibility) { $wrapperEl.children("." + swiperParams.slideVisibleClass).each(function (slideEl) { var index = isVirtual ? $(slideEl).attr('data-swiper-slide-index') : $(slideEl).index(); loadInSlide(index); }); } else if (slidesPerView > 1) { for (var i = activeIndex; i < activeIndex + slidesPerView; i += 1) { if (slideExist(i)) loadInSlide(i); } } else { loadInSlide(activeIndex); } if (params.loadPrevNext) { if (slidesPerView > 1 || params.loadPrevNextAmount && params.loadPrevNextAmount > 1) { var amount = params.loadPrevNextAmount; var spv = slidesPerView; var maxIndex = Math.min(activeIndex + spv + Math.max(amount, spv), slides.length); var minIndex = Math.max(activeIndex - Math.max(spv, amount), 0); // Next Slides for (var _i = activeIndex + slidesPerView; _i < maxIndex; _i += 1) { if (slideExist(_i)) loadInSlide(_i); } // Prev Slides for (var _i2 = minIndex; _i2 < activeIndex; _i2 += 1) { if (slideExist(_i2)) loadInSlide(_i2); } } else { var nextSlide = $wrapperEl.children("." + swiperParams.slideNextClass); if (nextSlide.length > 0) loadInSlide(slideIndex(nextSlide)); var prevSlide = $wrapperEl.children("." + swiperParams.slidePrevClass); if (prevSlide.length > 0) loadInSlide(slideIndex(prevSlide)); } } } function checkInViewOnLoad() { var window = getWindow(); if (!swiper || swiper.destroyed) return; var $scrollElement = swiper.params.lazy.scrollingElement ? $(swiper.params.lazy.scrollingElement) : $(window); var isWindow = $scrollElement[0] === window; var scrollElementWidth = isWindow ? window.innerWidth : $scrollElement[0].offsetWidth; var scrollElementHeight = isWindow ? window.innerHeight : $scrollElement[0].offsetHeight; var swiperOffset = swiper.$el.offset(); var rtl = swiper.rtlTranslate; var inView = false; if (rtl) swiperOffset.left -= swiper.$el[0].scrollLeft; var swiperCoord = [[swiperOffset.left, swiperOffset.top], [swiperOffset.left + swiper.width, swiperOffset.top], [swiperOffset.left, swiperOffset.top + swiper.height], [swiperOffset.left + swiper.width, swiperOffset.top + swiper.height]]; for (var i = 0; i < swiperCoord.length; i += 1) { var point = swiperCoord[i]; if (point[0] >= 0 && point[0] <= scrollElementWidth && point[1] >= 0 && point[1] <= scrollElementHeight) { if (point[0] === 0 && point[1] === 0) continue; // eslint-disable-line inView = true; } } var passiveListener = swiper.touchEvents.start === 'touchstart' && swiper.support.passiveListener && swiper.params.passiveListeners ? { passive: true, capture: false } : false; if (inView) { load(); $scrollElement.off('scroll', checkInViewOnLoad, passiveListener); } else if (!scrollHandlerAttached) { scrollHandlerAttached = true; $scrollElement.on('scroll', checkInViewOnLoad, passiveListener); } } on('beforeInit', function () { if (swiper.params.lazy.enabled && swiper.params.preloadImages) { swiper.params.preloadImages = false; } }); on('init', function () { if (swiper.params.lazy.enabled && !swiper.params.loop && swiper.params.initialSlide === 0) { if (swiper.params.lazy.checkInView) { checkInViewOnLoad(); } else { load(); } } }); on('scroll', function () { if (swiper.params.freeMode && swiper.params.freeMode.enabled && !swiper.params.freeMode.sticky) { load(); } }); on('scrollbarDragMove resize _freeModeNoMomentumRelease', function () { if (swiper.params.lazy.enabled) { load(); } }); on('transitionStart', function () { if (swiper.params.lazy.enabled) { if (swiper.params.lazy.loadOnTransitionStart || !swiper.params.lazy.loadOnTransitionStart && !initialImageLoaded) { load(); } } }); on('transitionEnd', function () { if (swiper.params.lazy.enabled && !swiper.params.lazy.loadOnTransitionStart) { load(); } }); on('slideChange', function () { var _swiper$params = swiper.params, lazy = _swiper$params.lazy, cssMode = _swiper$params.cssMode, watchSlidesVisibility = _swiper$params.watchSlidesVisibility, watchSlidesProgress = _swiper$params.watchSlidesProgress, touchReleaseOnEdges = _swiper$params.touchReleaseOnEdges, resistanceRatio = _swiper$params.resistanceRatio; if (lazy.enabled && (cssMode || (watchSlidesVisibility || watchSlidesProgress) && (touchReleaseOnEdges || resistanceRatio === 0))) { load(); } }); Object.assign(swiper.lazy, { load: load, loadInSlide: loadInSlide }); } /* eslint no-bitwise: ["error", { "allow": [">>"] }] */ function Controller(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on; extendParams({ controller: { control: undefined, inverse: false, by: 'slide' // or 'container' } }); swiper.controller = { control: undefined }; function LinearSpline(x, y) { var binarySearch = function search() { var maxIndex; var minIndex; var guess; return function (array, val) { minIndex = -1; maxIndex = array.length; while (maxIndex - minIndex > 1) { guess = maxIndex + minIndex >> 1; if (array[guess] <= val) { minIndex = guess; } else { maxIndex = guess; } } return maxIndex; }; }(); this.x = x; this.y = y; this.lastIndex = x.length - 1; // Given an x value (x2), return the expected y2 value: // (x1,y1) is the known point before given value, // (x3,y3) is the known point after given value. var i1; var i3; this.interpolate = function interpolate(x2) { if (!x2) return 0; // Get the indexes of x1 and x3 (the array indexes before and after given x2): i3 = binarySearch(this.x, x2); i1 = i3 - 1; // We have our indexes i1 & i3, so we can calculate already: // y2 := ((x2−x1) × (y3−y1)) ÷ (x3−x1) + y1 return (x2 - this.x[i1]) * (this.y[i3] - this.y[i1]) / (this.x[i3] - this.x[i1]) + this.y[i1]; }; return this; } // xxx: for now i will just save one spline function to to function getInterpolateFunction(c) { if (!swiper.controller.spline) { swiper.controller.spline = swiper.params.loop ? new LinearSpline(swiper.slidesGrid, c.slidesGrid) : new LinearSpline(swiper.snapGrid, c.snapGrid); } } function setTranslate(_t, byController) { var controlled = swiper.controller.control; var multiplier; var controlledTranslate; var Swiper = swiper.constructor; function setControlledTranslate(c) { // this will create an Interpolate function based on the snapGrids // x is the Grid of the scrolled scroller and y will be the controlled scroller // it makes sense to create this only once and recall it for the interpolation // the function does a lot of value caching for performance var translate = swiper.rtlTranslate ? -swiper.translate : swiper.translate; if (swiper.params.controller.by === 'slide') { getInterpolateFunction(c); // i am not sure why the values have to be multiplicated this way, tried to invert the snapGrid // but it did not work out controlledTranslate = -swiper.controller.spline.interpolate(-translate); } if (!controlledTranslate || swiper.params.controller.by === 'container') { multiplier = (c.maxTranslate() - c.minTranslate()) / (swiper.maxTranslate() - swiper.minTranslate()); controlledTranslate = (translate - swiper.minTranslate()) * multiplier + c.minTranslate(); } if (swiper.params.controller.inverse) { controlledTranslate = c.maxTranslate() - controlledTranslate; } c.updateProgress(controlledTranslate); c.setTranslate(controlledTranslate, swiper); c.updateActiveIndex(); c.updateSlidesClasses(); } if (Array.isArray(controlled)) { for (var i = 0; i < controlled.length; i += 1) { if (controlled[i] !== byController && controlled[i] instanceof Swiper) { setControlledTranslate(controlled[i]); } } } else if (controlled instanceof Swiper && byController !== controlled) { setControlledTranslate(controlled); } } function setTransition(duration, byController) { var Swiper = swiper.constructor; var controlled = swiper.controller.control; var i; function setControlledTransition(c) { c.setTransition(duration, swiper); if (duration !== 0) { c.transitionStart(); if (c.params.autoHeight) { nextTick(function () { c.updateAutoHeight(); }); } c.$wrapperEl.transitionEnd(function () { if (!controlled) return; if (c.params.loop && swiper.params.controller.by === 'slide') { c.loopFix(); } c.transitionEnd(); }); } } if (Array.isArray(controlled)) { for (i = 0; i < controlled.length; i += 1) { if (controlled[i] !== byController && controlled[i] instanceof Swiper) { setControlledTransition(controlled[i]); } } } else if (controlled instanceof Swiper && byController !== controlled) { setControlledTransition(controlled); } } function removeSpline() { if (!swiper.controller.control) return; if (swiper.controller.spline) { swiper.controller.spline = undefined; delete swiper.controller.spline; } } on('beforeInit', function () { swiper.controller.control = swiper.params.controller.control; }); on('update', function () { removeSpline(); }); on('resize', function () { removeSpline(); }); on('observerUpdate', function () { removeSpline(); }); on('setTranslate', function (_s, translate, byController) { if (!swiper.controller.control) return; swiper.controller.setTranslate(translate, byController); }); on('setTransition', function (_s, duration, byController) { if (!swiper.controller.control) return; swiper.controller.setTransition(duration, byController); }); Object.assign(swiper.controller, { setTranslate: setTranslate, setTransition: setTransition }); } function A11y(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on; extendParams({ a11y: { enabled: true, notificationClass: 'swiper-notification', prevSlideMessage: 'Previous slide', nextSlideMessage: 'Next slide', firstSlideMessage: 'This is the first slide', lastSlideMessage: 'This is the last slide', paginationBulletMessage: 'Go to slide {{index}}', slideLabelMessage: '{{index}} / {{slidesLength}}', containerMessage: null, containerRoleDescriptionMessage: null, itemRoleDescriptionMessage: null, slideRole: 'group' } }); var liveRegion = null; function notify(message) { var notification = liveRegion; if (notification.length === 0) return; notification.html(''); notification.html(message); } function getRandomNumber(size) { if (size === void 0) { size = 16; } var randomChar = function randomChar() { return Math.round(16 * Math.random()).toString(16); }; return 'x'.repeat(size).replace(/x/g, randomChar); } function makeElFocusable($el) { $el.attr('tabIndex', '0'); } function makeElNotFocusable($el) { $el.attr('tabIndex', '-1'); } function addElRole($el, role) { $el.attr('role', role); } function addElRoleDescription($el, description) { $el.attr('aria-roledescription', description); } function addElControls($el, controls) { $el.attr('aria-controls', controls); } function addElLabel($el, label) { $el.attr('aria-label', label); } function addElId($el, id) { $el.attr('id', id); } function addElLive($el, live) { $el.attr('aria-live', live); } function disableEl($el) { $el.attr('aria-disabled', true); } function enableEl($el) { $el.attr('aria-disabled', false); } function onEnterOrSpaceKey(e) { if (e.keyCode !== 13 && e.keyCode !== 32) return; var params = swiper.params.a11y; var $targetEl = $(e.target); if (swiper.navigation && swiper.navigation.$nextEl && $targetEl.is(swiper.navigation.$nextEl)) { if (!(swiper.isEnd && !swiper.params.loop)) { swiper.slideNext(); } if (swiper.isEnd) { notify(params.lastSlideMessage); } else { notify(params.nextSlideMessage); } } if (swiper.navigation && swiper.navigation.$prevEl && $targetEl.is(swiper.navigation.$prevEl)) { if (!(swiper.isBeginning && !swiper.params.loop)) { swiper.slidePrev(); } if (swiper.isBeginning) { notify(params.firstSlideMessage); } else { notify(params.prevSlideMessage); } } if (swiper.pagination && $targetEl.is(classesToSelector(swiper.params.pagination.bulletClass))) { $targetEl[0].click(); } } function updateNavigation() { if (swiper.params.loop || !swiper.navigation) return; var _swiper$navigation = swiper.navigation, $nextEl = _swiper$navigation.$nextEl, $prevEl = _swiper$navigation.$prevEl; if ($prevEl && $prevEl.length > 0) { if (swiper.isBeginning) { disableEl($prevEl); makeElNotFocusable($prevEl); } else { enableEl($prevEl); makeElFocusable($prevEl); } } if ($nextEl && $nextEl.length > 0) { if (swiper.isEnd) { disableEl($nextEl); makeElNotFocusable($nextEl); } else { enableEl($nextEl); makeElFocusable($nextEl); } } } function hasPagination() { return swiper.pagination && swiper.params.pagination.clickable && swiper.pagination.bullets && swiper.pagination.bullets.length; } function updatePagination() { var params = swiper.params.a11y; if (hasPagination()) { swiper.pagination.bullets.each(function (bulletEl) { var $bulletEl = $(bulletEl); makeElFocusable($bulletEl); if (!swiper.params.pagination.renderBullet) { addElRole($bulletEl, 'button'); addElLabel($bulletEl, params.paginationBulletMessage.replace(/\{\{index\}\}/, $bulletEl.index() + 1)); } }); } } var initNavEl = function initNavEl($el, wrapperId, message) { makeElFocusable($el); if ($el[0].tagName !== 'BUTTON') { addElRole($el, 'button'); $el.on('keydown', onEnterOrSpaceKey); } addElLabel($el, message); addElControls($el, wrapperId); }; function init() { var params = swiper.params.a11y; swiper.$el.append(liveRegion); // Container var $containerEl = swiper.$el; if (params.containerRoleDescriptionMessage) { addElRoleDescription($containerEl, params.containerRoleDescriptionMessage); } if (params.containerMessage) { addElLabel($containerEl, params.containerMessage); } // Wrapper var $wrapperEl = swiper.$wrapperEl; var wrapperId = $wrapperEl.attr('id') || "swiper-wrapper-" + getRandomNumber(16); var live = swiper.params.autoplay && swiper.params.autoplay.enabled ? 'off' : 'polite'; addElId($wrapperEl, wrapperId); addElLive($wrapperEl, live); // Slide if (params.itemRoleDescriptionMessage) { addElRoleDescription($(swiper.slides), params.itemRoleDescriptionMessage); } addElRole($(swiper.slides), params.slideRole); var slidesLength = swiper.params.loop ? swiper.slides.filter(function (el) { return !el.classList.contains(swiper.params.slideDuplicateClass); }).length : swiper.slides.length; swiper.slides.each(function (slideEl, index) { var $slideEl = $(slideEl); var slideIndex = swiper.params.loop ? parseInt($slideEl.attr('data-swiper-slide-index'), 10) : index; var ariaLabelMessage = params.slideLabelMessage.replace(/\{\{index\}\}/, slideIndex + 1).replace(/\{\{slidesLength\}\}/, slidesLength); addElLabel($slideEl, ariaLabelMessage); }); // Navigation var $nextEl; var $prevEl; if (swiper.navigation && swiper.navigation.$nextEl) { $nextEl = swiper.navigation.$nextEl; } if (swiper.navigation && swiper.navigation.$prevEl) { $prevEl = swiper.navigation.$prevEl; } if ($nextEl && $nextEl.length) { initNavEl($nextEl, params.nextSlideMessage); } if ($prevEl && $prevEl.length) { initNavEl($prevEl, params.prevSlideMessage); } // Pagination if (hasPagination()) { swiper.pagination.$el.on('keydown', classesToSelector(swiper.params.pagination.bulletClass), onEnterOrSpaceKey); } } function destroy() { if (liveRegion && liveRegion.length > 0) liveRegion.remove(); var $nextEl; var $prevEl; if (swiper.navigation && swiper.navigation.$nextEl) { $nextEl = swiper.navigation.$nextEl; } if (swiper.navigation && swiper.navigation.$prevEl) { $prevEl = swiper.navigation.$prevEl; } if ($nextEl) { $nextEl.off('keydown', onEnterOrSpaceKey); } if ($prevEl) { $prevEl.off('keydown', onEnterOrSpaceKey); } // Pagination if (hasPagination()) { swiper.pagination.$el.off('keydown', classesToSelector(swiper.params.pagination.bulletClass), onEnterOrSpaceKey); } } on('beforeInit', function () { liveRegion = $("<span class=\"" + swiper.params.a11y.notificationClass + "\" aria-live=\"assertive\" aria-atomic=\"true\"></span>"); }); on('afterInit', function () { if (!swiper.params.a11y.enabled) return; init(); updateNavigation(); }); on('toEdge', function () { if (!swiper.params.a11y.enabled) return; updateNavigation(); }); on('fromEdge', function () { if (!swiper.params.a11y.enabled) return; updateNavigation(); }); on('paginationUpdate', function () { if (!swiper.params.a11y.enabled) return; updatePagination(); }); on('destroy', function () { if (!swiper.params.a11y.enabled) return; destroy(); }); } function History(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on; extendParams({ history: { enabled: false, root: '', replaceState: false, key: 'slides' } }); var initialized = false; var paths = {}; var slugify = function slugify(text) { return text.toString().replace(/\s+/g, '-').replace(/[^\w-]+/g, '').replace(/--+/g, '-').replace(/^-+/, '').replace(/-+$/, ''); }; var getPathValues = function getPathValues(urlOverride) { var window = getWindow(); var location; if (urlOverride) { location = new URL(urlOverride); } else { location = window.location; } var pathArray = location.pathname.slice(1).split('/').filter(function (part) { return part !== ''; }); var total = pathArray.length; var key = pathArray[total - 2]; var value = pathArray[total - 1]; return { key: key, value: value }; }; var setHistory = function setHistory(key, index) { var window = getWindow(); if (!initialized || !swiper.params.history.enabled) return; var location; if (swiper.params.url) { location = new URL(swiper.params.url); } else { location = window.location; } var slide = swiper.slides.eq(index); var value = slugify(slide.attr('data-history')); if (swiper.params.history.root.length > 0) { var root = swiper.params.history.root; if (root[root.length - 1] === '/') root = root.slice(0, root.length - 1); value = root + "/" + key + "/" + value; } else if (!location.pathname.includes(key)) { value = key + "/" + value; } var currentState = window.history.state; if (currentState && currentState.value === value) { return; } if (swiper.params.history.replaceState) { window.history.replaceState({ value: value }, null, value); } else { window.history.pushState({ value: value }, null, value); } }; var scrollToSlide = function scrollToSlide(speed, value, runCallbacks) { if (value) { for (var i = 0, length = swiper.slides.length; i < length; i += 1) { var slide = swiper.slides.eq(i); var slideHistory = slugify(slide.attr('data-history')); if (slideHistory === value && !slide.hasClass(swiper.params.slideDuplicateClass)) { var index = slide.index(); swiper.slideTo(index, speed, runCallbacks); } } } else { swiper.slideTo(0, speed, runCallbacks); } }; var setHistoryPopState = function setHistoryPopState() { paths = getPathValues(swiper.params.url); scrollToSlide(swiper.params.speed, swiper.paths.value, false); }; var init = function init() { var window = getWindow(); if (!swiper.params.history) return; if (!window.history || !window.history.pushState) { swiper.params.history.enabled = false; swiper.params.hashNavigation.enabled = true; return; } initialized = true; paths = getPathValues(swiper.params.url); if (!paths.key && !paths.value) return; scrollToSlide(0, paths.value, swiper.params.runCallbacksOnInit); if (!swiper.params.history.replaceState) { window.addEventListener('popstate', setHistoryPopState); } }; var destroy = function destroy() { var window = getWindow(); if (!swiper.params.history.replaceState) { window.removeEventListener('popstate', setHistoryPopState); } }; on('init', function () { if (swiper.params.history.enabled) { init(); } }); on('destroy', function () { if (swiper.params.history.enabled) { destroy(); } }); on('transitionEnd _freeModeNoMomentumRelease', function () { if (initialized) { setHistory(swiper.params.history.key, swiper.activeIndex); } }); on('slideChange', function () { if (initialized && swiper.params.cssMode) { setHistory(swiper.params.history.key, swiper.activeIndex); } }); } function HashNavigation(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, emit = _ref.emit, on = _ref.on; var initialized = false; var document = getDocument(); var window = getWindow(); extendParams({ hashNavigation: { enabled: false, replaceState: false, watchState: false } }); var onHashChange = function onHashChange() { emit('hashChange'); var newHash = document.location.hash.replace('#', ''); var activeSlideHash = swiper.slides.eq(swiper.activeIndex).attr('data-hash'); if (newHash !== activeSlideHash) { var newIndex = swiper.$wrapperEl.children("." + swiper.params.slideClass + "[data-hash=\"" + newHash + "\"]").index(); if (typeof newIndex === 'undefined') return; swiper.slideTo(newIndex); } }; var setHash = function setHash() { if (!initialized || !swiper.params.hashNavigation.enabled) return; if (swiper.params.hashNavigation.replaceState && window.history && window.history.replaceState) { window.history.replaceState(null, null, "#" + swiper.slides.eq(swiper.activeIndex).attr('data-hash') || ''); emit('hashSet'); } else { var slide = swiper.slides.eq(swiper.activeIndex); var hash = slide.attr('data-hash') || slide.attr('data-history'); document.location.hash = hash || ''; emit('hashSet'); } }; var init = function init() { if (!swiper.params.hashNavigation.enabled || swiper.params.history && swiper.params.history.enabled) return; initialized = true; var hash = document.location.hash.replace('#', ''); if (hash) { var speed = 0; for (var i = 0, length = swiper.slides.length; i < length; i += 1) { var slide = swiper.slides.eq(i); var slideHash = slide.attr('data-hash') || slide.attr('data-history'); if (slideHash === hash && !slide.hasClass(swiper.params.slideDuplicateClass)) { var index = slide.index(); swiper.slideTo(index, speed, swiper.params.runCallbacksOnInit, true); } } } if (swiper.params.hashNavigation.watchState) { $(window).on('hashchange', onHashChange); } }; var destroy = function destroy() { if (swiper.params.hashNavigation.watchState) { $(window).off('hashchange', onHashChange); } }; on('init', function () { if (swiper.params.hashNavigation.enabled) { init(); } }); on('destroy', function () { if (swiper.params.hashNavigation.enabled) { destroy(); } }); on('transitionEnd _freeModeNoMomentumRelease', function () { if (initialized) { setHash(); } }); on('slideChange', function () { if (initialized && swiper.params.cssMode) { setHash(); } }); } /* eslint no-underscore-dangle: "off" */ function Autoplay(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on, emit = _ref.emit; var timeout; swiper.autoplay = { running: false, paused: false }; extendParams({ autoplay: { enabled: false, delay: 3000, waitForTransition: true, disableOnInteraction: true, stopOnLastSlide: false, reverseDirection: false, pauseOnMouseEnter: false } }); function run() { var $activeSlideEl = swiper.slides.eq(swiper.activeIndex); var delay = swiper.params.autoplay.delay; if ($activeSlideEl.attr('data-swiper-autoplay')) { delay = $activeSlideEl.attr('data-swiper-autoplay') || swiper.params.autoplay.delay; } clearTimeout(timeout); timeout = nextTick(function () { var autoplayResult; if (swiper.params.autoplay.reverseDirection) { if (swiper.params.loop) { swiper.loopFix(); autoplayResult = swiper.slidePrev(swiper.params.speed, true, true); emit('autoplay'); } else if (!swiper.isBeginning) { autoplayResult = swiper.slidePrev(swiper.params.speed, true, true); emit('autoplay'); } else if (!swiper.params.autoplay.stopOnLastSlide) { autoplayResult = swiper.slideTo(swiper.slides.length - 1, swiper.params.speed, true, true); emit('autoplay'); } else { stop(); } } else if (swiper.params.loop) { swiper.loopFix(); autoplayResult = swiper.slideNext(swiper.params.speed, true, true); emit('autoplay'); } else if (!swiper.isEnd) { autoplayResult = swiper.slideNext(swiper.params.speed, true, true); emit('autoplay'); } else if (!swiper.params.autoplay.stopOnLastSlide) { autoplayResult = swiper.slideTo(0, swiper.params.speed, true, true); emit('autoplay'); } else { stop(); } if (swiper.params.cssMode && swiper.autoplay.running) run();else if (autoplayResult === false) { run(); } }, delay); } function start() { if (typeof timeout !== 'undefined') return false; if (swiper.autoplay.running) return false; swiper.autoplay.running = true; emit('autoplayStart'); run(); return true; } function stop() { if (!swiper.autoplay.running) return false; if (typeof timeout === 'undefined') return false; if (timeout) { clearTimeout(timeout); timeout = undefined; } swiper.autoplay.running = false; emit('autoplayStop'); return true; } function pause(speed) { if (!swiper.autoplay.running) return; if (swiper.autoplay.paused) return; if (timeout) clearTimeout(timeout); swiper.autoplay.paused = true; if (speed === 0 || !swiper.params.autoplay.waitForTransition) { swiper.autoplay.paused = false; run(); } else { ['transitionend', 'webkitTransitionEnd'].forEach(function (event) { swiper.$wrapperEl[0].addEventListener(event, onTransitionEnd); }); } } function onVisibilityChange() { var document = getDocument(); if (document.visibilityState === 'hidden' && swiper.autoplay.running) { pause(); } if (document.visibilityState === 'visible' && swiper.autoplay.paused) { run(); swiper.autoplay.paused = false; } } function onTransitionEnd(e) { if (!swiper || swiper.destroyed || !swiper.$wrapperEl) return; if (e.target !== swiper.$wrapperEl[0]) return; ['transitionend', 'webkitTransitionEnd'].forEach(function (event) { swiper.$wrapperEl[0].removeEventListener(event, onTransitionEnd); }); swiper.autoplay.paused = false; if (!swiper.autoplay.running) { stop(); } else { run(); } } function onMouseEnter() { if (swiper.params.autoplay.disableOnInteraction) { stop(); } else { pause(); } ['transitionend', 'webkitTransitionEnd'].forEach(function (event) { swiper.$wrapperEl[0].removeEventListener(event, onTransitionEnd); }); } function onMouseLeave() { if (swiper.params.autoplay.disableOnInteraction) { return; } swiper.autoplay.paused = false; run(); } function attachMouseEvents() { if (swiper.params.autoplay.pauseOnMouseEnter) { swiper.$el.on('mouseenter', onMouseEnter); swiper.$el.on('mouseleave', onMouseLeave); } } function detachMouseEvents() { swiper.$el.off('mouseenter', onMouseEnter); swiper.$el.off('mouseleave', onMouseLeave); } on('init', function () { if (swiper.params.autoplay.enabled) { start(); var document = getDocument(); document.addEventListener('visibilitychange', onVisibilityChange); attachMouseEvents(); } }); on('beforeTransitionStart', function (_s, speed, internal) { if (swiper.autoplay.running) { if (internal || !swiper.params.autoplay.disableOnInteraction) { swiper.autoplay.pause(speed); } else { stop(); } } }); on('sliderFirstMove', function () { if (swiper.autoplay.running) { if (swiper.params.autoplay.disableOnInteraction) { stop(); } else { pause(); } } }); on('touchEnd', function () { if (swiper.params.cssMode && swiper.autoplay.paused && !swiper.params.autoplay.disableOnInteraction) { run(); } }); on('destroy', function () { detachMouseEvents(); if (swiper.autoplay.running) { stop(); } var document = getDocument(); document.removeEventListener('visibilitychange', onVisibilityChange); }); Object.assign(swiper.autoplay, { pause: pause, run: run, stop: stop }); } function Fade(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on; extendParams({ fadeEffect: { crossFade: false } }); var setTranslate = function setTranslate() { var slides = swiper.slides; for (var i = 0; i < slides.length; i += 1) { var $slideEl = swiper.slides.eq(i); var offset = $slideEl[0].swiperSlideOffset; var tx = -offset; if (!swiper.params.virtualTranslate) tx -= swiper.translate; var ty = 0; if (!swiper.isHorizontal()) { ty = tx; tx = 0; } var slideOpacity = swiper.params.fadeEffect.crossFade ? Math.max(1 - Math.abs($slideEl[0].progress), 0) : 1 + Math.min(Math.max($slideEl[0].progress, -1), 0); $slideEl.css({ opacity: slideOpacity }).transform("translate3d(" + tx + "px, " + ty + "px, 0px)"); } }; var setTransition = function setTransition(duration) { var slides = swiper.slides, $wrapperEl = swiper.$wrapperEl; slides.transition(duration); if (swiper.params.virtualTranslate && duration !== 0) { var eventTriggered = false; slides.transitionEnd(function () { if (eventTriggered) return; if (!swiper || swiper.destroyed) return; eventTriggered = true; swiper.animating = false; var triggerEvents = ['webkitTransitionEnd', 'transitionend']; for (var i = 0; i < triggerEvents.length; i += 1) { $wrapperEl.trigger(triggerEvents[i]); } }); } }; on('beforeInit', function () { if (swiper.params.effect !== 'fade') return; swiper.classNames.push(swiper.params.containerModifierClass + "fade"); var overwriteParams = { slidesPerView: 1, slidesPerColumn: 1, slidesPerGroup: 1, watchSlidesProgress: true, spaceBetween: 0, virtualTranslate: true }; Object.assign(swiper.params, overwriteParams); Object.assign(swiper.originalParams, overwriteParams); }); on('setTranslate', function () { if (swiper.params.effect !== 'fade') return; setTranslate(); }); on('setTransition', function (_s, duration) { if (swiper.params.effect !== 'fade') return; setTransition(duration); }); } function Cube(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on; extendParams({ cubeEffect: { slideShadows: true, shadow: true, shadowOffset: 20, shadowScale: 0.94 } }); var setTranslate = function setTranslate() { var $el = swiper.$el, $wrapperEl = swiper.$wrapperEl, slides = swiper.slides, swiperWidth = swiper.width, swiperHeight = swiper.height, rtl = swiper.rtlTranslate, swiperSize = swiper.size, browser = swiper.browser; var params = swiper.params.cubeEffect; var isHorizontal = swiper.isHorizontal(); var isVirtual = swiper.virtual && swiper.params.virtual.enabled; var wrapperRotate = 0; var $cubeShadowEl; if (params.shadow) { if (isHorizontal) { $cubeShadowEl = $wrapperEl.find('.swiper-cube-shadow'); if ($cubeShadowEl.length === 0) { $cubeShadowEl = $('<div class="swiper-cube-shadow"></div>'); $wrapperEl.append($cubeShadowEl); } $cubeShadowEl.css({ height: swiperWidth + "px" }); } else { $cubeShadowEl = $el.find('.swiper-cube-shadow'); if ($cubeShadowEl.length === 0) { $cubeShadowEl = $('<div class="swiper-cube-shadow"></div>'); $el.append($cubeShadowEl); } } } for (var i = 0; i < slides.length; i += 1) { var $slideEl = slides.eq(i); var slideIndex = i; if (isVirtual) { slideIndex = parseInt($slideEl.attr('data-swiper-slide-index'), 10); } var slideAngle = slideIndex * 90; var round = Math.floor(slideAngle / 360); if (rtl) { slideAngle = -slideAngle; round = Math.floor(-slideAngle / 360); } var progress = Math.max(Math.min($slideEl[0].progress, 1), -1); var tx = 0; var ty = 0; var tz = 0; if (slideIndex % 4 === 0) { tx = -round * 4 * swiperSize; tz = 0; } else if ((slideIndex - 1) % 4 === 0) { tx = 0; tz = -round * 4 * swiperSize; } else if ((slideIndex - 2) % 4 === 0) { tx = swiperSize + round * 4 * swiperSize; tz = swiperSize; } else if ((slideIndex - 3) % 4 === 0) { tx = -swiperSize; tz = 3 * swiperSize + swiperSize * 4 * round; } if (rtl) { tx = -tx; } if (!isHorizontal) { ty = tx; tx = 0; } var transform = "rotateX(" + (isHorizontal ? 0 : -slideAngle) + "deg) rotateY(" + (isHorizontal ? slideAngle : 0) + "deg) translate3d(" + tx + "px, " + ty + "px, " + tz + "px)"; if (progress <= 1 && progress > -1) { wrapperRotate = slideIndex * 90 + progress * 90; if (rtl) wrapperRotate = -slideIndex * 90 - progress * 90; } $slideEl.transform(transform); if (params.slideShadows) { // Set shadows var shadowBefore = isHorizontal ? $slideEl.find('.swiper-slide-shadow-left') : $slideEl.find('.swiper-slide-shadow-top'); var shadowAfter = isHorizontal ? $slideEl.find('.swiper-slide-shadow-right') : $slideEl.find('.swiper-slide-shadow-bottom'); if (shadowBefore.length === 0) { shadowBefore = $("<div class=\"swiper-slide-shadow-" + (isHorizontal ? 'left' : 'top') + "\"></div>"); $slideEl.append(shadowBefore); } if (shadowAfter.length === 0) { shadowAfter = $("<div class=\"swiper-slide-shadow-" + (isHorizontal ? 'right' : 'bottom') + "\"></div>"); $slideEl.append(shadowAfter); } if (shadowBefore.length) shadowBefore[0].style.opacity = Math.max(-progress, 0); if (shadowAfter.length) shadowAfter[0].style.opacity = Math.max(progress, 0); } } $wrapperEl.css({ '-webkit-transform-origin': "50% 50% -" + swiperSize / 2 + "px", 'transform-origin': "50% 50% -" + swiperSize / 2 + "px" }); if (params.shadow) { if (isHorizontal) { $cubeShadowEl.transform("translate3d(0px, " + (swiperWidth / 2 + params.shadowOffset) + "px, " + -swiperWidth / 2 + "px) rotateX(90deg) rotateZ(0deg) scale(" + params.shadowScale + ")"); } else { var shadowAngle = Math.abs(wrapperRotate) - Math.floor(Math.abs(wrapperRotate) / 90) * 90; var multiplier = 1.5 - (Math.sin(shadowAngle * 2 * Math.PI / 360) / 2 + Math.cos(shadowAngle * 2 * Math.PI / 360) / 2); var scale1 = params.shadowScale; var scale2 = params.shadowScale / multiplier; var offset = params.shadowOffset; $cubeShadowEl.transform("scale3d(" + scale1 + ", 1, " + scale2 + ") translate3d(0px, " + (swiperHeight / 2 + offset) + "px, " + -swiperHeight / 2 / scale2 + "px) rotateX(-90deg)"); } } var zFactor = browser.isSafari || browser.isWebView ? -swiperSize / 2 : 0; $wrapperEl.transform("translate3d(0px,0," + zFactor + "px) rotateX(" + (swiper.isHorizontal() ? 0 : wrapperRotate) + "deg) rotateY(" + (swiper.isHorizontal() ? -wrapperRotate : 0) + "deg)"); }; var setTransition = function setTransition(duration) { var $el = swiper.$el, slides = swiper.slides; slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration); if (swiper.params.cubeEffect.shadow && !swiper.isHorizontal()) { $el.find('.swiper-cube-shadow').transition(duration); } }; on('beforeInit', function () { if (swiper.params.effect !== 'cube') return; swiper.classNames.push(swiper.params.containerModifierClass + "cube"); swiper.classNames.push(swiper.params.containerModifierClass + "3d"); var overwriteParams = { slidesPerView: 1, slidesPerColumn: 1, slidesPerGroup: 1, watchSlidesProgress: true, resistanceRatio: 0, spaceBetween: 0, centeredSlides: false, virtualTranslate: true }; Object.assign(swiper.params, overwriteParams); Object.assign(swiper.originalParams, overwriteParams); }); on('setTranslate', function () { if (swiper.params.effect !== 'cube') return; setTranslate(); }); on('setTransition', function (_s, duration) { if (swiper.params.effect !== 'cube') return; setTransition(duration); }); } function Flip(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on; extendParams({ flipEffect: { slideShadows: true, limitRotation: true } }); var setTranslate = function setTranslate() { var slides = swiper.slides, rtl = swiper.rtlTranslate; for (var i = 0; i < slides.length; i += 1) { var $slideEl = slides.eq(i); var progress = $slideEl[0].progress; if (swiper.params.flipEffect.limitRotation) { progress = Math.max(Math.min($slideEl[0].progress, 1), -1); } var offset = $slideEl[0].swiperSlideOffset; var rotate = -180 * progress; var rotateY = rotate; var rotateX = 0; var tx = -offset; var ty = 0; if (!swiper.isHorizontal()) { ty = tx; tx = 0; rotateX = -rotateY; rotateY = 0; } else if (rtl) { rotateY = -rotateY; } $slideEl[0].style.zIndex = -Math.abs(Math.round(progress)) + slides.length; if (swiper.params.flipEffect.slideShadows) { // Set shadows var shadowBefore = swiper.isHorizontal() ? $slideEl.find('.swiper-slide-shadow-left') : $slideEl.find('.swiper-slide-shadow-top'); var shadowAfter = swiper.isHorizontal() ? $slideEl.find('.swiper-slide-shadow-right') : $slideEl.find('.swiper-slide-shadow-bottom'); if (shadowBefore.length === 0) { shadowBefore = $("<div class=\"swiper-slide-shadow-" + (swiper.isHorizontal() ? 'left' : 'top') + "\"></div>"); $slideEl.append(shadowBefore); } if (shadowAfter.length === 0) { shadowAfter = $("<div class=\"swiper-slide-shadow-" + (swiper.isHorizontal() ? 'right' : 'bottom') + "\"></div>"); $slideEl.append(shadowAfter); } if (shadowBefore.length) shadowBefore[0].style.opacity = Math.max(-progress, 0); if (shadowAfter.length) shadowAfter[0].style.opacity = Math.max(progress, 0); } $slideEl.transform("translate3d(" + tx + "px, " + ty + "px, 0px) rotateX(" + rotateX + "deg) rotateY(" + rotateY + "deg)"); } }; var setTransition = function setTransition(duration) { var slides = swiper.slides, activeIndex = swiper.activeIndex, $wrapperEl = swiper.$wrapperEl; slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration); if (swiper.params.virtualTranslate && duration !== 0) { var eventTriggered = false; // eslint-disable-next-line slides.eq(activeIndex).transitionEnd(function onTransitionEnd() { if (eventTriggered) return; if (!swiper || swiper.destroyed) return; eventTriggered = true; swiper.animating = false; var triggerEvents = ['webkitTransitionEnd', 'transitionend']; for (var i = 0; i < triggerEvents.length; i += 1) { $wrapperEl.trigger(triggerEvents[i]); } }); } }; on('beforeInit', function () { if (swiper.params.effect !== 'flip') return; swiper.classNames.push(swiper.params.containerModifierClass + "flip"); swiper.classNames.push(swiper.params.containerModifierClass + "3d"); var overwriteParams = { slidesPerView: 1, slidesPerColumn: 1, slidesPerGroup: 1, watchSlidesProgress: true, spaceBetween: 0, virtualTranslate: true }; Object.assign(swiper.params, overwriteParams); Object.assign(swiper.originalParams, overwriteParams); }); on('setTranslate', function () { if (swiper.params.effect !== 'flip') return; setTranslate(); }); on('setTransition', function (_s, duration) { if (swiper.params.effect !== 'flip') return; setTransition(duration); }); } function Coverflow(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on; extendParams({ coverflowEffect: { rotate: 50, stretch: 0, depth: 100, scale: 1, modifier: 1, slideShadows: true } }); var setTranslate = function setTranslate() { var swiperWidth = swiper.width, swiperHeight = swiper.height, slides = swiper.slides, slidesSizesGrid = swiper.slidesSizesGrid; var params = swiper.params.coverflowEffect; var isHorizontal = swiper.isHorizontal(); var transform = swiper.translate; var center = isHorizontal ? -transform + swiperWidth / 2 : -transform + swiperHeight / 2; var rotate = isHorizontal ? params.rotate : -params.rotate; var translate = params.depth; // Each slide offset from center for (var i = 0, length = slides.length; i < length; i += 1) { var $slideEl = slides.eq(i); var slideSize = slidesSizesGrid[i]; var slideOffset = $slideEl[0].swiperSlideOffset; var offsetMultiplier = (center - slideOffset - slideSize / 2) / slideSize * params.modifier; var rotateY = isHorizontal ? rotate * offsetMultiplier : 0; var rotateX = isHorizontal ? 0 : rotate * offsetMultiplier; // var rotateZ = 0 var translateZ = -translate * Math.abs(offsetMultiplier); var stretch = params.stretch; // Allow percentage to make a relative stretch for responsive sliders if (typeof stretch === 'string' && stretch.indexOf('%') !== -1) { stretch = parseFloat(params.stretch) / 100 * slideSize; } var translateY = isHorizontal ? 0 : stretch * offsetMultiplier; var translateX = isHorizontal ? stretch * offsetMultiplier : 0; var scale = 1 - (1 - params.scale) * Math.abs(offsetMultiplier); // Fix for ultra small values if (Math.abs(translateX) < 0.001) translateX = 0; if (Math.abs(translateY) < 0.001) translateY = 0; if (Math.abs(translateZ) < 0.001) translateZ = 0; if (Math.abs(rotateY) < 0.001) rotateY = 0; if (Math.abs(rotateX) < 0.001) rotateX = 0; if (Math.abs(scale) < 0.001) scale = 0; var slideTransform = "translate3d(" + translateX + "px," + translateY + "px," + translateZ + "px) rotateX(" + rotateX + "deg) rotateY(" + rotateY + "deg) scale(" + scale + ")"; $slideEl.transform(slideTransform); $slideEl[0].style.zIndex = -Math.abs(Math.round(offsetMultiplier)) + 1; if (params.slideShadows) { // Set shadows var $shadowBeforeEl = isHorizontal ? $slideEl.find('.swiper-slide-shadow-left') : $slideEl.find('.swiper-slide-shadow-top'); var $shadowAfterEl = isHorizontal ? $slideEl.find('.swiper-slide-shadow-right') : $slideEl.find('.swiper-slide-shadow-bottom'); if ($shadowBeforeEl.length === 0) { $shadowBeforeEl = $("<div class=\"swiper-slide-shadow-" + (isHorizontal ? 'left' : 'top') + "\"></div>"); $slideEl.append($shadowBeforeEl); } if ($shadowAfterEl.length === 0) { $shadowAfterEl = $("<div class=\"swiper-slide-shadow-" + (isHorizontal ? 'right' : 'bottom') + "\"></div>"); $slideEl.append($shadowAfterEl); } if ($shadowBeforeEl.length) $shadowBeforeEl[0].style.opacity = offsetMultiplier > 0 ? offsetMultiplier : 0; if ($shadowAfterEl.length) $shadowAfterEl[0].style.opacity = -offsetMultiplier > 0 ? -offsetMultiplier : 0; } } }; var setTransition = function setTransition(duration) { swiper.slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration); }; on('beforeInit', function () { if (swiper.params.effect !== 'coverflow') return; swiper.classNames.push(swiper.params.containerModifierClass + "coverflow"); swiper.classNames.push(swiper.params.containerModifierClass + "3d"); swiper.params.watchSlidesProgress = true; swiper.originalParams.watchSlidesProgress = true; }); on('setTranslate', function () { if (swiper.params.effect !== 'coverflow') return; setTranslate(); }); on('setTransition', function (_s, duration) { if (swiper.params.effect !== 'coverflow') return; setTransition(duration); }); } function Thumb(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, on = _ref.on; extendParams({ thumbs: { swiper: null, multipleActiveThumbs: true, autoScrollOffset: 0, slideThumbActiveClass: 'swiper-slide-thumb-active', thumbsContainerClass: 'swiper-container-thumbs' } }); var initialized = false; var swiperCreated = false; swiper.thumbs = { swiper: null }; function onThumbClick() { var thumbsSwiper = swiper.thumbs.swiper; if (!thumbsSwiper) return; var clickedIndex = thumbsSwiper.clickedIndex; var clickedSlide = thumbsSwiper.clickedSlide; if (clickedSlide && $(clickedSlide).hasClass(swiper.params.thumbs.slideThumbActiveClass)) return; if (typeof clickedIndex === 'undefined' || clickedIndex === null) return; var slideToIndex; if (thumbsSwiper.params.loop) { slideToIndex = parseInt($(thumbsSwiper.clickedSlide).attr('data-swiper-slide-index'), 10); } else { slideToIndex = clickedIndex; } if (swiper.params.loop) { var currentIndex = swiper.activeIndex; if (swiper.slides.eq(currentIndex).hasClass(swiper.params.slideDuplicateClass)) { swiper.loopFix(); // eslint-disable-next-line swiper._clientLeft = swiper.$wrapperEl[0].clientLeft; currentIndex = swiper.activeIndex; } var prevIndex = swiper.slides.eq(currentIndex).prevAll("[data-swiper-slide-index=\"" + slideToIndex + "\"]").eq(0).index(); var nextIndex = swiper.slides.eq(currentIndex).nextAll("[data-swiper-slide-index=\"" + slideToIndex + "\"]").eq(0).index(); if (typeof prevIndex === 'undefined') slideToIndex = nextIndex;else if (typeof nextIndex === 'undefined') slideToIndex = prevIndex;else if (nextIndex - currentIndex < currentIndex - prevIndex) slideToIndex = nextIndex;else slideToIndex = prevIndex; } swiper.slideTo(slideToIndex); } function init() { var thumbsParams = swiper.params.thumbs; if (initialized) return false; initialized = true; var SwiperClass = swiper.constructor; if (thumbsParams.swiper instanceof SwiperClass) { swiper.thumbs.swiper = thumbsParams.swiper; Object.assign(swiper.thumbs.swiper.originalParams, { watchSlidesProgress: true, slideToClickedSlide: false }); Object.assign(swiper.thumbs.swiper.params, { watchSlidesProgress: true, slideToClickedSlide: false }); } else if (isObject(thumbsParams.swiper)) { var thumbsSwiperParams = Object.assign({}, thumbsParams.swiper); Object.assign(thumbsSwiperParams, { watchSlidesVisibility: true, watchSlidesProgress: true, slideToClickedSlide: false }); swiper.thumbs.swiper = new SwiperClass(thumbsSwiperParams); swiperCreated = true; } swiper.thumbs.swiper.$el.addClass(swiper.params.thumbs.thumbsContainerClass); swiper.thumbs.swiper.on('tap', onThumbClick); return true; } function update(initial) { var thumbsSwiper = swiper.thumbs.swiper; if (!thumbsSwiper) return; var slidesPerView = thumbsSwiper.params.slidesPerView === 'auto' ? thumbsSwiper.slidesPerViewDynamic() : thumbsSwiper.params.slidesPerView; var autoScrollOffset = swiper.params.thumbs.autoScrollOffset; var useOffset = autoScrollOffset && !thumbsSwiper.params.loop; if (swiper.realIndex !== thumbsSwiper.realIndex || useOffset) { var currentThumbsIndex = thumbsSwiper.activeIndex; var newThumbsIndex; var direction; if (thumbsSwiper.params.loop) { if (thumbsSwiper.slides.eq(currentThumbsIndex).hasClass(thumbsSwiper.params.slideDuplicateClass)) { thumbsSwiper.loopFix(); // eslint-disable-next-line thumbsSwiper._clientLeft = thumbsSwiper.$wrapperEl[0].clientLeft; currentThumbsIndex = thumbsSwiper.activeIndex; } // Find actual thumbs index to slide to var prevThumbsIndex = thumbsSwiper.slides.eq(currentThumbsIndex).prevAll("[data-swiper-slide-index=\"" + swiper.realIndex + "\"]").eq(0).index(); var nextThumbsIndex = thumbsSwiper.slides.eq(currentThumbsIndex).nextAll("[data-swiper-slide-index=\"" + swiper.realIndex + "\"]").eq(0).index(); if (typeof prevThumbsIndex === 'undefined') { newThumbsIndex = nextThumbsIndex; } else if (typeof nextThumbsIndex === 'undefined') { newThumbsIndex = prevThumbsIndex; } else if (nextThumbsIndex - currentThumbsIndex === currentThumbsIndex - prevThumbsIndex) { newThumbsIndex = thumbsSwiper.params.slidesPerGroup > 1 ? nextThumbsIndex : currentThumbsIndex; } else if (nextThumbsIndex - currentThumbsIndex < currentThumbsIndex - prevThumbsIndex) { newThumbsIndex = nextThumbsIndex; } else { newThumbsIndex = prevThumbsIndex; } direction = swiper.activeIndex > swiper.previousIndex ? 'next' : 'prev'; } else { newThumbsIndex = swiper.realIndex; direction = newThumbsIndex > swiper.previousIndex ? 'next' : 'prev'; } if (useOffset) { newThumbsIndex += direction === 'next' ? autoScrollOffset : -1 * autoScrollOffset; } if (thumbsSwiper.visibleSlidesIndexes && thumbsSwiper.visibleSlidesIndexes.indexOf(newThumbsIndex) < 0) { if (thumbsSwiper.params.centeredSlides) { if (newThumbsIndex > currentThumbsIndex) { newThumbsIndex = newThumbsIndex - Math.floor(slidesPerView / 2) + 1; } else { newThumbsIndex = newThumbsIndex + Math.floor(slidesPerView / 2) - 1; } } else if (newThumbsIndex > currentThumbsIndex && thumbsSwiper.params.slidesPerGroup === 1) ; thumbsSwiper.slideTo(newThumbsIndex, initial ? 0 : undefined); } } // Activate thumbs var thumbsToActivate = 1; var thumbActiveClass = swiper.params.thumbs.slideThumbActiveClass; if (swiper.params.slidesPerView > 1 && !swiper.params.centeredSlides) { thumbsToActivate = swiper.params.slidesPerView; } if (!swiper.params.thumbs.multipleActiveThumbs) { thumbsToActivate = 1; } thumbsToActivate = Math.floor(thumbsToActivate); thumbsSwiper.slides.removeClass(thumbActiveClass); if (thumbsSwiper.params.loop || thumbsSwiper.params.virtual && thumbsSwiper.params.virtual.enabled) { for (var i = 0; i < thumbsToActivate; i += 1) { thumbsSwiper.$wrapperEl.children("[data-swiper-slide-index=\"" + (swiper.realIndex + i) + "\"]").addClass(thumbActiveClass); } } else { for (var _i = 0; _i < thumbsToActivate; _i += 1) { thumbsSwiper.slides.eq(swiper.realIndex + _i).addClass(thumbActiveClass); } } } on('beforeInit', function () { var thumbs = swiper.params.thumbs; if (!thumbs || !thumbs.swiper) return; init(); update(true); }); on('slideChange update resize observerUpdate', function () { if (!swiper.thumbs.swiper) return; update(); }); on('setTransition', function (_s, duration) { var thumbsSwiper = swiper.thumbs.swiper; if (!thumbsSwiper) return; thumbsSwiper.setTransition(duration); }); on('beforeDestroy', function () { var thumbsSwiper = swiper.thumbs.swiper; if (!thumbsSwiper) return; if (swiperCreated && thumbsSwiper) { thumbsSwiper.destroy(); } }); Object.assign(swiper.thumbs, { init: init, update: update }); } function freeMode(_ref) { var swiper = _ref.swiper, extendParams = _ref.extendParams, emit = _ref.emit, once = _ref.once; extendParams({ freeMode: { enabled: false, momentum: true, momentumRatio: 1, momentumBounce: true, momentumBounceRatio: 1, momentumVelocityRatio: 1, sticky: false, minimumVelocity: 0.02 } }); function onTouchMove() { var data = swiper.touchEventsData, touches = swiper.touches; // Velocity if (data.velocities.length === 0) { data.velocities.push({ position: touches[swiper.isHorizontal() ? 'startX' : 'startY'], time: data.touchStartTime }); } data.velocities.push({ position: touches[swiper.isHorizontal() ? 'currentX' : 'currentY'], time: now() }); } function onTouchEnd(_ref2) { var currentPos = _ref2.currentPos; var params = swiper.params, $wrapperEl = swiper.$wrapperEl, rtl = swiper.rtlTranslate, snapGrid = swiper.snapGrid, data = swiper.touchEventsData; // Time diff var touchEndTime = now(); var timeDiff = touchEndTime - data.touchStartTime; if (currentPos < -swiper.minTranslate()) { swiper.slideTo(swiper.activeIndex); return; } if (currentPos > -swiper.maxTranslate()) { if (swiper.slides.length < snapGrid.length) { swiper.slideTo(snapGrid.length - 1); } else { swiper.slideTo(swiper.slides.length - 1); } return; } if (params.freeMode.momentum) { if (data.velocities.length > 1) { var lastMoveEvent = data.velocities.pop(); var velocityEvent = data.velocities.pop(); var distance = lastMoveEvent.position - velocityEvent.position; var time = lastMoveEvent.time - velocityEvent.time; swiper.velocity = distance / time; swiper.velocity /= 2; if (Math.abs(swiper.velocity) < params.freeMode.minimumVelocity) { swiper.velocity = 0; } // this implies that the user stopped moving a finger then released. // There would be no events with distance zero, so the last event is stale. if (time > 150 || now() - lastMoveEvent.time > 300) { swiper.velocity = 0; } } else { swiper.velocity = 0; } swiper.velocity *= params.freeMode.momentumVelocityRatio; data.velocities.length = 0; var momentumDuration = 1000 * params.freeMode.momentumRatio; var momentumDistance = swiper.velocity * momentumDuration; var newPosition = swiper.translate + momentumDistance; if (rtl) newPosition = -newPosition; var doBounce = false; var afterBouncePosition; var bounceAmount = Math.abs(swiper.velocity) * 20 * params.freeMode.momentumBounceRatio; var needsLoopFix; if (newPosition < swiper.maxTranslate()) { if (params.freeMode.momentumBounce) { if (newPosition + swiper.maxTranslate() < -bounceAmount) { newPosition = swiper.maxTranslate() - bounceAmount; } afterBouncePosition = swiper.maxTranslate(); doBounce = true; data.allowMomentumBounce = true; } else { newPosition = swiper.maxTranslate(); } if (params.loop && params.centeredSlides) needsLoopFix = true; } else if (newPosition > swiper.minTranslate()) { if (params.freeMode.momentumBounce) { if (newPosition - swiper.minTranslate() > bounceAmount) { newPosition = swiper.minTranslate() + bounceAmount; } afterBouncePosition = swiper.minTranslate(); doBounce = true; data.allowMomentumBounce = true; } else { newPosition = swiper.minTranslate(); } if (params.loop && params.centeredSlides) needsLoopFix = true; } else if (params.freeMode.sticky) { var nextSlide; for (var j = 0; j < snapGrid.length; j += 1) { if (snapGrid[j] > -newPosition) { nextSlide = j; break; } } if (Math.abs(snapGrid[nextSlide] - newPosition) < Math.abs(snapGrid[nextSlide - 1] - newPosition) || swiper.swipeDirection === 'next') { newPosition = snapGrid[nextSlide]; } else { newPosition = snapGrid[nextSlide - 1]; } newPosition = -newPosition; } if (needsLoopFix) { once('transitionEnd', function () { swiper.loopFix(); }); } // Fix duration if (swiper.velocity !== 0) { if (rtl) { momentumDuration = Math.abs((-newPosition - swiper.translate) / swiper.velocity); } else { momentumDuration = Math.abs((newPosition - swiper.translate) / swiper.velocity); } if (params.freeMode.sticky) { // If freeMode.sticky is active and the user ends a swipe with a slow-velocity // event, then durations can be 20+ seconds to slide one (or zero!) slides. // It's easy to see this when simulating touch with mouse events. To fix this, // limit single-slide swipes to the default slide duration. This also has the // nice side effect of matching slide speed if the user stopped moving before // lifting finger or mouse vs. moving slowly before lifting the finger/mouse. // For faster swipes, also apply limits (albeit higher ones). var moveDistance = Math.abs((rtl ? -newPosition : newPosition) - swiper.translate); var currentSlideSize = swiper.slidesSizesGrid[swiper.activeIndex]; if (moveDistance < currentSlideSize) { momentumDuration = params.speed; } else if (moveDistance < 2 * currentSlideSize) { momentumDuration = params.speed * 1.5; } else { momentumDuration = params.speed * 2.5; } } } else if (params.freeMode.sticky) { swiper.slideToClosest(); return; } if (params.freeMode.momentumBounce && doBounce) { swiper.updateProgress(afterBouncePosition); swiper.setTransition(momentumDuration); swiper.setTranslate(newPosition); swiper.transitionStart(true, swiper.swipeDirection); swiper.animating = true; $wrapperEl.transitionEnd(function () { if (!swiper || swiper.destroyed || !data.allowMomentumBounce) return; emit('momentumBounce'); swiper.setTransition(params.speed); setTimeout(function () { swiper.setTranslate(afterBouncePosition); $wrapperEl.transitionEnd(function () { if (!swiper || swiper.destroyed) return; swiper.transitionEnd(); }); }, 0); }); } else if (swiper.velocity) { emit('_freeModeNoMomentumRelease'); swiper.updateProgress(newPosition); swiper.setTransition(momentumDuration); swiper.setTranslate(newPosition); swiper.transitionStart(true, swiper.swipeDirection); if (!swiper.animating) { swiper.animating = true; $wrapperEl.transitionEnd(function () { if (!swiper || swiper.destroyed) return; swiper.transitionEnd(); }); } } else { swiper.updateProgress(newPosition); } swiper.updateActiveIndex(); swiper.updateSlidesClasses(); } else if (params.freeMode.sticky) { swiper.slideToClosest(); return; } else if (params.freeMode) { emit('_freeModeNoMomentumRelease'); } if (!params.freeMode.momentum || timeDiff >= params.longSwipesMs) { swiper.updateProgress(); swiper.updateActiveIndex(); swiper.updateSlidesClasses(); } } Object.assign(swiper, { freeMode: { onTouchMove: onTouchMove, onTouchEnd: onTouchEnd } }); } // Swiper Class var components = [Virtual, Keyboard, Mousewheel, Navigation, Pagination, Scrollbar, Parallax, Zoom, Lazy, Controller, A11y, History, HashNavigation, Autoplay, Fade, Cube, Flip, Coverflow, Thumb, freeMode]; Swiper.use(components); export default Swiper; export { Swiper }; //# sourceMappingURL=swiper-bundle.esm.browser.js.map
{ "content_hash": "4bcc16f440f780020ed90de18bff29ec", "timestamp": "", "source": "github", "line_count": 9675, "max_line_length": 254, "avg_line_length": 29.948113695090438, "alnum_prop": 0.6287014923312672, "repo_name": "cdnjs/cdnjs", "id": "be686e59d11da815462bb4816e6f5c907d65e389", "size": "290016", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/Swiper/7.0.0-alpha.5/swiper-bundle.esm.browser.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
layout : blocks/working-session title : Security Monitoring Playbooks type : workshop track : Security Playbooks technology : related-to : status : need-working materials when-day : Wed when-time : PM-3 location : Room-5 organizers : participants : Johan Peeters --- ## Why Security monitoring is a very complex activity, but Playbooks can help to define what to do and what to look for. Here is how [Using a “Playbook” Model to Organize Your Information Security Monitoring Strategy](http://blogs.cisco.com/security/using-a-playbook-model-to-organize-your-information-security-monitoring-strategy) defines Playbooks: > Our Playbook is our answer to this complexity. At its heart, it’s a collection of “plays” that each generate a report from some set of data sources. The thing about plays that makes them so useful is that they aren’t just some complex query or code to find bad stuff. > > Plays are self-contained, fully documented prescriptive procedures for finding some sort of undesired activity. > > By building the documentation into the play we’ve directly coupled the motivation for the play, how it gets analyzed, the specific query for it, and any additional information needed to both run the play and act upon the report results. The Working Session will create Security Monitoring Playbooks. ## What - Create Security Monitoring Playbooks for use by the Community ## Outcomes - Security Monitoring Playbooks ## Who The target audience for this Working Session is: - Security professionals - SOC specialists ## References - [Using a “Playbook” Model to Organize Your Information Security Monitoring Strategy](http://blogs.cisco.com/security/using-a-playbook-model-to-organize-your-information-security-monitoring-strategy) --- ## Working materials Here are the current 'work in progress' materials for this session (please add as much information as possible before the sessions) ### Content ...add content...
{ "content_hash": "e3d83c7f69d89b63119a34d36bf80f8b", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 269, "avg_line_length": 34.05084745762712, "alnum_prop": 0.7590841214534594, "repo_name": "mkasmani/owasp-devseccon-summit", "id": "59bb156352f50bff3d0da682dee2c14707b96eb7", "size": "2031", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Working-Sessions/Security-Playbooks/Security-Monitoring-Playbooks.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1554481" }, { "name": "CoffeeScript", "bytes": "35227" }, { "name": "HTML", "bytes": "1129397" }, { "name": "JavaScript", "bytes": "319138" }, { "name": "Nginx", "bytes": "1101" }, { "name": "PHP", "bytes": "198040" }, { "name": "Shell", "bytes": "3457" } ], "symlink_target": "" }
package org.apache.sshd.client.config.hosts; import java.io.IOException; import java.net.SocketAddress; import java.nio.file.LinkOption; import java.nio.file.Path; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import org.apache.sshd.common.AttributeRepository; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.common.util.io.ModifiableFileWatcher; /** * Watches for changes in a configuration file and automatically reloads any changes * * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a> */ public class ConfigFileHostEntryResolver extends ModifiableFileWatcher implements HostConfigEntryResolver { private final AtomicReference<HostConfigEntryResolver> delegateHolder = // assumes initially empty new AtomicReference<>(HostConfigEntryResolver.EMPTY); public ConfigFileHostEntryResolver(Path file) { this(file, IoUtils.EMPTY_LINK_OPTIONS); } public ConfigFileHostEntryResolver(Path file, LinkOption... options) { super(file, options); } @Override public HostConfigEntry resolveEffectiveHost( String host, int port, SocketAddress localAddress, String username, AttributeRepository context) throws IOException { try { HostConfigEntryResolver delegate = Objects.requireNonNull(resolveEffectiveResolver(host, port, username), "No delegate"); HostConfigEntry entry = delegate.resolveEffectiveHost(host, port, localAddress, username, context); if (log.isDebugEnabled()) { log.debug("resolveEffectiveHost({}@{}:{}) => {}", username, host, port, entry); } return entry; } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("resolveEffectiveHost({}@{}:{}) failed ({}) to resolve: {}", username, host, port, e.getClass().getSimpleName(), e.getMessage()); } if (log.isTraceEnabled()) { log.trace("resolveEffectiveHost(" + username + "@" + host + ":" + port + ") resolution failure details", e); } if (e instanceof IOException) { throw (IOException) e; } else { throw new IOException(e); } } } protected HostConfigEntryResolver resolveEffectiveResolver(String host, int port, String username) throws IOException { if (checkReloadRequired()) { delegateHolder.set(HostConfigEntryResolver.EMPTY); // start fresh Path path = getPath(); if (exists()) { Collection<HostConfigEntry> entries = reloadHostConfigEntries(path, host, port, username); if (GenericUtils.size(entries) > 0) { delegateHolder.set(HostConfigEntry.toHostConfigEntryResolver(entries)); } } else { log.info("resolveEffectiveResolver({}@{}:{}) no configuration file at {}", username, host, port, path); } } return delegateHolder.get(); } protected List<HostConfigEntry> reloadHostConfigEntries( Path path, String host, int port, String username) throws IOException { List<HostConfigEntry> entries = HostConfigEntry.readHostConfigEntries(path); log.info("resolveEffectiveResolver({}@{}:{}) loaded {} entries from {}", username, host, port, GenericUtils.size(entries), path); updateReloadAttributes(); return entries; } }
{ "content_hash": "1e2fb13281d51b2da1fa3ff5a660072e", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 137, "avg_line_length": 39.924731182795696, "alnum_prop": 0.6404524643145705, "repo_name": "lgoldstein/mina-sshd", "id": "fe40b7326c67ef26f825ce3870bd2e41344fffc1", "size": "4514", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sshd-common/src/main/java/org/apache/sshd/client/config/hosts/ConfigFileHostEntryResolver.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "15035" }, { "name": "HTML", "bytes": "5769" }, { "name": "Java", "bytes": "6840795" }, { "name": "Python", "bytes": "11690" }, { "name": "Shell", "bytes": "34849" } ], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fa_IR" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About MillionBitcoinCash</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;MillionBitcoinCash&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The MillionBitcoinCash developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>برای ویرایش حساب و یا برچسب دوبار کلیک نمایید</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>گشایش حسابی جدید</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>کپی کردن حساب انتخاب شده به حافظه سیستم - کلیپ بورد</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your MillionBitcoinCash addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>و کپی آدرس</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a MillionBitcoinCash address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified MillionBitcoinCash address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>و حذف</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>کپی و برچسب</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>و ویرایش</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>سی.اس.وی. (فایل جداگانه دستوری)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>برچسب</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>حساب</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(برچسب ندارد)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>رمز/پَس فرِیز را وارد کنید</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>رمز/پَس فرِیز جدید را وارد کنید</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>رمز/پَس فرِیز را دوباره وارد کنید</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>رمز/پَس فرِیز جدید را در wallet وارد کنید. برای انتخاب رمز/پَس فرِیز از 10 کاراکتر تصادفی یا بیشتر و یا هشت کلمه یا بیشتر استفاده کنید. </translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>wallet را رمزگذاری کنید</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>برای انجام این عملکرد به رمز/پَس فرِیزِwallet نیاز است تا آن را از حالت قفل درآورد.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>باز کردن قفل wallet </translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>برای کشف رمز wallet، به رمز/پَس فرِیزِwallet نیاز است.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>کشف رمز wallet</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>تغییر رمز/پَس فرِیز</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>رمز/پَس فرِیزِ قدیم و جدید را در wallet وارد کنید</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>رمزگذاری wallet را تایید کنید</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>تایید رمزگذاری</translation> </message> <message> <location line="-58"/> <source>MillionBitcoinCash will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>رمزگذاری تایید نشد</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>رمزگذاری به علت خطای داخلی تایید نشد. wallet شما رمزگذاری نشد</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>رمزهای/پَس فرِیزهایِ وارد شده با هم تطابق ندارند</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>قفل wallet باز نشد</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>رمزهای/پَس فرِیزهایِ وارد شده wallet برای کشف رمز اشتباه است.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>کشف رمز wallet انجام نشد</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+280"/> <source>Sign &amp;message...</source> <translation>امضا و پیام</translation> </message> <message> <location line="+242"/> <source>Synchronizing with network...</source> <translation>به روز رسانی با شبکه...</translation> </message> <message> <location line="-308"/> <source>&amp;Overview</source> <translation>و بازبینی</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>نمای کلی از wallet را نشان بده</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>و تراکنش</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>تاریخچه تراکنش را باز کن</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>خروج</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>از &quot;درخواست نامه&quot;/ application خارج شو</translation> </message> <message> <location line="+4"/> <source>Show information about MillionBitcoinCash</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>درباره و QT</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>نمایش اطلاعات درباره QT</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>و انتخابها</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>و رمزگذاری wallet</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>و گرفتن نسخه پیشتیبان از wallet</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>تغییر رمز/پَس فرِیز</translation> </message> <message numerus="yes"> <location line="+250"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-247"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Send coins to a MillionBitcoinCash address</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Modify configuration options for MillionBitcoinCash</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>گرفتن نسخه پیشتیبان در آدرسی دیگر</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>رمز مربوط به رمزگذاریِ wallet را تغییر دهید</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-200"/> <source>MillionBitcoinCash</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>کیف پول</translation> </message> <message> <location line="+178"/> <source>&amp;About MillionBitcoinCash</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;نمایش/ عدم نمایش و</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>&amp;File</source> <translation>و فایل</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>و تنظیمات</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>و راهنما</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>نوار ابزار</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>MillionBitcoinCash client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to MillionBitcoinCash network</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="-284"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+288"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>روزآمد</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>در حال روزآمد سازی..</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>ارسال تراکنش</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>تراکنش دریافتی</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>تاریخ: %1⏎ میزان وجه : %2⏎ نوع: %3⏎ آدرس: %4⏎ </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid MillionBitcoinCash address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>wallet رمزگذاری شد و در حال حاضر از حالت قفل در آمده است</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>wallet رمزگذاری شد و در حال حاضر قفل است</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. MillionBitcoinCash can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>هشدار شبکه</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>میزان وجه:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation>میزان</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>حساب</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>تایید شده</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>آدرس را کپی کنید</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>برچسب را کپی کنید</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>میزان وجه کپی شود</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(برچسب ندارد)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>ویرایش حساب</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>و برچسب</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>حساب&amp;</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>حساب دریافت کننده جدید </translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>حساب ارسال کننده جدید</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>ویرایش حساب دریافت کننده</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>ویرایش حساب ارسال کننده</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>حساب وارد شده «1%» از پیش در دفترچه حساب ها موجود است.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid MillionBitcoinCash address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>عدم توانیی برای قفل گشایی wallet</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>عدم توانیی در ایجاد کلید جدید</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>MillionBitcoinCash-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>انتخاب/آپشن</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start MillionBitcoinCash after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start MillionBitcoinCash on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the MillionBitcoinCash client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the MillionBitcoinCash network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting MillionBitcoinCash.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show MillionBitcoinCash addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>و نمایش آدرسها در فهرست تراکنش</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>و تایید</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>و رد</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>پیش فرض</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting MillionBitcoinCash.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>فرم</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the MillionBitcoinCash network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>کیف پول</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>تراکنشهای اخیر</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>خارج از روزآمد سازی</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>نام کنسول RPC</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation>ویرایش کنسول RPC</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation>شبکه</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>تعداد اتصال</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>زنجیره مجموعه تراکنش ها</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>تعداد زنجیره های حاضر</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the MillionBitcoinCash-Qt help message to get a list with possible MillionBitcoinCash command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>MillionBitcoinCash - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>MillionBitcoinCash Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the MillionBitcoinCash debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the MillionBitcoinCash RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>سکه های ارسالی</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>میزان وجه:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 BC</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>ارسال همزمان به گیرنده های متعدد</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>مانده حساب:</translation> </message> <message> <location line="+16"/> <source>123.456 BC</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>تایید عملیات ارسال </translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>و ارسال</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a MillionBitcoinCash address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>میزان وجه کپی شود</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>تایید ارسال بیت کوین ها</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>میزان پرداخت باید بیشتر از 0 باشد</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>مقدار مورد نظر از مانده حساب بیشتر است.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid MillionBitcoinCash address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(برچسب ندارد)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>و میزان وجه</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>پرداخت و به چه کسی</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>یک برچسب برای این آدرس بنویسید تا به دفترچه آدرسهای شما اضافه شود</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>و برچسب</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt و A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>آدرس را بر کلیپ بورد کپی کنید</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt و P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a MillionBitcoinCash address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>و امضای پیام </translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt و A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>آدرس را بر کلیپ بورد کپی کنید</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt و P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this MillionBitcoinCash address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified MillionBitcoinCash address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a MillionBitcoinCash address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter MillionBitcoinCash signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>باز کن تا %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1 / تایید نشده</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 تایید</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>برچسب</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation>پیام</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 20 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>میزان</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>، هنوز با موفقیت ارسال نگردیده است</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>ناشناس</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>جزئیات تراکنش</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>این بخش جزئیات تراکنش را نشان می دهد</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>گونه</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>آدرس</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>میزان وجه</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>باز کن تا %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>تایید شده (%1 تاییدها)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>این block توسط گره های دیگری دریافت نشده است و ممکن است قبول نشود</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>تولید شده اما قبول نشده است</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>قبول با </translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>دریافت شده از</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>ارسال به</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>وجه برای شما </translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>استخراج شده</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>خالی</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>وضعیت تراکنش. با اشاره به این بخش تعداد تاییدها نمایش داده می شود</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>زمان و تاریخی که تراکنش دریافت شده است</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>نوع تراکنش</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>آدرس مقصد در تراکنش</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>میزان وجه کم شده یا اضافه شده به حساب</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>همه</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>امروز</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>این هفته</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>این ماه</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>ماه گذشته</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>این سال</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>حدود..</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>دریافت با</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>ارسال به</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>به شما</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>استخراج شده</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>دیگر</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>آدرس یا برچسب را برای جستجو وارد کنید</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>حداقل میزان وجه</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>آدرس را کپی کنید</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>برچسب را کپی کنید</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>میزان وجه کپی شود</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>برچسب را ویرایش کنید</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv) فایل جداگانه دستوری</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>تایید شده</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>تاریخ</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>نوع</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>برچسب</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>آدرس</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>میزان</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>شناسه کاربری</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>دامنه:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>به</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>MillionBitcoinCash version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>میزان استفاده:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or millionbitcoincashd</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>فهرست دستورها</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>درخواست کمک برای یک دستور</translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>انتخابها:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: millionbitcoincash.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: millionbitcoincashd.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>دایرکتوری داده را مشخص کن</translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>حافظه بانک داده را به مگابایت تنظیم کنید (پیش فرض: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 24069 or testnet: 34069)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>نگهداری &lt;N&gt; ارتباطات برای قرینه سازی (پیش فرض:125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>آستانه قطع برای قرینه سازی اشتباه (پیش فرض:100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>تعداد ثانیه ها برای اتصال دوباره قرینه های اشتباه (پیش فرض:86400)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 24070 or testnet: 34070)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>command line و JSON-RPC commands را قبول کنید</translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>به عنوان daemon بک گراند را اجرا کنید و دستورات را قبول نمایید</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>از تستِ شبکه استفاده نمایید</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong MillionBitcoinCash will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>ارسال اطلاعات پیگیری/خطایابی به کنسول به جای ارسال به فایل debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>تعیین مدت زمان وقفه (time out) به هزارم ثانیه</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>شناسه کاربری برای ارتباطاتِ JSON-RPC</translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>رمز برای ارتباطاتِ JSON-RPC</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=millionbitcoincashrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;MillionBitcoinCash Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>ارتباطاتِ JSON-RPC را از آدرس آی.پی. مشخصی برقرار کنید.</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>دستورات را به گره اجرا شده در&lt;ip&gt; ارسال کنید (پیش فرض:127.0.0.1)</translation> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>دستور را وقتی بهترین بلاک تغییر کرد اجرا کن (%s در دستور توسط block hash جایگزین شده است)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>wallet را به جدیدترین نسخه روزآمد کنید</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>حجم key pool را به اندازه &lt;n&gt; تنظیم کنید (پیش فرض:100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>زنجیره بلاک را برای تراکنش جا افتاده در WALLET دوباره اسکن کنید</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>برای ارتباطاتِ JSON-RPC از OpenSSL (https) استفاده کنید</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>فایل certificate سرور (پیش فرض server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>رمز اختصاصی سرور (پیش فرض: server.pem)</translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation>این پیام راهنما</translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. MillionBitcoinCash is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>MillionBitcoinCash</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>لود شدن آدرسها..</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>خطا در هنگام لود شدن wallet.dat: Wallet corrupted</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of MillionBitcoinCash</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart MillionBitcoinCash to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>خطا در هنگام لود شدن wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>میزان اشتباه است for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>میزان اشتباه است</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>وجوه ناکافی</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>لود شدن نمایه بلاکها..</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>یک گره برای اتصال اضافه کنید و تلاش کنید تا اتصال را باز نگاه دارید</translation> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. MillionBitcoinCash is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>wallet در حال لود شدن است...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>قابلیت برگشت به نسخه قبلی برای wallet امکان پذیر نیست</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>آدرس پیش فرض قابل ذخیره نیست</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>اسکنِ دوباره...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>اتمام لود شدن</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>برای استفاده از %s از اختیارات</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>خطا</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>شما باید یک رمز rpcpassword=&lt;password&gt; را در فایل تنظیمات ایجاد کنید⏎ %s ⏎ اگر فایل ایجاد نشده است، آن را با یک فایل &quot;فقط متنی&quot; ایجاد کنید. </translation> </message> </context> </TS>
{ "content_hash": "d33daae4a3107f40143f38ae84155b8a", "timestamp": "", "source": "github", "line_count": 3278, "max_line_length": 394, "avg_line_length": 33.977425259304454, "alnum_prop": 0.5938156547971771, "repo_name": "MillionBitcoincash/millionbitcoincash", "id": "da33cbe9e206ff013bebf65521d5470bdeb7b3cf", "size": "115001", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_fa_IR.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "51312" }, { "name": "C", "bytes": "35921" }, { "name": "C++", "bytes": "2584421" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50620" }, { "name": "Makefile", "bytes": "13085" }, { "name": "NSIS", "bytes": "5914" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "3537" }, { "name": "Python", "bytes": "41580" }, { "name": "QMake", "bytes": "13990" }, { "name": "Roff", "bytes": "12684" }, { "name": "Shell", "bytes": "9083" } ], "symlink_target": "" }
/** * @depends {3rdparty/jquery-2.1.0.js} * @depends {3rdparty/bootstrap.js} * @depends {3rdparty/big.js} * @depends {3rdparty/jsbn.js} * @depends {3rdparty/jsbn2.js} * @depends {3rdparty/pako.js} * @depends {3rdparty/webdb.js} * @depends {3rdparty/ajaxmultiqueue.js} * @depends {3rdparty/growl.js} * @depends {3rdparty/zeroclipboard.js} * @depends {crypto/curve25519.js} * @depends {crypto/curve25519_.js} * @depends {crypto/passphrasegenerator.js} * @depends {crypto/sha256worker.js} * @depends {crypto/3rdparty/cryptojs/aes.js} * @depends {crypto/3rdparty/cryptojs/sha256.js} * @depends {crypto/3rdparty/jssha256.js} * @depends {crypto/3rdparty/seedrandom.js} * @depends {util/converters.js} * @depends {util/extensions.js} * @depends {util/nxtaddress.js} */ var NRS = (function(NRS, $, undefined) { "use strict"; NRS.server = ""; NRS.state = {}; NRS.blocks = []; NRS.genesis = "1739068987193023818"; NRS.genesisRS = "NXT-MRCC-2YLS-8M54-3CMAJ"; NRS.account = ""; NRS.accountRS = ""; NRS.publicKey = ""; NRS.accountInfo = {}; NRS.database = null; NRS.databaseSupport = false; NRS.serverConnect = false; NRS.peerConnect = false; NRS.settings = {}; NRS.contacts = {}; NRS.isTestNet = false; NRS.isLocalHost = false; NRS.isForging = false; NRS.isLeased = false; NRS.lastBlockHeight = 0; NRS.downloadingBlockchain = false; NRS.rememberPassword = false; NRS.selectedContext = null; NRS.currentPage = "dashboard"; NRS.currentSubPage = ""; NRS.pageNumber = 1; //NRS.itemsPerPage = 50; /* Now set in nrs.settings.js */ NRS.pages = {}; NRS.incoming = {}; if (!_checkDOMenabled()) { NRS.hasLocalStorage = false; } else { NRS.hasLocalStorage = true; } NRS.inApp = false; NRS.appVersion = ""; NRS.appPlatform = ""; NRS.assetTableKeys = []; var stateInterval; var stateIntervalSeconds = 30; var isScanning = false; NRS.init = function() { NRS.sendRequest("getState", { "includeCounts": "false" }, function (response) { var isTestnet = false; var isOffline = false; var peerPort = 0; for (var key in response) { if (key == "isTestnet") { isTestnet = response[key]; } if (key == "isOffline") { isOffline = response[key]; } if (key == "peerPort") { peerPort = response[key]; } } if (!isTestnet) { $(".testnet_only").hide(); } else { NRS.isTestNet = true; var testnetWarningDiv = $("#testnet_warning"); var warningText = testnetWarningDiv.text() + " The testnet peer port is " + peerPort + (isOffline ? ", the peer is working offline." : "."); testnetWarningDiv.text(warningText); $(".testnet_only, #testnet_login, #testnet_warning").show(); } }); if (!NRS.server) { var hostName = window.location.hostname.toLowerCase(); NRS.isLocalHost = hostName == "localhost" || hostName == "127.0.0.1" || NRS.isPrivateIP(hostName); } if (!NRS.isLocalHost) { $(".remote_warning").show(); } try { window.localStorage; } catch (err) { NRS.hasLocalStorage = false; } if (NRS.getCookie("remember_passphrase")) { $("#remember_password").prop("checked", true); } NRS.createDatabase(function() { NRS.getSettings(); }); NRS.getState(function() { setTimeout(function() { NRS.checkAliasVersions(); }, 5000); }); NRS.showLockscreen(); if (window.parent) { var match = window.location.href.match(/\?app=?(win|mac|lin)?\-?([\d\.]+)?/i); if (match) { NRS.inApp = true; if (match[1]) { NRS.appPlatform = match[1]; } if (match[2]) { NRS.appVersion = match[2]; } if (!NRS.appPlatform || NRS.appPlatform == "mac") { var macVersion = navigator.userAgent.match(/OS X 10_([0-9]+)/i); if (macVersion && macVersion[1]) { macVersion = parseInt(macVersion[1]); if (macVersion < 9) { $(".modal").removeClass("fade"); } } } $("#show_console").hide(); parent.postMessage("loaded", "*"); window.addEventListener("message", receiveMessage, false); } } NRS.setStateInterval(30); if (!NRS.isTestNet) { setInterval(NRS.checkAliasVersions, 1000 * 60 * 60); } NRS.allowLoginViaEnter(); NRS.automaticallyCheckRecipient(); $(".show_popover").popover({ "trigger": "hover" }); $("#dashboard_transactions_table, #transactions_table").on("mouseenter", "td.confirmations", function() { $(this).popover("show"); }).on("mouseleave", "td.confirmations", function() { $(this).popover("destroy"); $(".popover").remove(); }); _fix(); $(window).on("resize", function() { _fix(); if (NRS.currentPage == "asset_exchange") { NRS.positionAssetSidebar(); } }); $("[data-toggle='tooltip']").tooltip(); $(".sidebar .treeview").tree(); $("#dgs_search_account_top, #dgs_search_account_center").mask("NXT-****-****-****-*****", { "unmask": false }); /* $("#asset_exchange_search input[name=q]").addClear({ right: 0, top: 4, onClear: function(input) { $("#asset_exchange_search").trigger("submit"); } }); $("#id_search input[name=q], #alias_search input[name=q]").addClear({ right: 0, top: 4 });*/ }; function _fix() { var height = $(window).height() - $("body > .header").height(); //$(".wrapper").css("min-height", height + "px"); var content = $(".wrapper").height(); $(".content.content-stretch:visible").width($(".page:visible").width()); if (content > height) { $(".left-side, html, body").css("min-height", content + "px"); } else { $(".left-side, html, body").css("min-height", height + "px"); } } NRS.setStateInterval = function(seconds) { if (seconds == stateIntervalSeconds && stateInterval) { return; } if (stateInterval) { clearInterval(stateInterval); } stateIntervalSeconds = seconds; stateInterval = setInterval(function() { NRS.getState(); }, 1000 * seconds); }; NRS.getState = function(callback) { NRS.sendRequest("getBlockchainStatus", function(response) { if (response.errorCode) { NRS.serverConnect = false; //todo } else { var firstTime = !("lastBlock" in NRS.state); var previousLastBlock = (firstTime ? "0" : NRS.state.lastBlock); NRS.state = response; NRS.serverConnect = true; if (firstTime) { $("#nrs_version").html(NRS.state.version).removeClass("loading_dots"); NRS.getBlock(NRS.state.lastBlock, NRS.handleInitialBlocks); } else if (NRS.state.isScanning) { //do nothing but reset NRS.state so that when isScanning is done, everything is reset. isScanning = true; } else if (isScanning) { //rescan is done, now we must reset everything... isScanning = false; NRS.blocks = []; NRS.tempBlocks = []; NRS.getBlock(NRS.state.lastBlock, NRS.handleInitialBlocks); if (NRS.account) { NRS.getInitialTransactions(); NRS.getAccountInfo(); } } else if (previousLastBlock != NRS.state.lastBlock) { NRS.tempBlocks = []; if (NRS.account) { NRS.getAccountInfo(); } NRS.getBlock(NRS.state.lastBlock, NRS.handleNewBlocks); if (NRS.account) { NRS.getNewTransactions(); } } else { if (NRS.account) { NRS.getUnconfirmedTransactions(function(unconfirmedTransactions) { NRS.handleIncomingTransactions(unconfirmedTransactions, false); }); } } if (callback) { callback(); } } /* Checks if the client is connected to active peers */ NRS.checkConnected(); //only done so that download progress meter updates correctly based on lastFeederHeight if (NRS.downloadingBlockchain) { NRS.updateBlockchainDownloadProgress(); } }); }; $("#logo, .sidebar-menu a").click(function(e, data) { if ($(this).hasClass("ignore")) { $(this).removeClass("ignore"); return; } e.preventDefault(); if ($(this).data("toggle") == "modal") { return; } var page = $(this).data("page"); if (page == NRS.currentPage) { if (data && data.callback) { data.callback(); } return; } $(".page").hide(); $(document.documentElement).scrollTop(0); $("#" + page + "_page").show(); $(".content-header h1").find(".loading_dots").remove(); var changeActive = !($(this).closest("ul").hasClass("treeview-menu")); if (changeActive) { var currentActive = $("ul.sidebar-menu > li.active"); if (currentActive.hasClass("treeview")) { currentActive.children("a").first().addClass("ignore").click(); } else { currentActive.removeClass("active"); } if ($(this).attr("id") && $(this).attr("id") == "logo") { $("#dashboard_link").addClass("active"); } else { $(this).parent().addClass("active"); } } if (NRS.currentPage != "messages") { $("#inline_message_password").val(""); } //NRS.previousPage = NRS.currentPage; NRS.currentPage = page; NRS.currentSubPage = ""; NRS.pageNumber = 1; NRS.showPageNumbers = false; if (NRS.pages[page]) { NRS.pageLoading(); if (data && data.callback) { NRS.pages[page](data.callback); } else if (data) { NRS.pages[page](data); } else { NRS.pages[page](); } } }); $("button.goto-page, a.goto-page").click(function(event) { event.preventDefault(); NRS.goToPage($(this).data("page")); }); NRS.loadPage = function(page, callback) { NRS.pageLoading(); NRS.pages[page](callback); }; NRS.goToPage = function(page, callback) { var $link = $("ul.sidebar-menu a[data-page=" + page + "]"); if ($link.length > 1) { if ($link.last().is(":visible")) { $link = $link.last(); } else { $link = $link.first(); } } if ($link.length == 1) { if (callback) { $link.trigger("click", [{ "callback": callback }]); } else { $link.trigger("click"); } } else { NRS.currentPage = page; NRS.currentSubPage = ""; NRS.pageNumber = 1; NRS.showPageNumbers = false; $("ul.sidebar-menu a.active").removeClass("active"); $(".page").hide(); $("#" + page + "_page").show(); if (NRS.pages[page]) { NRS.pageLoading(); NRS.pages[page](callback); } } }; NRS.pageLoading = function() { NRS.hasMorePages = false; var $pageHeader = $("#" + NRS.currentPage + "_page .content-header h1"); $pageHeader.find(".loading_dots").remove(); $pageHeader.append("<span class='loading_dots'><span>.</span><span>.</span><span>.</span></span>"); }; NRS.pageLoaded = function(callback) { var $currentPage = $("#" + NRS.currentPage + "_page"); $currentPage.find(".content-header h1 .loading_dots").remove(); if ($currentPage.hasClass("paginated")) { NRS.addPagination(); } if (callback) { callback(); } }; NRS.addPagination = function(section) { var firstStartNr = 1; var firstEndNr = NRS.itemsPerPage; var currentStartNr = (NRS.pageNumber-1) * NRS.itemsPerPage + 1; var currentEndNr = NRS.pageNumber * NRS.itemsPerPage; var prevHTML = '<span style="display:inline-block;width:48px;text-align:right;">'; var firstHTML = '<span style="display:inline-block;min-width:48px;text-align:right;vertical-align:top;margin-top:4px;">'; var currentHTML = '<span style="display:inline-block;min-width:48px;text-align:left;vertical-align:top;margin-top:4px;">'; var nextHTML = '<span style="display:inline-block;width:48px;text-align:left;">'; if (NRS.pageNumber > 1) { prevHTML += "<a href='#' data-page='" + (NRS.pageNumber - 1) + "' title='" + $.t("previous") + "' style='font-size:20px;'>"; prevHTML += "<i class='fa fa-arrow-circle-left'></i></a>"; } else { prevHTML += '&nbsp;'; } if (NRS.hasMorePages) { currentHTML += currentStartNr + "-" + currentEndNr + "&nbsp;"; nextHTML += "<a href='#' data-page='" + (NRS.pageNumber + 1) + "' title='" + $.t("next") + "' style='font-size:20px;'>"; nextHTML += "<i class='fa fa-arrow-circle-right'></i></a>"; } else { if (NRS.pageNumber > 1) { currentHTML += currentStartNr + "+"; } else { currentHTML += "&nbsp;"; } nextHTML += "&nbsp;"; } if (NRS.pageNumber > 1) { firstHTML += "&nbsp;<a href='#' data-page='1'>" + firstStartNr + "-" + firstEndNr + "</a>&nbsp;|&nbsp;"; } else { firstHTML += "&nbsp;"; } prevHTML += '</span>'; firstHTML += '</span>'; currentHTML += '</span>'; nextHTML += '</span>'; var output = prevHTML + firstHTML + currentHTML + nextHTML; var $paginationContainer = $("#" + NRS.currentPage + "_page .data-pagination"); if ($paginationContainer.length) { $paginationContainer.html(output); } }; $(".data-pagination").on("click", "a", function(e) { e.preventDefault(); NRS.goToPageNumber($(this).data("page")); }); NRS.goToPageNumber = function(pageNumber) { /*if (!pageLoaded) { return; }*/ NRS.pageNumber = pageNumber; NRS.pageLoading(); NRS.pages[NRS.currentPage](); }; NRS.createDatabase = function(callback) { var schema = { contacts: { id: { "primary": true, "autoincrement": true, "type": "NUMBER" }, name: "VARCHAR(100) COLLATE NOCASE", email: "VARCHAR(200)", account: "VARCHAR(25)", accountRS: "VARCHAR(25)", description: "TEXT" }, assets: { account: "VARCHAR(25)", accountRS: "VARCHAR(25)", asset: { "primary": true, "type": "VARCHAR(25)" }, description: "TEXT", name: "VARCHAR(10)", decimals: "NUMBER", quantityQNT: "VARCHAR(15)", groupName: "VARCHAR(30) COLLATE NOCASE" }, data: { id: { "primary": true, "type": "VARCHAR(40)" }, contents: "TEXT" } }; NRS.assetTableKeys = ["account", "accountRS", "asset", "description", "name", "position", "decimals", "quantityQNT", "groupName"]; try { NRS.database = new WebDB("NRS_USER_DB", schema, 2, 4, function(error, db) { if (!error) { NRS.databaseSupport = true; NRS.loadContacts(); NRS.database.select("data", [{ "id": "asset_exchange_version" }], function(error, result) { if (!result || !result.length) { NRS.database.delete("assets", [], function(error, affected) { if (!error) { NRS.database.insert("data", { "id": "asset_exchange_version", "contents": 2 }); } }); } }); NRS.database.select("data", [{ "id": "closed_groups" }], function(error, result) { if (result && result.length) { NRS.closedGroups = result[0].contents.split("#"); } else { NRS.database.insert("data", { id: "closed_groups", contents: "" }); } }); if (callback) { callback(); } } else { if (callback) { callback(); } } }); } catch (err) { NRS.database = null; NRS.databaseSupport = false; if (callback) { callback(); } } }; /* Display connected state in Sidebar */ NRS.checkConnected = function() { NRS.sendRequest("getPeers+", { "state": "CONNECTED" }, function(response) { if (response.peers && response.peers.length) { NRS.peerConnect = true; $("#connected_indicator").addClass("connected"); $("#connected_indicator span").html($.t("Connected")).attr("data-i18n", "connected"); $("#connected_indicator").show(); } else { NRS.peerConnect = false; $("#connected_indicator").removeClass("connected"); $("#connected_indicator span").html($.t("Not Connected")).attr("data-i18n", "not_connected"); $("#connected_indicator").show(); } }); }; NRS.getAccountInfo = function(firstRun, callback) { NRS.sendRequest("getAccount", { "account": NRS.account }, function(response) { var previousAccountInfo = NRS.accountInfo; NRS.accountInfo = response; if (response.errorCode) { $("#account_balance, #account_balance_sidebar, #account_nr_assets, #account_assets_balance, #account_currency_count, #account_purchase_count, #account_pending_sale_count, #account_completed_sale_count, #account_message_count, #account_alias_count").html("0"); if (NRS.accountInfo.errorCode == 5) { if (NRS.downloadingBlockchain) { if (NRS.newlyCreatedAccount) { $("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_new_account", { "account_id": String(NRS.accountRS).escapeHTML(), "public_key": String(NRS.publicKey).escapeHTML() }) + "<br /><br />" + $.t("status_blockchain_downloading")).show(); } else { $("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_blockchain_downloading")).show(); } } else if (NRS.state && NRS.state.isScanning) { $("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html($.t("status_blockchain_rescanning")).show(); } else { $("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_new_account", { "account_id": String(NRS.accountRS).escapeHTML(), "public_key": String(NRS.publicKey).escapeHTML() })).show(); } } else { $("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html(NRS.accountInfo.errorDescription ? NRS.accountInfo.errorDescription.escapeHTML() : $.t("error_unknown")).show(); } } else { if (NRS.accountRS && NRS.accountInfo.accountRS != NRS.accountRS) { $.growl("Generated Reed Solomon address different from the one in the blockchain!", { "type": "danger" }); NRS.accountRS = NRS.accountInfo.accountRS; } if (NRS.downloadingBlockchain) { $("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_blockchain_downloading")).show(); } else if (NRS.state && NRS.state.isScanning) { $("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html($.t("status_blockchain_rescanning")).show(); } else if (!NRS.accountInfo.publicKey) { $("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html($.t("no_public_key_warning") + " " + $.t("public_key_actions")).show(); } else { $("#dashboard_message").hide(); } //only show if happened within last week var showAssetDifference = (!NRS.downloadingBlockchain || (NRS.blocks && NRS.blocks[0] && NRS.state && NRS.state.time - NRS.blocks[0].timestamp < 60 * 60 * 24 * 7)); if (NRS.databaseSupport) { NRS.database.select("data", [{ "id": "asset_balances_" + NRS.account }], function(error, asset_balance) { if (asset_balance && asset_balance.length) { var previous_balances = asset_balance[0].contents; if (!NRS.accountInfo.assetBalances) { NRS.accountInfo.assetBalances = []; } var current_balances = JSON.stringify(NRS.accountInfo.assetBalances); if (previous_balances != current_balances) { if (previous_balances != "undefined" && typeof previous_balances != "undefined") { previous_balances = JSON.parse(previous_balances); } else { previous_balances = []; } NRS.database.update("data", { contents: current_balances }, [{ id: "asset_balances_" + NRS.account }]); if (showAssetDifference) { NRS.checkAssetDifferences(NRS.accountInfo.assetBalances, previous_balances); } } } else { NRS.database.insert("data", { id: "asset_balances_" + NRS.account, contents: JSON.stringify(NRS.accountInfo.assetBalances) }); } }); } else if (showAssetDifference && previousAccountInfo && previousAccountInfo.assetBalances) { var previousBalances = JSON.stringify(previousAccountInfo.assetBalances); var currentBalances = JSON.stringify(NRS.accountInfo.assetBalances); if (previousBalances != currentBalances) { NRS.checkAssetDifferences(NRS.accountInfo.assetBalances, previousAccountInfo.assetBalances); } } $("#account_balance, #account_balance_sidebar").html(NRS.formatStyledAmount(response.unconfirmedBalanceNQT)); $("#account_forged_balance").html(NRS.formatStyledAmount(response.forgedBalanceNQT)); /*** Need to clean up and optimize code if possible ***/ var nr_assets = 0; var assets = { "asset": [], "quantity": {}, "trades": {} }; var tradeNum = 0; var assets_LastTrade = []; if (response.assetBalances) { for (var i = 0; i < response.assetBalances.length; i++) { if (response.assetBalances[i].balanceQNT != "0") { nr_assets++; assets.quantity[response.assetBalances[i].asset] = response.assetBalances[i].balanceQNT; assets.asset.push(response.assetBalances[i].asset); NRS.sendRequest("getTrades", { "asset": response.assetBalances[i].asset, "firstIndex": 0, "lastIndex": 0 }, function(responseTrade, input) { if (responseTrade.trades && responseTrade.trades.length) { assets.trades[input.asset] = responseTrade.trades[0].priceNQT/100000000; } else{ assets.trades[input.asset] = 0; } if (tradeNum == nr_assets-1) NRS.updateAssetsValue(assets); else tradeNum++; }); } } } else { $("#account_assets_balance").html(0); } $("#account_nr_assets").html(nr_assets); if (NRS.accountInfo.accountCurrencies && NRS.accountInfo.accountCurrencies.length) { $("#account_currency_count").empty().append(NRS.accountInfo.accountCurrencies.length); } else { $("#account_currency_count").empty().append("0"); } /* Display message count in top and limit to 100 for now because of possible performance issues*/ NRS.sendRequest("getAccountTransactions+", { "account": NRS.account, "type": 1, "subtype": 0, "firstIndex": 0, "lastIndex": 99 }, function(response) { if (response.transactions && response.transactions.length) { if (response.transactions.length > 99) $("#account_message_count").empty().append("99+"); else $("#account_message_count").empty().append(response.transactions.length); } else { $("#account_message_count").empty().append("0"); } }); /*** ****************** ***/ NRS.sendRequest("getAliasCount+", { "account":NRS.account }, function(response) { if (response.numberOfAliases != null) { $("#account_alias_count").empty().append(response.numberOfAliases); } }); NRS.sendRequest("getDGSPurchaseCount+", { "buyer": NRS.account }, function(response) { if (response.numberOfPurchases != null) { $("#account_purchase_count").empty().append(response.numberOfPurchases); } }); NRS.sendRequest("getDGSPendingPurchases+", { "seller": NRS.account }, function(response) { if (response.purchases && response.purchases.length) { $("#account_pending_sale_count").empty().append(response.purchases.length); } else { $("#account_pending_sale_count").empty().append("0"); } }); NRS.sendRequest("getDGSPurchaseCount+", { "seller": NRS.account, "completed": true }, function(response) { if (response.numberOfPurchases != null) { $("#account_completed_sale_count").empty().append(response.numberOfPurchases); } }); if (NRS.lastBlockHeight) { var isLeased = NRS.lastBlockHeight >= NRS.accountInfo.currentLeasingHeightFrom; if (isLeased != NRS.IsLeased) { var leasingChange = true; NRS.isLeased = isLeased; } } else { var leasingChange = false; } if (leasingChange || (response.currentLeasingHeightFrom != previousAccountInfo.currentLeasingHeightFrom) || (response.lessors && !previousAccountInfo.lessors) || (!response.lessors && previousAccountInfo.lessors) || (response.lessors && previousAccountInfo.lessors && response.lessors.sort().toString() != previousAccountInfo.lessors.sort().toString())) { NRS.updateAccountLeasingStatus(); } if (response.name) { $("#account_name").html(response.name.escapeHTML()).removeAttr("data-i18n"); } } if (firstRun) { $("#account_balance, #account_balance_sidebar, #account_assets_balance, #account_nr_assets, #account_currency_count, #account_purchase_count, #account_pending_sale_count, #account_completed_sale_count, #account_message_count, #account_alias_count").removeClass("loading_dots"); } if (callback) { callback(); } }); }; NRS.updateAssetsValue = function(assets) { var assetTotal = 0; for (var i = 0; i < assets.asset.length; i++) { if (assets.quantity[assets.asset[i]] && assets.trades[assets.asset[i]]) assetTotal += assets.quantity[assets.asset[i]]*assets.trades[assets.asset[i]]; } $("#account_assets_balance").html(NRS.formatStyledAmount(new Big(assetTotal).toFixed(8))); }; NRS.updateAccountLeasingStatus = function() { var accountLeasingLabel = ""; var accountLeasingStatus = ""; var nextLesseeStatus = ""; if (NRS.accountInfo.nextLeasingHeightFrom < 2147483647) { nextLesseeStatus = $.t("next_lessee_status", { "start": String(NRS.accountInfo.nextLeasingHeightFrom).escapeHTML(), "end": String(NRS.accountInfo.nextLeasingHeightTo).escapeHTML(), "account": String(NRS.convertNumericToRSAccountFormat(NRS.accountInfo.nextLessee)).escapeHTML() }) } if (NRS.lastBlockHeight >= NRS.accountInfo.currentLeasingHeightFrom) { accountLeasingLabel = $.t("leased_out"); accountLeasingStatus = $.t("balance_is_leased_out", { "blocks": String(NRS.accountInfo.currentLeasingHeightTo - NRS.lastBlockHeight).escapeHTML(), "end": String(NRS.accountInfo.currentLeasingHeightTo).escapeHTML(), "account": String(NRS.accountInfo.currentLesseeRS).escapeHTML() }); $("#lease_balance_message").html($.t("balance_leased_out_help")); } else if (NRS.lastBlockHeight < NRS.accountInfo.currentLeasingHeightTo) { accountLeasingLabel = $.t("leased_soon"); accountLeasingStatus = $.t("balance_will_be_leased_out", { "blocks": String(NRS.accountInfo.currentLeasingHeightFrom - NRS.lastBlockHeight).escapeHTML(), "start": String(NRS.accountInfo.currentLeasingHeightFrom).escapeHTML(), "end": String(NRS.accountInfo.currentLeasingHeightTo).escapeHTML(), "account": String(NRS.accountInfo.currentLesseeRS).escapeHTML() }); $("#lease_balance_message").html($.t("balance_leased_out_help")); } else { accountLeasingStatus = $.t("balance_not_leased_out"); $("#lease_balance_message").html($.t("balance_leasing_help")); } if (nextLesseeStatus != "") { accountLeasingStatus += "<br>" + nextLesseeStatus; } if (NRS.accountInfo.effectiveBalanceNXT == 0) { $("#forging_indicator").removeClass("forging"); $("#forging_indicator span").html($.t("not_forging")).attr("data-i18n", "not_forging"); $("#forging_indicator").show(); NRS.isForging = false; } //no reed solomon available? do it myself? todo if (NRS.accountInfo.lessors) { if (accountLeasingLabel) { accountLeasingLabel += ", "; accountLeasingStatus += "<br /><br />"; } accountLeasingLabel += $.t("x_lessor", { "count": NRS.accountInfo.lessors.length }); accountLeasingStatus += $.t("x_lessor_lease", { "count": NRS.accountInfo.lessors.length }); var rows = ""; for (var i = 0; i < NRS.accountInfo.lessorsRS.length; i++) { var lessor = NRS.accountInfo.lessorsRS[i]; var lessorInfo = NRS.accountInfo.lessorsInfo[i]; var blocksLeft = lessorInfo.currentHeightTo - NRS.lastBlockHeight; var blocksLeftTooltip = "From block " + lessorInfo.currentHeightFrom + " to block " + lessorInfo.currentHeightTo; var nextLessee = "Not set"; var nextTooltip = "Next lessee not set"; if (lessorInfo.nextLesseeRS == NRS.accountRS) { nextLessee = "You"; nextTooltip = "From block " + lessorInfo.nextHeightFrom + " to block " + lessorInfo.nextHeightTo; } else if (lessorInfo.nextHeightFrom < 2147483647) { nextLessee = "Not you"; nextTooltip = "Account " + NRS.getAccountTitle(lessorInfo.nextLesseeRS) +" from block " + lessorInfo.nextHeightFrom + " to block " + lessorInfo.nextHeightTo; } rows += "<tr>" + "<td><a href='#' data-user='" + String(lessor).escapeHTML() + "'>" + NRS.getAccountTitle(lessor) + "</a></td>" + "<td>" + String(lessorInfo.effectiveBalanceNXT).escapeHTML() + "</td>" + "<td><label>" + String(blocksLeft).escapeHTML() + " <i class='fa fa-question-circle show_popover' data-toggle='tooltip' title='" + blocksLeftTooltip + "' data-placement='right' style='color:#4CAA6E'></i></label></td>" + "<td><label>" + String(nextLessee).escapeHTML() + " <i class='fa fa-question-circle show_popover' data-toggle='tooltip' title='" + nextTooltip + "' data-placement='right' style='color:#4CAA6E'></i></label></td>" + "</tr>"; } $("#account_lessor_table tbody").empty().append(rows); $("#account_lessor_container").show(); $("#account_lessor_table [data-toggle='tooltip']").tooltip(); } else { $("#account_lessor_table tbody").empty(); $("#account_lessor_container").hide(); } if (accountLeasingLabel) { $("#account_leasing").html(accountLeasingLabel).show(); } else { $("#account_leasing").hide(); } if (accountLeasingStatus) { $("#account_leasing_status").html(accountLeasingStatus).show(); } else { $("#account_leasing_status").hide(); } }; NRS.checkAssetDifferences = function(current_balances, previous_balances) { var current_balances_ = {}; var previous_balances_ = {}; if (previous_balances.length) { for (var k in previous_balances) { previous_balances_[previous_balances[k].asset] = previous_balances[k].balanceQNT; } } if (current_balances.length) { for (var k in current_balances) { current_balances_[current_balances[k].asset] = current_balances[k].balanceQNT; } } var diff = {}; for (var k in previous_balances_) { if (!(k in current_balances_)) { diff[k] = "-" + previous_balances_[k]; } else if (previous_balances_[k] !== current_balances_[k]) { var change = (new BigInteger(current_balances_[k]).subtract(new BigInteger(previous_balances_[k]))).toString(); diff[k] = change; } } for (k in current_balances_) { if (!(k in previous_balances_)) { diff[k] = current_balances_[k]; // property is new } } var nr = Object.keys(diff).length; if (nr == 0) { return; } else if (nr <= 3) { for (k in diff) { NRS.sendRequest("getAsset", { "asset": k, "_extra": { "asset": k, "difference": diff[k] } }, function(asset, input) { if (asset.errorCode) { return; } asset.difference = input["_extra"].difference; asset.asset = input["_extra"].asset; if (asset.difference.charAt(0) != "-") { var quantity = NRS.formatQuantity(asset.difference, asset.decimals) if (quantity != "0") { $.growl($.t("you_received_assets", { "asset": String(asset.asset).escapeHTML(), "name": String(asset.name).escapeHTML(), "count": quantity }), { "type": "success" }); NRS.loadAssetExchangeSidebar(); } } else { asset.difference = asset.difference.substring(1); var quantity = NRS.formatQuantity(asset.difference, asset.decimals) if (quantity != "0") { $.growl($.t("you_sold_assets", { "asset": String(asset.asset).escapeHTML(), "name": String(asset.name).escapeHTML(), "count": quantity }), { "type": "success" }); NRS.loadAssetExchangeSidebar(); } } }); } } else { $.growl($.t("multiple_assets_differences"), { "type": "success" }); } }; NRS.checkLocationHash = function(password) { if (window.location.hash) { var hash = window.location.hash.replace("#", "").split(":") if (hash.length == 2) { if (hash[0] == "message") { var $modal = $("#send_message_modal"); } else if (hash[0] == "send") { var $modal = $("#send_money_modal"); } else if (hash[0] == "asset") { NRS.goToAsset(hash[1]); return; } else { var $modal = ""; } if ($modal) { var account_id = String($.trim(hash[1])); if (!/^\d+$/.test(account_id) && account_id.indexOf("@") !== 0) { account_id = "@" + account_id; } $modal.find("input[name=recipient]").val(account_id.unescapeHTML()).trigger("blur"); if (password && typeof password == "string") { $modal.find("input[name=secretPhrase]").val(password); } $modal.modal("show"); } } window.location.hash = "#"; } }; NRS.updateBlockchainDownloadProgress = function() { var lastNumBlocks = 5000; $('#downloading_blockchain .last_num_blocks').html($.t('last_num_blocks', { "blocks": lastNumBlocks })); if (!NRS.serverConnect || !NRS.peerConnect) { $("#downloading_blockchain .db_active").hide(); $("#downloading_blockchain .db_halted").show(); } else { $("#downloading_blockchain .db_halted").hide(); $("#downloading_blockchain .db_active").show(); var percentageTotal = 0; var blocksLeft = undefined; var percentageLast = 0; if (NRS.state.lastBlockchainFeederHeight && NRS.state.numberOfBlocks <= NRS.state.lastBlockchainFeederHeight) { percentageTotal = parseInt(Math.round((NRS.state.numberOfBlocks / NRS.state.lastBlockchainFeederHeight) * 100), 10); blocksLeft = NRS.state.lastBlockchainFeederHeight - NRS.state.numberOfBlocks; if (blocksLeft <= lastNumBlocks && NRS.state.lastBlockchainFeederHeight > lastNumBlocks) { percentageLast = parseInt(Math.round(((lastNumBlocks - blocksLeft) / lastNumBlocks) * 100), 10); } } if (!blocksLeft || blocksLeft < parseInt(lastNumBlocks / 2)) { $("#downloading_blockchain .db_progress_total").hide(); } else { $("#downloading_blockchain .db_progress_total").show(); $("#downloading_blockchain .db_progress_total .progress-bar").css("width", percentageTotal + "%"); $("#downloading_blockchain .db_progress_total .sr-only").html($.t("percent_complete", { "percent": percentageTotal })); } if (!blocksLeft || blocksLeft >= (lastNumBlocks * 2) || NRS.state.lastBlockchainFeederHeight <= lastNumBlocks) { $("#downloading_blockchain .db_progress_last").hide(); } else { $("#downloading_blockchain .db_progress_last").show(); $("#downloading_blockchain .db_progress_last .progress-bar").css("width", percentageLast + "%"); $("#downloading_blockchain .db_progress_last .sr-only").html($.t("percent_complete", { "percent": percentageLast })); } if (blocksLeft) { $("#downloading_blockchain .blocks_left_outer").show(); $("#downloading_blockchain .blocks_left").html($.t("blocks_left", { "numBlocks": blocksLeft })); } } }; NRS.checkIfOnAFork = function() { if (!NRS.downloadingBlockchain) { var onAFork = true; if (NRS.blocks && NRS.blocks.length >= 10) { for (var i = 0; i < 10; i++) { if (NRS.blocks[i].generator != NRS.account) { onAFork = false; break; } } } if (onAFork) { $.growl($.t("fork_warning"), { "type": "danger" }); } } }; $("#id_search").on("submit", function(e) { e.preventDefault(); var id = $.trim($("#id_search input[name=q]").val()); if (/NXT\-/i.test(id)) { NRS.sendRequest("getAccount", { "account": id }, function(response, input) { if (!response.errorCode) { response.account = input.account; NRS.showAccountModal(response); } else { $.growl($.t("error_search_no_results"), { "type": "danger" }); } }); } else { if (!/^\d+$/.test(id)) { $.growl($.t("error_search_invalid"), { "type": "danger" }); return; } NRS.sendRequest("getTransaction", { "transaction": id }, function(response, input) { if (!response.errorCode) { response.transaction = input.transaction; NRS.showTransactionModal(response); } else { NRS.sendRequest("getAccount", { "account": id }, function(response, input) { if (!response.errorCode) { response.account = input.account; NRS.showAccountModal(response); } else { NRS.sendRequest("getBlock", { "block": id }, function(response, input) { if (!response.errorCode) { response.block = input.block; NRS.showBlockModal(response); } else { $.growl($.t("error_search_no_results"), { "type": "danger" }); } }); } }); } }); } }); return NRS; }(NRS || {}, jQuery)); $(document).ready(function() { NRS.init(); }); function receiveMessage(event) { if (event.origin != "file://") { return; } //parent.postMessage("from iframe", "file://"); } function _checkDOMenabled() { var storage; var fail; var uid; try { uid = new Date; (storage = window.localStorage).setItem(uid, uid); fail = storage.getItem(uid) != uid; storage.removeItem(uid); fail && (storage = false); } catch (exception) {} return storage; }
{ "content_hash": "ab6d9151b771f28f460080e16f0ef1af", "timestamp": "", "source": "github", "line_count": 1250, "max_line_length": 281, "avg_line_length": 29.8072, "alnum_prop": 0.6130062535226388, "repo_name": "giannisKonst/blockchain", "id": "a97ddbc80b37dfd90c81432b5acebb90b35731ab", "size": "37260", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "html/ui/js/nrs.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "204698" }, { "name": "HTML", "bytes": "686484" }, { "name": "Java", "bytes": "1507542" }, { "name": "JavaScript", "bytes": "667258" }, { "name": "Shell", "bytes": "2627" } ], "symlink_target": "" }
@media print{#searchAd,#searchUser,.navbar{display:none!important}}
{ "content_hash": "d3555c8479799763d55a8bd0df647eeb", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 67, "avg_line_length": 67, "alnum_prop": 0.8059701492537313, "repo_name": "meseven/easyad", "id": "9d85062e7d989926e964c70a4a1c1cb523f2e043", "size": "67", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/dist/css/admin/print.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12461" }, { "name": "HTML", "bytes": "106131" }, { "name": "JavaScript", "bytes": "126297" } ], "symlink_target": "" }
=================================== Rule ``no_useless_concat_operator`` =================================== There should not be useless concat operations. Configuration ------------- ``juggle_simple_strings`` ~~~~~~~~~~~~~~~~~~~~~~~~~ Allow for simple string quote juggling if it results in more concat-operations merges. Allowed types: ``bool`` Default value: ``false`` Examples -------- Example #1 ~~~~~~~~~~ *Default* configuration. .. code-block:: diff --- Original +++ New <?php -$a = 'a'.'b'; +$a = 'ab'; Example #2 ~~~~~~~~~~ With configuration: ``['juggle_simple_strings' => true]``. .. code-block:: diff --- Original +++ New <?php -$a = 'a'."b"; +$a = "ab"; Rule sets --------- The rule is part of the following rule sets: @PhpCsFixer Using the `@PhpCsFixer <./../../ruleSets/PhpCsFixer.rst>`_ rule set will enable the ``no_useless_concat_operator`` rule with the default config. @Symfony Using the `@Symfony <./../../ruleSets/Symfony.rst>`_ rule set will enable the ``no_useless_concat_operator`` rule with the default config.
{ "content_hash": "9240c30d178039e31d12a7279ee1c106", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 146, "avg_line_length": 18.82758620689655, "alnum_prop": 0.5668498168498168, "repo_name": "FriendsOfPHP/PHP-CS-Fixer", "id": "b438f673818a6a02cf28181a3453fc45006bb03f", "size": "1092", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "doc/rules/operator/no_useless_concat_operator.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "3369" }, { "name": "PHP", "bytes": "9499804" }, { "name": "Shell", "bytes": "5393" } ], "symlink_target": "" }
package org.apache.bookkeeper.stream.storage.impl.metadata; import com.google.common.collect.Maps; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.clients.impl.internal.api.StorageServerClientManager; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.statelib.api.mvcc.MVCCAsyncStore; import org.apache.bookkeeper.stream.proto.RangeMetadata; import org.apache.bookkeeper.stream.proto.StreamProperties; import org.apache.bookkeeper.stream.proto.storage.GetActiveRangesRequest; import org.apache.bookkeeper.stream.proto.storage.GetActiveRangesResponse; import org.apache.bookkeeper.stream.proto.storage.RelatedRanges; import org.apache.bookkeeper.stream.proto.storage.RelationType; import org.apache.bookkeeper.stream.proto.storage.StatusCode; import org.apache.bookkeeper.stream.protocol.util.StorageContainerPlacementPolicy; import org.apache.bookkeeper.stream.storage.api.metadata.MetaRangeStore; import org.apache.bookkeeper.stream.storage.api.metadata.stream.MetaRange; import org.apache.bookkeeper.stream.storage.impl.metadata.stream.MetaRangeImpl; /** * The default implementation of {@link MetaRangeStore}. */ @Slf4j public class MetaRangeStoreImpl implements MetaRangeStore { private final MVCCAsyncStore<byte[], byte[]> store; private final ScheduledExecutorService executor; private final StorageContainerPlacementPolicy rangePlacementPolicy; private final Map<Long, MetaRangeImpl> streams; private final StorageServerClientManager clientManager; public MetaRangeStoreImpl(MVCCAsyncStore<byte[], byte[]> store, StorageContainerPlacementPolicy rangePlacementPolicy, ScheduledExecutorService executor, StorageServerClientManager clientManager) { this.store = store; this.executor = executor; this.rangePlacementPolicy = rangePlacementPolicy; this.streams = Maps.newHashMap(); this.clientManager = clientManager; } // // Methods for {@link MetaRangeStore} // // // Stream API // private CompletableFuture<GetActiveRangesResponse> createStreamIfMissing(long streamId, MetaRangeImpl metaRange, StreamProperties streamProps) { if (null == streamProps) { return FutureUtils.value(GetActiveRangesResponse.newBuilder() .setCode(StatusCode.STREAM_NOT_FOUND) .build()); } return metaRange.create(streamProps).thenCompose(created -> { if (created) { synchronized (streams) { streams.put(streamId, metaRange); } return getActiveRanges(metaRange); } else { return FutureUtils.value(GetActiveRangesResponse.newBuilder() .setCode(StatusCode.INTERNAL_SERVER_ERROR) .build()); } }); } @Override public CompletableFuture<GetActiveRangesResponse> getActiveRanges(GetActiveRangesRequest request) { final long streamId = request.getStreamId(); MetaRangeImpl metaRange = streams.get(streamId); if (null == metaRange) { final MetaRangeImpl metaRangeImpl = new MetaRangeImpl(store, executor, rangePlacementPolicy); return metaRangeImpl.load(streamId) .thenCompose(mr -> { if (null == mr) { // meta range doesn't exist, talk to root range to get the stream props return clientManager.getStreamProperties(streamId) .thenCompose(streamProperties -> createStreamIfMissing(streamId, metaRangeImpl, streamProperties)); } else { synchronized (streams) { streams.put(streamId, (MetaRangeImpl) mr); } return getActiveRanges(mr); } }); } else { return getActiveRanges(metaRange); } } private CompletableFuture<GetActiveRangesResponse> getActiveRanges(MetaRange metaRange) { GetActiveRangesResponse.Builder respBuilder = GetActiveRangesResponse.newBuilder(); return metaRange.getActiveRanges() .thenApplyAsync(ranges -> { for (RangeMetadata range : ranges) { RelatedRanges.Builder rrBuilder = RelatedRanges.newBuilder() .setProps(range.getProps()) .setType(RelationType.PARENTS) .addAllRelatedRanges(range.getParentsList()); respBuilder.addRanges(rrBuilder); } return respBuilder .setCode(StatusCode.SUCCESS) .build(); }, executor) .exceptionally(cause -> respBuilder.setCode(StatusCode.INTERNAL_SERVER_ERROR).build()); } }
{ "content_hash": "840fbb4aafbbc37f126fbb4b4e8c86b0", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 108, "avg_line_length": 42.584, "alnum_prop": 0.6300958106331016, "repo_name": "apache/bookkeeper", "id": "b64d3205f71a8fb9548c524032571f379a5d35ef", "size": "6129", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "stream/storage/impl/src/main/java/org/apache/bookkeeper/stream/storage/impl/metadata/MetaRangeStoreImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "11886" }, { "name": "C++", "bytes": "17844" }, { "name": "Dockerfile", "bytes": "11186" }, { "name": "Groovy", "bytes": "48262" }, { "name": "Java", "bytes": "15908174" }, { "name": "JavaScript", "bytes": "12042" }, { "name": "Makefile", "bytes": "6544" }, { "name": "Python", "bytes": "215336" }, { "name": "Roff", "bytes": "39396" }, { "name": "SCSS", "bytes": "1345" }, { "name": "Shell", "bytes": "183376" }, { "name": "Thrift", "bytes": "1473" } ], "symlink_target": "" }
package com.netflix.spinnaker.clouddriver.ecs.provider.view; import static com.netflix.spinnaker.clouddriver.core.provider.agent.Namespace.TARGET_GROUPS; import com.amazonaws.services.ecs.model.LoadBalancer; import com.google.common.collect.Sets; import com.netflix.spinnaker.clouddriver.aws.AmazonCloudProvider; import com.netflix.spinnaker.clouddriver.aws.data.ArnUtils; import com.netflix.spinnaker.clouddriver.ecs.EcsCloudProvider; import com.netflix.spinnaker.clouddriver.ecs.cache.client.EcsLoadbalancerCacheClient; import com.netflix.spinnaker.clouddriver.ecs.cache.client.EcsTargetGroupCacheClient; import com.netflix.spinnaker.clouddriver.ecs.cache.client.ServiceCacheClient; import com.netflix.spinnaker.clouddriver.ecs.cache.model.EcsLoadBalancerCache; import com.netflix.spinnaker.clouddriver.ecs.cache.model.Service; import com.netflix.spinnaker.clouddriver.ecs.model.loadbalancer.EcsLoadBalancer; import com.netflix.spinnaker.clouddriver.ecs.model.loadbalancer.EcsLoadBalancerDetail; import com.netflix.spinnaker.clouddriver.ecs.model.loadbalancer.EcsLoadBalancerSummary; import com.netflix.spinnaker.clouddriver.ecs.model.loadbalancer.EcsTargetGroup; import com.netflix.spinnaker.clouddriver.model.LoadBalancerProvider; import java.util.*; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class EcsLoadBalancerProvider implements LoadBalancerProvider<EcsLoadBalancer> { private final EcsLoadbalancerCacheClient ecsLoadbalancerCacheClient; private final EcsAccountMapper ecsAccountMapper; private final ServiceCacheClient ecsServiceCacheClient; private final EcsTargetGroupCacheClient ecsTargetGroupCacheClient; private final Logger log = LoggerFactory.getLogger(getClass()); @Autowired public EcsLoadBalancerProvider( EcsLoadbalancerCacheClient ecsLoadbalancerCacheClient, EcsAccountMapper ecsAccountMapper, ServiceCacheClient ecsServiceCacheClient, EcsTargetGroupCacheClient ecsTargetGroupCacheClient) { this.ecsLoadbalancerCacheClient = ecsLoadbalancerCacheClient; this.ecsAccountMapper = ecsAccountMapper; this.ecsServiceCacheClient = ecsServiceCacheClient; this.ecsTargetGroupCacheClient = ecsTargetGroupCacheClient; } @Override public String getCloudProvider() { return EcsCloudProvider.ID; } @Override public List<Item> list() { Map<String, EcsLoadBalancerSummary> map = new HashMap<>(); List<EcsLoadBalancerCache> loadBalancers = ecsLoadbalancerCacheClient.findAll(); for (EcsLoadBalancerCache lb : loadBalancers) { if (lb.getAccount() == null) { continue; } String name = lb.getLoadBalancerName(); String region = lb.getRegion(); EcsLoadBalancerSummary summary = map.get(name); if (summary == null) { summary = new EcsLoadBalancerSummary().withName(name); map.put(name, summary); } EcsLoadBalancerDetail loadBalancer = new EcsLoadBalancerDetail(); loadBalancer.setAccount(lb.getAccount()); loadBalancer.setRegion(region); loadBalancer.setName(name); loadBalancer.setVpcId(lb.getVpcId()); loadBalancer.setSecurityGroups(lb.getSecurityGroups()); loadBalancer.setLoadBalancerType(lb.getLoadBalancerType()); loadBalancer.setTargetGroups(lb.getTargetGroups()); summary .getOrCreateAccount(lb.getAccount()) .getOrCreateRegion(region) .getLoadBalancers() .add(loadBalancer); } return new ArrayList<>(map.values()); } @Override public Item get(String name) { return null; // intentionally null, implement if/when needed in Deck. } @Override public List<Details> byAccountAndRegionAndName(String account, String region, String name) { return null; // intentionally null, implement if/when needed in Deck. } @Override public Set<EcsLoadBalancer> getApplicationLoadBalancers(String application) { // Find the load balancers currently in use by ECS services in this application Set<Service> services = ecsServiceCacheClient.getAll().stream() .filter(service -> service.getApplicationName().equals(application)) .collect(Collectors.toSet()); log.debug("Retrieved {} services for application '{}'", services.size(), application); Collection<String> allTargetGroupKeys = ecsTargetGroupCacheClient.getAllKeys(); log.debug( "Retrieved {} target group keys for application '{}'", allTargetGroupKeys.size(), application); Map<String, Set<String>> targetGroupToServicesMap = new HashMap<>(); Set<String> targetGroupKeys = new HashSet<>(); // find all the target group cache keys for (Service service : services) { String awsAccountName = ecsAccountMapper.fromEcsAccountNameToAwsAccountName(service.getAccount()); for (LoadBalancer loadBalancer : service.getLoadBalancers()) { if (loadBalancer.getTargetGroupArn() != null) { String tgArn = loadBalancer.getTargetGroupArn(); String keyPrefix = String.format( "%s:%s:%s:%s:%s:", AmazonCloudProvider.ID, TARGET_GROUPS.getNs(), awsAccountName, service.getRegion(), ArnUtils.extractTargetGroupName(tgArn).get()); Set<String> matchingKeys = allTargetGroupKeys.stream() .filter(key -> key.startsWith(keyPrefix)) .collect(Collectors.toSet()); targetGroupKeys.addAll(matchingKeys); // associate target group with services it contains targets for if (targetGroupToServicesMap.containsKey(tgArn)) { log.debug("Mapping additional service '{}' to '{}'", service.getServiceName(), tgArn); Set<String> serviceList = targetGroupToServicesMap.get(tgArn); serviceList.add(service.getServiceName()); targetGroupToServicesMap.put(tgArn, serviceList); } else { log.debug("Mapping service '{}' to '{}'", service.getServiceName(), tgArn); Set<String> srcServices = Sets.newHashSet(service.getServiceName()); targetGroupToServicesMap.put(tgArn, srcServices); } } } } // retrieve matching target groups List<EcsTargetGroup> tgs = ecsTargetGroupCacheClient.find(targetGroupKeys); // find the load balancers for those target groups List<EcsLoadBalancerCache> tgLBs = ecsLoadbalancerCacheClient.findWithTargetGroups(targetGroupKeys); log.debug( "Retrieved {} load balancers for {} target group keys.", tgLBs.size(), targetGroupKeys.size()); Set<EcsLoadBalancer> ecsLoadBalancers = new HashSet<>(); for (EcsLoadBalancerCache loadBalancerCache : tgLBs) { List<EcsTargetGroup> matchingTGs = tgs.stream() .filter(tg -> loadBalancerCache.getTargetGroups().contains(tg.getTargetGroupName())) .collect(Collectors.toList()); EcsLoadBalancer ecsLB = makeEcsLoadBalancer(loadBalancerCache, matchingTGs, targetGroupToServicesMap); ecsLoadBalancers.add(ecsLB); } return ecsLoadBalancers; } private EcsLoadBalancer makeEcsLoadBalancer( EcsLoadBalancerCache elbCacheData, List<EcsTargetGroup> tgCacheData, Map<String, Set<String>> tgToServiceMap) { EcsLoadBalancer ecsLoadBalancer = new EcsLoadBalancer(); ecsLoadBalancer.setAccount(elbCacheData.getAccount()); ecsLoadBalancer.setRegion(elbCacheData.getRegion()); ecsLoadBalancer.setLoadBalancerArn(elbCacheData.getLoadBalancerArn()); ecsLoadBalancer.setLoadBalancerName(elbCacheData.getLoadBalancerName()); ecsLoadBalancer.setLoadBalancerType(elbCacheData.getLoadBalancerType()); ecsLoadBalancer.setCloudProvider(elbCacheData.getCloudProvider()); ecsLoadBalancer.setListeners(elbCacheData.getListeners()); ecsLoadBalancer.setAvailabilityZones(elbCacheData.getAvailabilityZones()); ecsLoadBalancer.setIpAddressType(elbCacheData.getIpAddressType()); ecsLoadBalancer.setDnsname(elbCacheData.getDnsname()); ecsLoadBalancer.setVpcId(elbCacheData.getVpcId()); ecsLoadBalancer.setCreatedTime(elbCacheData.getCreatedTime()); ecsLoadBalancer.setSecurityGroups(elbCacheData.getSecurityGroups()); ecsLoadBalancer.setSubnets(elbCacheData.getSubnets()); ecsLoadBalancer.setTargetGroups(tgCacheData); ecsLoadBalancer.setTargetGroupServices(tgToServiceMap); // TODO: get, add target healths per service/tg return ecsLoadBalancer; } }
{ "content_hash": "543a5eafce1c4424447fef74d1231b59", "timestamp": "", "source": "github", "line_count": 207, "max_line_length": 98, "avg_line_length": 42.35748792270532, "alnum_prop": 0.7309534671532847, "repo_name": "ajordens/clouddriver", "id": "24b0e6d384eb592445359923912a274ecb6a2fda", "size": "9363", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "clouddriver-ecs/src/main/java/com/netflix/spinnaker/clouddriver/ecs/provider/view/EcsLoadBalancerProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "7717938" }, { "name": "HTML", "bytes": "1493" }, { "name": "Java", "bytes": "4421205" }, { "name": "Kotlin", "bytes": "282523" }, { "name": "Shell", "bytes": "3135" }, { "name": "TSQL", "bytes": "444" } ], "symlink_target": "" }
source $HELPER_SCRIPTS/install.sh source $HELPER_SCRIPTS/etc-environment.sh # Install GraalVM GRAALVM_ROOT=/usr/local/graalvm export GRAALVM_11_ROOT=$GRAALVM_ROOT/graalvm-ce-java11* downloadUrl=$(get_github_package_download_url "graalvm/graalvm-ce-builds" "contains(\"graalvm-ce-java11-linux-amd64\") and endswith(\"tar.gz\")") download_with_retries "$downloadUrl" "/tmp" "graalvm-archive.tar.gz" mkdir $GRAALVM_ROOT tar -xzf "/tmp/graalvm-archive.tar.gz" -C $GRAALVM_ROOT # Set environment variable for GraalVM root setEtcEnvironmentVariable "GRAALVM_11_ROOT" $GRAALVM_11_ROOT # Install Native Image $GRAALVM_11_ROOT/bin/gu install native-image invoke_tests "Tools" "GraalVM"
{ "content_hash": "68e28b81797b60d0fa7d69819b5e5b3b", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 145, "avg_line_length": 35.89473684210526, "alnum_prop": 0.7756598240469208, "repo_name": "mattgwagner/New-Machine", "id": "6a79032b50c2b956cb59766d91bfdbf823bbc735", "size": "698", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": ".github-actions/images/linux/scripts/installers/graalvm.sh", "mode": "33188", "license": "mit", "language": [ { "name": "AppleScript", "bytes": "1726" }, { "name": "Batchfile", "bytes": "185" }, { "name": "HCL", "bytes": "29543" }, { "name": "PowerShell", "bytes": "596822" }, { "name": "Python", "bytes": "2435" }, { "name": "Ruby", "bytes": "5743" }, { "name": "Shell", "bytes": "196728" }, { "name": "Swift", "bytes": "2148" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <include android:id="@+id/toolbar" layout="@layout/toolbar"/> </android.support.design.widget.AppBarLayout> <include android:id="@+id/fragment_container" layout="@layout/fragment_container"/> <include layout="@layout/fab"/> </android.support.design.widget.CoordinatorLayout>
{ "content_hash": "4ecd73f05f08237010330bf995dab02a", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 62, "avg_line_length": 29.77777777777778, "alnum_prop": 0.6791044776119403, "repo_name": "denisura/mordor", "id": "87963e21fef4e854e2a998af3abe30a812ba32e4", "size": "804", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/activity_fragment_collection.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "125083" } ], "symlink_target": "" }
.scripts-pause-on-exceptions-status-bar-item .glyph { -webkit-mask-position: -256px 0; } .scripts-pause-on-exceptions-status-bar-item.toggled-on .glyph { background-color: rgb(66, 129, 235); } .evaluate-snippet-status-bar-item .glyph { -webkit-mask-position: -64px -48px; } .evaluate-snippet-status-bar-item.toggled .glyph { background-color: rgb(66, 129, 235); } .scripts-debug-toolbar { position: absolute; top: 0; width: 100%; background-color: rgb(236, 236, 236); overflow: hidden; white-space: nowrap; } .scripts-debug-toolbar-drawer { flex: 0 0 46px; -webkit-transition: margin-top 0.1s ease-in-out; margin-top: -23px; line-height: 23px; padding-top: 22px; border-bottom: 1px solid rgb(202, 202, 202); background-color: white; overflow: hidden; } .scripts-debug-toolbar-drawer.expanded { margin-top: 0; } .scripts-debug-toolbar-drawer > label { display: flex; padding-left: 3px; border-top: 1px solid rgb(196,196,196); } #scripts-editor-toolbar { position: relative; margin-top: -1px; height: 24px; } .scripts-run-snippet .glyph { -webkit-mask-position: -64px -48px; } .scripts-pause .glyph { -webkit-mask-position: -32px -72px; } .scripts-pause.toggled-on .glyph { -webkit-mask-position: 0 -72px; } .scripts-step-over .glyph { -webkit-mask-position: -128px -72px; } .scripts-step-into .glyph { -webkit-mask-position: -64px -72px; } .scripts-step-out .glyph { -webkit-mask-position: -96px -72px; } .scripts-long-resume .glyph { -webkit-mask-position: -64px -48px; } .scripts-toggle-breakpoints.toggled-on .glyph { -webkit-mask-position: -32px 0; } .scripts-toggle-breakpoints .glyph { -webkit-mask-position: 0 -24px; } .dedicated-worker-item { margin: 5px 0 5px 1px; } #shared-workers-list { margin: 5px 0 5px 20px; font-style:italic; } #pause-workers-checkbox > input { position: relative; top: 2px; } .panel.sources #sources-editor-container-tabbed-pane .tabbed-pane-header-contents { margin-left: 22px; margin-right: 36px; } .panel.sources .split-view button.scripts-debugger-show-hide-button.right-sidebar-show-hide-button.toggled-hide { margin-right: 15px; } .panel.sources .split-view #scripts-debug-sidebar-resizer-widget.ns-resizer-widget { -webkit-transform: rotate(90deg); right: 17px; bottom: 4px; top: auto; height: 10px; width: 18px; } .panel.sources .split-view.hbox #scripts-debug-sidebar-resizer-widget { bottom: 0; } .panel.sources .scripts-debugger-show-hide-button { display: block; } .panel.sources button.status-bar-item.scripts-navigator-show-hide-button { display: block; top: 4px; left: 4px; } .panel.sources .navigator-tabbed-pane .tabbed-pane-header { background-color: rgb(236, 236, 236); } .function-location-link { float: right; margin-left: 10px; } .function-popover-title { border-bottom: 1px solid #AAA; margin-bottom: 3px; padding-bottom: 2px; } .function-popover-title .function-name { font-weight: bold; } .workers-list > li { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-left: 1em; font-size: 12px; } a.worker-item { color: rgb(33%, 33%, 33%); cursor: pointer; text-decoration: none; } a.worker-item:hover { color: rgb(15%, 15%, 15%); } .panel.sources .sidebar-pane-stack { overflow: auto; } .threads-toolbar { padding-left: 10px; margin-top: -1px; } .panel.sources .drag-mask { background-color: rgba(255,255,255,0.8); z-index: 1000; } .panel.sources .drag-mask-inner { font-size: 30px; color: #999; display: flex; justify-content: center; align-items: center; margin: 20px; border: 4px dashed #ddd; pointer-events: none; }
{ "content_hash": "94c917a14499044dd656e0273cc02e9b", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 113, "avg_line_length": 19.593908629441625, "alnum_prop": 0.6585492227979275, "repo_name": "danieldanciu/schoggi", "id": "6416333ce5b8f7024f4427af2765336e918910db", "size": "5493", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "gae_mini_profiler/static/chrome/inspector-20140603/sourcesPanel.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "341225" }, { "name": "HTML", "bytes": "3369532" }, { "name": "Java", "bytes": "705" }, { "name": "JavaScript", "bytes": "1660297" }, { "name": "Python", "bytes": "3319431" }, { "name": "Shell", "bytes": "19316" } ], "symlink_target": "" }
<?php // ------------------------------------------------------------------------ namespace O2System\ORM\Relations; defined( 'ROOTPATH' ) || exit( 'No direct script access allowed' ); // ------------------------------------------------------------------------ use O2System\ORM; use O2System\ORM\Factory\Relation; use O2System\ORM\Factory\Query; /** * ORM Polymorphic To Many Relationship Factory Class * * @package O2System * @subpackage core/orm/factory * @category core libraries driver factory * @author Circle Creative Dev Team * @link http://o2system.center/wiki/#ORMBelongsTo */ class Morph_many extends Relation { /** * Result * * Abstract: extended class of Relation must implements result method * * @return mixed */ public function result() { // TODO: Implement result() method. } }
{ "content_hash": "fd0042cd0388600efd9c534a1577146b", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 75, "avg_line_length": 23.710526315789473, "alnum_prop": 0.5294117647058824, "repo_name": "circlecreative/o2orm", "id": "99683a5a0bb1a0bbbbfc4e17043fc719a327a96d", "size": "2513", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Relations/Morph_Many.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "115802" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <!-- Appenders --> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p: %c - %m%n" /> </layout> </appender> <!-- Application Loggers --> <logger name="com.fullstackstarter.SpringCustomAnnotation"> <level value="info" /> </logger> <!-- 3rdparty Loggers --> <logger name="org.springframework.core"> <level value="info" /> </logger> <logger name="org.springframework.beans"> <level value="info" /> </logger> <logger name="org.springframework.context"> <level value="info" /> </logger> <logger name="org.springframework.web"> <level value="info" /> </logger> <!-- Root Logger --> <root> <priority value="info" /> <appender-ref ref="console" /> </root> </log4j:configuration>
{ "content_hash": "e16ac056ceb8b4fee33e78af50450d0c", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 80, "avg_line_length": 25.975609756097562, "alnum_prop": 0.6591549295774648, "repo_name": "FiaDot/spring-custom-annotation", "id": "b1dcdbb27dfae69622aa25af9a5c4d6191d732b7", "size": "1065", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/resources/log4j.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2437" } ], "symlink_target": "" }
require 'spec_helper' describe Milestone do let(:milestone) { milestones(:public) } let(:workspace) { workspaces(:public) } let(:params) { {:name => 'cool milestone', :target_date => '2020-07-30T14:00:00-07:00'} } let(:actor) { users(:owner) } describe "create" do it "updates the workspace's target date" do expect { workspace.milestones.create(params) workspace.reload }.to change(workspace, :project_target_date).to(Date.parse(params[:target_date])) end it "creates activity after user creates a milestone" do expect do Events::MilestoneCreated.add( :actor => actor, :milestone => milestone, :workspace => workspace, ) end end end describe "destroy" do context "deleting the milestone with the target date" do let(:last_date) { workspace.project_target_date } let(:last_ms) { workspace.milestones.order(:target_date).last } let(:dates) { workspace.milestones.order(:target_date).map(&:target_date) } it "updates its workspace's project target date" do expect { last_ms.destroy workspace.reload }.to change(workspace, :project_target_date).from(last_date).to(dates[dates.length-2]) end end end end
{ "content_hash": "02f22bd0b066596cfad3821a7ec6c703", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 94, "avg_line_length": 29, "alnum_prop": 0.6268199233716475, "repo_name": "atul-alpine/chorus", "id": "30c2222ac80b4ee8ba2680d8cb3913f82ffe5e5b", "size": "1305", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/models/milestone_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "70" }, { "name": "CSS", "bytes": "390729" }, { "name": "HTML", "bytes": "62382" }, { "name": "Handlebars", "bytes": "226541" }, { "name": "Java", "bytes": "107" }, { "name": "JavaScript", "bytes": "4535821" }, { "name": "Python", "bytes": "74117" }, { "name": "Rebol", "bytes": "107" }, { "name": "Ruby", "bytes": "2557415" }, { "name": "Shell", "bytes": "72889" }, { "name": "VimL", "bytes": "339" } ], "symlink_target": "" }
/* * * * X-range series module * * (c) 2010-2020 Torstein Honsi, Lars A. V. Cabrera * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from '../parts/Globals.js'; /* * * @interface Highcharts.PointOptionsObject in parts/Point.ts */ /** * The ending X value of the range point. * @name Highcharts.PointOptionsObject#x2 * @type {number|undefined} * @requires modules/xrange */ import Color from '../parts/Color.js'; var color = Color.parse; import Point from '../parts/Point.js'; import U from '../parts/Utilities.js'; var addEvent = U.addEvent, clamp = U.clamp, correctFloat = U.correctFloat, defined = U.defined, find = U.find, isNumber = U.isNumber, isObject = U.isObject, merge = U.merge, pick = U.pick, seriesType = U.seriesType; var columnType = H.seriesTypes.column, seriesTypes = H.seriesTypes, Axis = H.Axis, Series = H.Series; /** * Return color of a point based on its category. * * @private * @function getColorByCategory * * @param {object} series * The series which the point belongs to. * * @param {object} point * The point to calculate its color for. * * @return {object} * Returns an object containing the properties color and colorIndex. */ function getColorByCategory(series, point) { var colors = series.options.colors || series.chart.options.colors, colorCount = colors ? colors.length : series.chart.options.chart.colorCount, colorIndex = point.y % colorCount, color = colors && colors[colorIndex]; return { colorIndex: colorIndex, color: color }; } /** * @private * @class * @name Highcharts.seriesTypes.xrange * * @augments Highcharts.Series */ seriesType('xrange', 'column' /** * The X-range series displays ranges on the X axis, typically time * intervals with a start and end date. * * @sample {highcharts} highcharts/demo/x-range/ * X-range * @sample {highcharts} highcharts/css/x-range/ * Styled mode X-range * @sample {highcharts} highcharts/chart/inverted-xrange/ * Inverted X-range * * @extends plotOptions.column * @since 6.0.0 * @product highcharts highstock gantt * @excluding boostThreshold, crisp, cropThreshold, depth, edgeColor, * edgeWidth, findNearestPointBy, getExtremesFromAll, * negativeColor, pointInterval, pointIntervalUnit, * pointPlacement, pointRange, pointStart, softThreshold, * stacking, threshold, data, dataSorting * @requires modules/xrange * @optionparent plotOptions.xrange */ , { /** * A partial fill for each point, typically used to visualize how much * of a task is performed. The partial fill object can be set either on * series or point level. * * @sample {highcharts} highcharts/demo/x-range * X-range with partial fill * * @product highcharts highstock gantt * @apioption plotOptions.xrange.partialFill */ /** * The fill color to be used for partial fills. Defaults to a darker * shade of the point color. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highcharts highstock gantt * @apioption plotOptions.xrange.partialFill.fill */ /** * A partial fill for each point, typically used to visualize how much * of a task is performed. See [completed](series.gantt.data.completed). * * @sample gantt/demo/progress-indicator * Gantt with progress indicator * * @product gantt * @apioption plotOptions.gantt.partialFill */ /** * In an X-range series, this option makes all points of the same Y-axis * category the same color. */ colorByPoint: true, dataLabels: { formatter: function () { var point = this.point, amount = point.partialFill; if (isObject(amount)) { amount = amount.amount; } if (isNumber(amount) && amount > 0) { return correctFloat(amount * 100) + '%'; } }, inside: true, verticalAlign: 'middle' }, tooltip: { headerFormat: '<span style="font-size: 10px">{point.x} - {point.x2}</span><br/>', pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.yCategory}</b><br/>' }, borderRadius: 3, pointRange: 0 }, { type: 'xrange', parallelArrays: ['x', 'x2', 'y'], requireSorting: false, animate: seriesTypes.line.prototype.animate, cropShoulder: 1, getExtremesFromAll: true, autoIncrement: H.noop, buildKDTree: H.noop, /* eslint-disable valid-jsdoc */ /** * @private * @function Highcarts.seriesTypes.xrange#init * @return {void} */ init: function () { seriesTypes.column.prototype.init.apply(this, arguments); this.options.stacking = void 0; // #13161 }, /** * Borrow the column series metrics, but with swapped axes. This gives * free access to features like groupPadding, grouping, pointWidth etc. * * @private * @function Highcharts.Series#getColumnMetrics * * @return {Highcharts.ColumnMetricsObject} */ getColumnMetrics: function () { var metrics, chart = this.chart; /** * @private */ function swapAxes() { chart.series.forEach(function (s) { var xAxis = s.xAxis; s.xAxis = s.yAxis; s.yAxis = xAxis; }); } swapAxes(); metrics = columnType.prototype.getColumnMetrics.call(this); swapAxes(); return metrics; }, /** * Override cropData to show a point where x or x2 is outside visible * range, but one of them is inside. * * @private * @function Highcharts.Series#cropData * * @param {Array<number>} xData * * @param {Array<number>} yData * * @param {number} min * * @param {number} max * * @param {number} [cropShoulder] * * @return {*} */ cropData: function (xData, yData, min, max) { // Replace xData with x2Data to find the appropriate cropStart var cropData = Series.prototype.cropData, crop = cropData.call(this, this.x2Data, yData, min, max); // Re-insert the cropped xData crop.xData = xData.slice(crop.start, crop.end); return crop; }, /** * Finds the index of an existing point that matches the given point * options. * * @private * @function Highcharts.Series#findPointIndex * @param {object} options The options of the point. * @returns {number|undefined} Returns index of a matching point, * returns undefined if no match is found. */ findPointIndex: function (options) { var _a = this, cropped = _a.cropped, cropStart = _a.cropStart, points = _a.points; var id = options.id; var pointIndex; if (id) { var point = find(points, function (point) { return point.id === id; }); pointIndex = point ? point.index : void 0; } if (typeof pointIndex === 'undefined') { var point = find(points, function (point) { return (point.x === options.x && point.x2 === options.x2 && !point.touched); }); pointIndex = point ? point.index : void 0; } // Reduce pointIndex if data is cropped if (cropped && isNumber(pointIndex) && isNumber(cropStart) && pointIndex >= cropStart) { pointIndex -= cropStart; } return pointIndex; }, /** * @private * @function Highcharts.Series#translatePoint * * @param {Highcharts.Point} point */ translatePoint: function (point) { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, metrics = series.columnMetrics, options = series.options, minPointLength = options.minPointLength || 0, plotX = point.plotX, posX = pick(point.x2, point.x + (point.len || 0)), plotX2 = xAxis.translate(posX, 0, 0, 0, 1), length = Math.abs(plotX2 - plotX), widthDifference, shapeArgs, partialFill, inverted = this.chart.inverted, borderWidth = pick(options.borderWidth, 1), crisper = borderWidth % 2 / 2, yOffset = metrics.offset, pointHeight = Math.round(metrics.width), dlLeft, dlRight, dlWidth, clipRectWidth, tooltipYOffset; if (minPointLength) { widthDifference = minPointLength - length; if (widthDifference < 0) { widthDifference = 0; } plotX -= widthDifference / 2; plotX2 += widthDifference / 2; } plotX = Math.max(plotX, -10); plotX2 = clamp(plotX2, -10, xAxis.len + 10); // Handle individual pointWidth if (defined(point.options.pointWidth)) { yOffset -= ((Math.ceil(point.options.pointWidth) - pointHeight) / 2); pointHeight = Math.ceil(point.options.pointWidth); } // Apply pointPlacement to the Y axis if (options.pointPlacement && isNumber(point.plotY) && yAxis.categories) { point.plotY = yAxis.translate(point.y, 0, 1, 0, 1, options.pointPlacement); } point.shapeArgs = { x: Math.floor(Math.min(plotX, plotX2)) + crisper, y: Math.floor(point.plotY + yOffset) + crisper, width: Math.round(Math.abs(plotX2 - plotX)), height: pointHeight, r: series.options.borderRadius }; // Align data labels inside the shape and inside the plot area dlLeft = point.shapeArgs.x; dlRight = dlLeft + point.shapeArgs.width; if (dlLeft < 0 || dlRight > xAxis.len) { dlLeft = clamp(dlLeft, 0, xAxis.len); dlRight = clamp(dlRight, 0, xAxis.len); dlWidth = dlRight - dlLeft; point.dlBox = merge(point.shapeArgs, { x: dlLeft, width: dlRight - dlLeft, centerX: dlWidth ? dlWidth / 2 : null }); } else { point.dlBox = null; } // Tooltip position var tooltipPos = point.tooltipPos; var xIndex = !inverted ? 0 : 1; var yIndex = !inverted ? 1 : 0; tooltipYOffset = series.columnMetrics ? series.columnMetrics.offset : -metrics.width / 2; // Limit position by the correct axis size (#9727) tooltipPos[xIndex] = clamp(tooltipPos[xIndex] + ((!inverted ? 1 : -1) * (xAxis.reversed ? -1 : 1) * (length / 2)), 0, xAxis.len - 1); tooltipPos[yIndex] = clamp(tooltipPos[yIndex] + ((inverted ? -1 : 1) * tooltipYOffset), 0, yAxis.len - 1); // Add a partShapeArgs to the point, based on the shapeArgs property partialFill = point.partialFill; if (partialFill) { // Get the partial fill amount if (isObject(partialFill)) { partialFill = partialFill.amount; } // If it was not a number, assume 0 if (!isNumber(partialFill)) { partialFill = 0; } shapeArgs = point.shapeArgs; point.partShapeArgs = { x: shapeArgs.x, y: shapeArgs.y, width: shapeArgs.width, height: shapeArgs.height, r: series.options.borderRadius }; clipRectWidth = Math.max(Math.round(length * partialFill + point.plotX - plotX), 0); point.clipRectArgs = { x: xAxis.reversed ? // #10717 shapeArgs.x + length - clipRectWidth : shapeArgs.x, y: shapeArgs.y, width: clipRectWidth, height: shapeArgs.height }; } }, /** * @private * @function Highcharts.Series#translate */ translate: function () { columnType.prototype.translate.apply(this, arguments); this.points.forEach(function (point) { this.translatePoint(point); }, this); }, /** * Draws a single point in the series. Needed for partial fill. * * This override turns point.graphic into a group containing the * original graphic and an overlay displaying the partial fill. * * @private * @function Highcharts.Series#drawPoint * * @param {Highcharts.Point} point * An instance of Point in the series. * * @param {"animate"|"attr"} verb * 'animate' (animates changes) or 'attr' (sets options) */ drawPoint: function (point, verb) { var series = this, seriesOpts = series.options, renderer = series.chart.renderer, graphic = point.graphic, type = point.shapeType, shapeArgs = point.shapeArgs, partShapeArgs = point.partShapeArgs, clipRectArgs = point.clipRectArgs, pfOptions = point.partialFill, cutOff = seriesOpts.stacking && !seriesOpts.borderRadius, pointState = point.state, stateOpts = (seriesOpts.states[pointState || 'normal'] || {}), pointStateVerb = typeof pointState === 'undefined' ? 'attr' : verb, pointAttr = series.pointAttribs(point, pointState), animation = pick(series.chart.options.chart.animation, stateOpts.animation), fill; if (!point.isNull && point.visible !== false) { // Original graphic if (graphic) { // update graphic.rect[verb](shapeArgs); } else { point.graphic = graphic = renderer.g('point') .addClass(point.getClassName()) .add(point.group || series.group); graphic.rect = renderer[type](merge(shapeArgs)) .addClass(point.getClassName()) .addClass('highcharts-partfill-original') .add(graphic); } // Partial fill graphic if (partShapeArgs) { if (graphic.partRect) { graphic.partRect[verb](merge(partShapeArgs)); graphic.partialClipRect[verb](merge(clipRectArgs)); } else { graphic.partialClipRect = renderer.clipRect(clipRectArgs.x, clipRectArgs.y, clipRectArgs.width, clipRectArgs.height); graphic.partRect = renderer[type](partShapeArgs) .addClass('highcharts-partfill-overlay') .add(graphic) .clip(graphic.partialClipRect); } } // Presentational if (!series.chart.styledMode) { graphic .rect[verb](pointAttr, animation) .shadow(seriesOpts.shadow, null, cutOff); if (partShapeArgs) { // Ensure pfOptions is an object if (!isObject(pfOptions)) { pfOptions = {}; } if (isObject(seriesOpts.partialFill)) { pfOptions = merge(pfOptions, seriesOpts.partialFill); } fill = (pfOptions.fill || color(pointAttr.fill).brighten(-0.3).get() || color(point.color || series.color) .brighten(-0.3).get()); pointAttr.fill = fill; graphic .partRect[pointStateVerb](pointAttr, animation) .shadow(seriesOpts.shadow, null, cutOff); } } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }, /** * @private * @function Highcharts.Series#drawPoints */ drawPoints: function () { var series = this, verb = series.getAnimationVerb(); // Draw the columns series.points.forEach(function (point) { series.drawPoint(point, verb); }); }, /** * Returns "animate", or "attr" if the number of points is above the * animation limit. * * @private * @function Highcharts.Series#getAnimationVerb * * @return {string} */ getAnimationVerb: function () { return (this.chart.pointCount < (this.options.animationLimit || 250) ? 'animate' : 'attr'); } /* // Override to remove stroke from points. For partial fill. pointAttribs: function () { var series = this, retVal = columnType.prototype.pointAttribs .apply(series, arguments); //retVal['stroke-width'] = 0; return retVal; } //*/ /* eslint-enable valid-jsdoc */ }, { /** * The ending X value of the range point. * @name Highcharts.Point#x2 * @type {number|undefined} * @requires modules/xrange */ /** * Extend applyOptions so that `colorByPoint` for x-range means that one * color is applied per Y axis category. * * @private * @function Highcharts.Point#applyOptions * * @return {Highcharts.Series} */ /* eslint-disable valid-jsdoc */ /** * @private */ resolveColor: function () { var series = this.series, colorByPoint; if (series.options.colorByPoint && !this.options.color) { colorByPoint = getColorByCategory(series, this); if (!series.chart.styledMode) { this.color = colorByPoint.color; } if (!this.options.colorIndex) { this.colorIndex = colorByPoint.colorIndex; } } else if (!this.color) { this.color = series.color; } }, /** * Extend init to have y default to 0. * * @private * @function Highcharts.Point#init * * @return {Highcharts.Point} */ init: function () { Point.prototype.init.apply(this, arguments); if (!this.y) { this.y = 0; } return this; }, /** * @private * @function Highcharts.Point#setState */ setState: function () { Point.prototype.setState.apply(this, arguments); this.series.drawPoint(this, this.series.getAnimationVerb()); }, /** * @private * @function Highcharts.Point#getLabelConfig * * @return {Highcharts.PointLabelObject} */ // Add x2 and yCategory to the available properties for tooltip formats getLabelConfig: function () { var point = this, cfg = Point.prototype.getLabelConfig.call(point), yCats = point.series.yAxis.categories; cfg.x2 = point.x2; cfg.yCategory = point.yCategory = yCats && yCats[point.y]; return cfg; }, tooltipDateKeys: ['x', 'x2'], /** * @private * @function Highcharts.Point#isValid * * @return {boolean} */ isValid: function () { return typeof this.x === 'number' && typeof this.x2 === 'number'; } /* eslint-enable valid-jsdoc */ }); /** * Max x2 should be considered in xAxis extremes */ addEvent(Axis, 'afterGetSeriesExtremes', function () { var axis = this, // eslint-disable-line no-invalid-this axisSeries = axis.series, dataMax, modMax; if (axis.isXAxis) { dataMax = pick(axis.dataMax, -Number.MAX_VALUE); axisSeries.forEach(function (series) { if (series.x2Data) { series.x2Data .forEach(function (val) { if (val > dataMax) { dataMax = val; modMax = true; } }); } }); if (modMax) { axis.dataMax = dataMax; } } }); /** * An `xrange` series. If the [type](#series.xrange.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.xrange * @excluding boostThreshold, crisp, cropThreshold, depth, edgeColor, edgeWidth, * findNearestPointBy, getExtremesFromAll, negativeColor, * pointInterval, pointIntervalUnit, pointPlacement, pointRange, * pointStart, softThreshold, stacking, threshold, dataSorting * @product highcharts highstock gantt * @requires modules/xrange * @apioption series.xrange */ /** * An array of data points for the series. For the `xrange` series type, * points can be given in the following ways: * * 1. An array of objects with named values. The objects are point configuration * objects as seen below. * ```js * data: [{ * x: Date.UTC(2017, 0, 1), * x2: Date.UTC(2017, 0, 3), * name: "Test", * y: 0, * color: "#00FF00" * }, { * x: Date.UTC(2017, 0, 4), * x2: Date.UTC(2017, 0, 5), * name: "Deploy", * y: 1, * color: "#FF0000" * }] * ``` * * @sample {highcharts} highcharts/series/data-array-of-objects/ * Config objects * * @declare Highcharts.XrangePointOptionsObject * @type {Array<*>} * @extends series.line.data * @product highcharts highstock gantt * @apioption series.xrange.data */ /** * The starting X value of the range point. * * @sample {highcharts} highcharts/demo/x-range * X-range * * @type {number} * @product highcharts highstock gantt * @apioption series.xrange.data.x */ /** * The ending X value of the range point. * * @sample {highcharts} highcharts/demo/x-range * X-range * * @type {number} * @product highcharts highstock gantt * @apioption series.xrange.data.x2 */ /** * The Y value of the range point. * * @sample {highcharts} highcharts/demo/x-range * X-range * * @type {number} * @product highcharts highstock gantt * @apioption series.xrange.data.y */ /** * A partial fill for each point, typically used to visualize how much of * a task is performed. The partial fill object can be set either on series * or point level. * * @sample {highcharts} highcharts/demo/x-range * X-range with partial fill * * @declare Highcharts.XrangePointPartialFillOptionsObject * @product highcharts highstock gantt * @apioption series.xrange.data.partialFill */ /** * The amount of the X-range point to be filled. Values can be 0-1 and are * converted to percentages in the default data label formatter. * * @type {number} * @product highcharts highstock gantt * @apioption series.xrange.data.partialFill.amount */ /** * The fill color to be used for partial fills. Defaults to a darker shade * of the point color. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highcharts highstock gantt * @apioption series.xrange.data.partialFill.fill */ ''; // adds doclets above to transpiled file
{ "content_hash": "64b17d59ba1584712f16c87a895d08ce", "timestamp": "", "source": "github", "line_count": 670, "max_line_length": 597, "avg_line_length": 34.853731343283584, "alnum_prop": 0.5719424460431655, "repo_name": "cdnjs/cdnjs", "id": "9bf7809be9b51bf390ae5f3e0a2374a995167a2e", "size": "23352", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ajax/libs/highcharts/8.1.0/es-modules/modules/xrange.src.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using Microsoft.AspNet.Identity.EntityFramework; namespace NfxLab.GlimpsePlugins.Test.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection") { } } }
{ "content_hash": "25a2ced8a1b560166bd6f5b34326d408", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 175, "avg_line_length": 31.529411764705884, "alnum_prop": 0.6828358208955224, "repo_name": "NicolasFatoux/GlimpsePlugins", "id": "08e5d9886bfe973800e829f4ad4ea0fc8623d958", "size": "538", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NfxLab.GlimpsePlugins.Test/Models/IdentityModels.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "118" }, { "name": "C#", "bytes": "30096" }, { "name": "CSS", "bytes": "726" }, { "name": "JavaScript", "bytes": "233962" } ], "symlink_target": "" }
''' :codeauthor: :email: `Mike Place <mp@saltstack.com>` ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../') # Import Salt libs from salt import template class TemplateTestCase(TestCase): render_dict = {'jinja': 'fake_jinja_func', 'json': 'fake_json_func', 'mako': 'fake_make_func'} def test_compile_template_bad_type(self): ''' Test to ensure that unsupported types cannot be passed to the template compiler ''' ret = template.compile_template(['1', '2', '3'], None, None) self.assertDictEqual(ret, {}) def test_check_render_pipe_str(self): ''' Check that all renderers specified in the pipe string are available. ''' ret = template.check_render_pipe_str('jinja|json', self.render_dict) self.assertIn(('fake_jinja_func', ''), ret) self.assertIn(('fake_json_func', ''), ret) self.assertNotIn(('OBVIOUSLY_NOT_HERE', ''), ret) if __name__ == '__main__': from integration import run_tests run_tests(TemplateTestCase, needs_daemon=False)
{ "content_hash": "7521216028084b01396eb7fe51c8fd51", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 87, "avg_line_length": 29.547619047619047, "alnum_prop": 0.6301369863013698, "repo_name": "stephane-martin/salt-debian-packaging", "id": "0bb8d05042da2824506b89b8a4f1f223e9e84d96", "size": "1265", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "salt-2016.3.3/tests/unit/template_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13798" }, { "name": "C", "bytes": "986" }, { "name": "Groff", "bytes": "13634346" }, { "name": "HTML", "bytes": "39558" }, { "name": "Makefile", "bytes": "20902" }, { "name": "NSIS", "bytes": "22316" }, { "name": "PowerShell", "bytes": "38719" }, { "name": "Python", "bytes": "40857506" }, { "name": "SaltStack", "bytes": "58278" }, { "name": "Scheme", "bytes": "1790" }, { "name": "Shell", "bytes": "829927" }, { "name": "Tcl", "bytes": "6532" }, { "name": "TeX", "bytes": "11632" } ], "symlink_target": "" }
package org.wso2.carbon.event.input.adaptor.core; import org.apache.log4j.Logger; import org.wso2.carbon.event.statistics.EventStatisticsMonitor; /** * listener class to receive the events from the event proxy */ public abstract class InputEventAdaptorListener { private static final String EVENT_TRACE_LOGGER = "EVENT_TRACE_LOGGER"; private Logger trace = Logger.getLogger(EVENT_TRACE_LOGGER); private Boolean statisticsEnabled; private Boolean traceEnabled; private String eventAdaptorName; private String tracerPrefix = ""; private EventStatisticsMonitor statisticsMonitor; /** * when an event definition is defined, event calls this method with the definition. * * @param object - received event definition */ public abstract void addEventDefinition(Object object); /** * when an event definition is removed event proxy call this method with the definition. * * @param object - received event definition */ public abstract void removeEventDefinition(Object object); /** * when an event happens event proxy call this method with the received event. * * @param object - received event */ public abstract void onEvent(Object object); /** * when an event definition is defined, event calls this method with the definition. * * @param object - received event definition */ public void addEventDefinitionCall(Object object) { if (traceEnabled) { trace.info(tracerPrefix + " Add EventDefinition " + System.getProperty("line.separator") + object); } addEventDefinition(object); } /** * when an event definition is removed event proxy call this method with the definition. * * @param object - received event definition */ public void removeEventDefinitionCall(Object object) { if (traceEnabled) { trace.info(tracerPrefix + " Remove EventDefinition " + System.getProperty("line.separator") + object); } removeEventDefinition(object); } /** * when an event happens event proxy call this method with the received event. * * @param object - received event */ public void onEventCall(Object object) { if (traceEnabled) { trace.info(tracerPrefix + object); } if (statisticsEnabled) { statisticsMonitor.incrementRequest(); } onEvent(object); } public Boolean getStatisticsEnabled() { return statisticsEnabled; } public void setStatisticsEnabled(Boolean statisticsEnabled) { this.statisticsEnabled = statisticsEnabled; } public Boolean getTraceEnabled() { return traceEnabled; } public void setTraceEnabled(Boolean traceEnabled) { this.traceEnabled = traceEnabled; } public String getEventAdaptorName() { return eventAdaptorName; } public void setEventAdaptorName(String eventAdaptorName) { this.eventAdaptorName = eventAdaptorName; } public void setStatisticsMonitor(EventStatisticsMonitor statisticsMonitor) { this.statisticsMonitor = statisticsMonitor; } public EventStatisticsMonitor getStatisticsMonitor() { return statisticsMonitor; } public void setTracerPrefix(String tracerPrefix) { this.tracerPrefix = tracerPrefix; } public String getTracerPrefix() { return tracerPrefix; } }
{ "content_hash": "4199e9fed66663ae79da3d906d38cfce", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 114, "avg_line_length": 27.62204724409449, "alnum_prop": 0.6724629418472063, "repo_name": "lankavitharana/carbon-event-processing", "id": "3788f5f2c21b093680a7a358690e4b3dfb53672b", "size": "4128", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/adaptors/event-input-adaptor/org.wso2.carbon.event.input.adaptor.core/src/main/java/org/wso2/carbon/event/input/adaptor/core/InputEventAdaptorListener.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
from __future__ import absolute_import # local imports from .members import all_current_committee_chairs from .members import all_current_members from .members import all_current_members_by_given_constituency_id from .members import all_current_members_by_given_party_id from .members import all_current_members_by_surname_search from .members import all_current_ministers from .members import all_member_contact_details from .members import all_member_roles from .members import all_members_by_given_date from .members import member_contact_details_by_person_id from .members import member_roles_by_person_id from .questions import question_details from .questions import questions_by_department from .questions import questions_by_member from .questions import questions_by_search_text from .questions import questions_for_oral_answer_answered_in_range from .questions import questions_for_oral_answer_tabled_in_range from .questions import questions_for_written_answer_answered_in_range from .questions import questions_for_written_answer_tabled_in_range from .questions import written_answer_html from .questions import written_answer_open_xml from .organisations import all_party_groups_list_current from .organisations import committees_list_current_ad_hoc from .organisations import committees_list_current_other from .organisations import committees_list_current_standing from .organisations import committees_list_current_statutory from .organisations import department_list_current from .organisations import organisation_list_current from .organisations import parties_list_current # all of the following objects will be imported if the caller does # `from niaopendata import *` (don't) __all__ = [ # Members Web Service 'all_current_committee_chairs', 'all_current_members', 'all_current_members_by_given_constituency_id', 'all_current_members_by_given_party_id', 'all_current_members_by_surname_search', 'all_current_ministers', 'all_member_contact_details', 'all_member_roles', 'all_members_by_given_date', 'member_contact_details_by_person_id', 'member_roles_by_person_id', # Questions Web Service 'question_details', 'questions_by_department', 'questions_by_member', 'questions_by_search_text', 'questions_for_oral_answer_answered_in_range', 'questions_for_oral_answer_tabled_in_range', 'questions_for_written_answer_answered_in_range', 'questions_for_written_answer_tabled_in_range', 'written_answer_html', 'written_answer_open_xml', # Organisations Web Service 'all_party_groups_list_current', 'committees_list_current_ad_hoc', 'committees_list_current_other', 'committees_list_current_standing', 'committees_list_current_statutory', 'department_list_current', 'organisation_list_current', 'parties_list_current', ]
{ "content_hash": "7038fc31a8d35d7bc8091f7a94b93fca", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 69, "avg_line_length": 39.28767123287671, "alnum_prop": 0.7681311018131102, "repo_name": "paddycarey/niaopendata", "id": "68d7f4fe737923224419a7ab66928ac5a4b239a9", "size": "2910", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "niaopendata/__init__.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "33259" } ], "symlink_target": "" }
__all__ = [ 'ZerigoDNSDriver' ] import copy import base64 import httplib from xml.etree import ElementTree as ET from libcloud.utils import fixxpath, findtext, findattr, findall from libcloud.utils import merge_valid_keys, get_new_obj from libcloud.common.base import XmlResponse, ConnectionUserAndKey from libcloud.common.types import InvalidCredsError, LibcloudError from libcloud.common.types import MalformedResponseError, LazyList from libcloud.dns.types import Provider, RecordType from libcloud.dns.types import ZoneDoesNotExistError, RecordDoesNotExistError from libcloud.dns.base import DNSDriver, Zone, Record API_HOST = 'ns.zerigo.com' API_VERSION = '1.1' API_ROOT = '/api/%s/' % (API_VERSION) VALID_ZONE_EXTRA_PARAMS = ['notes', 'tag-list', 'ns1', 'slave-nameservers'] VALID_RECORD_EXTRA_PARAMS = ['notes', 'ttl', 'priority'] # Number of items per page (maximum limit is 1000) ITEMS_PER_PAGE = 100 RECORD_TYPE_MAP = { RecordType.A: 'A', RecordType.AAAA: 'AAAA', RecordType.CNAME: 'CNAME', RecordType.MX: 'MX', RecordType.REDIRECT: 'REDIRECT', RecordType.TXT: 'TXT', RecordType.SRV: 'SRV', RecordType.NAPTR: 'NAPTR', RecordType.NS: 'NS', RecordType.PTR: 'PTR', RecordType.SPF: 'SPF', } class ZerigoError(LibcloudError): def __init__(self, code, errors): self.code = code self.errors = errors or [] def __str__(self): return 'Errors: %s' % (', '.join(self.errors)) def __repr__(self): return ('<ZerigoError response code=%s, errors count=%s>' % (self.code, len(self.errors))) class ZerigoDNSResponse(XmlResponse): def success(self): return self.status in [httplib.OK, httplib.CREATED, httplib.ACCEPTED] def parse_error(self): status = int(self.status) if status == 401: if not self.body: raise InvalidCredsError(str(self.status) + ': ' + self.error) else: raise InvalidCredsError(self.body) elif status == 404: context = self.connection.context if context['resource'] == 'zone': raise ZoneDoesNotExistError(value='', driver=self, zone_id=context['id']) elif context['resource'] == 'record': raise RecordDoesNotExistError(value='', driver=self, record_id=context['id']) elif status != 503: try: body = ET.XML(self.body) except: raise MalformedResponseError('Failed to parse XML', body=self.body) errors = [] for error in findall(element=body, xpath='error'): errors.append(error.text) raise ZerigoError(code=status, errors=errors) return self.body class ZerigoDNSConnection(ConnectionUserAndKey): host = API_HOST secure = True responseCls = ZerigoDNSResponse def add_default_headers(self, headers): auth_b64 = base64.b64encode('%s:%s' % (self.user_id, self.key)) headers['Authorization'] = 'Basic %s' % (auth_b64) return headers def request(self, action, params=None, data='', headers=None, method='GET'): if not headers: headers = {} if not params: params = {} if method in ("POST", "PUT"): headers = {'Content-Type': 'application/xml; charset=UTF-8'} return super(ZerigoDNSConnection, self).request(action=action, params=params, data=data, method=method, headers=headers) class ZerigoDNSDriver(DNSDriver): type = Provider.ZERIGO name = 'Zerigo DNS' connectionCls = ZerigoDNSConnection def list_record_types(self): return RECORD_TYPE_MAP.keys() def list_zones(self): value_dict = {'type': 'zones'} return LazyList(get_more=self._get_more, value_dict=value_dict) def list_records(self, zone): value_dict = {'type': 'records', 'zone': zone} return LazyList(get_more=self._get_more, value_dict=value_dict) def get_zone(self, zone_id): path = API_ROOT + 'zones/%s.xml' % (zone_id) self.connection.set_context({'resource': 'zone', 'id': zone_id}) data = self.connection.request(path).object zone = self._to_zone(elem=data) return zone def get_record(self, zone_id, record_id): zone = self.get_zone(zone_id=zone_id) self.connection.set_context({'resource': 'record', 'id': record_id}) path = API_ROOT + 'hosts/%s.xml' % (record_id) data = self.connection.request(path).object record = self._to_record(elem=data, zone=zone) return record def create_zone(self, domain, type='master', ttl=None, extra=None): """ Create a new zone. Provider API docs: https://www.zerigo.com/docs/apis/dns/1.1/zones/create """ path = API_ROOT + 'zones.xml' zone_elem = self._to_zone_elem(domain=domain, type=type, ttl=ttl, extra=extra) data = self.connection.request(action=path, data=ET.tostring(zone_elem), method='POST').object zone = self._to_zone(elem=data) return zone def update_zone(self, zone, domain=None, type=None, ttl=None, extra=None): """ Update an existing zone. Provider API docs: https://www.zerigo.com/docs/apis/dns/1.1/zones/update """ if domain: raise LibcloudError('Domain cannot be changed', driver=self) path = API_ROOT + 'zones/%s.xml' % (zone.id) zone_elem = self._to_zone_elem(domain=domain, type=type, ttl=ttl, extra=extra) response = self.connection.request(action=path, data=ET.tostring(zone_elem), method='PUT') assert response.status == httplib.OK merged = merge_valid_keys(params=copy.deepcopy(zone.extra), valid_keys=VALID_ZONE_EXTRA_PARAMS, extra=extra) updated_zone = get_new_obj(obj=zone, klass=Zone, attributes={'type': type, 'ttl': ttl, 'extra': merged}) return updated_zone def create_record(self, name, zone, type, data, extra=None): """ Create a new record. Provider API docs: https://www.zerigo.com/docs/apis/dns/1.1/hosts/create """ path = API_ROOT + 'zones/%s/hosts.xml' % (zone.id) record_elem = self._to_record_elem(name=name, type=type, data=data, extra=extra) response = self.connection.request(action=path, data=ET.tostring(record_elem), method='POST') assert response.status == httplib.CREATED record = self._to_record(elem=response.object, zone=zone) return record def update_record(self, record, name=None, type=None, data=None, extra=None): path = API_ROOT + 'hosts/%s.xml' % (record.id) record_elem = self._to_record_elem(name=name, type=type, data=data, extra=extra) response = self.connection.request(action=path, data=ET.tostring(record_elem), method='PUT') assert response.status == httplib.OK merged = merge_valid_keys(params=copy.deepcopy(record.extra), valid_keys=VALID_RECORD_EXTRA_PARAMS, extra=extra) updated_record = get_new_obj(obj=record, klass=Record, attributes={'type': type, 'data': data, 'extra': merged}) return updated_record def delete_zone(self, zone): path = API_ROOT + 'zones/%s.xml' % (zone.id) self.connection.set_context({'resource': 'zone', 'id': zone.id}) response = self.connection.request(action=path, method='DELETE') return response.status == httplib.OK def delete_record(self, record): path = API_ROOT + 'hosts/%s.xml' % (record.id) self.connection.set_context({'resource': 'record', 'id': record.id}) response = self.connection.request(action=path, method='DELETE') return response.status == httplib.OK def ex_get_zone_by_domain(self, domain): """ Retrieve a zone object by the domain name. """ path = API_ROOT + 'zones/%s.xml' % (domain) self.connection.set_context({'resource': 'zone', 'id': domain}) data = self.connection.request(path).object zone = self._to_zone(elem=data) return zone def ex_force_slave_axfr(self, zone): """ Force a zone transfer. """ path = API_ROOT + 'zones/%s/force_slave_axfr.xml' % (zone.id) self.connection.set_context({'resource': 'zone', 'id': zone.id}) response = self.connection.request(path, method='POST') assert response.status == httplib.ACCEPTED return zone def _to_zone_elem(self, domain=None, type=None, ttl=None, extra=None): zone_elem = ET.Element('zone', {}) if domain: domain_elem = ET.SubElement(zone_elem, 'domain') domain_elem.text = domain if type: ns_type_elem = ET.SubElement(zone_elem, 'ns-type') if type == 'master': ns_type_elem.text = 'pri_sec' elif type == 'slave': if not extra or 'ns1' not in extra: raise LibcloudError('ns1 extra attribute is required ' + 'when zone type is slave', driver=self) ns_type_elem.text = 'sec' ns1_elem = ET.SubElement(zone_elem, 'ns1') ns1_elem.text = extra['ns1'] elif type == 'std_master': # TODO: Each driver should provide supported zone types # Slave name servers are elsewhere if not extra or 'slave-nameservers' not in extra: raise LibcloudError('slave-nameservers extra ' + 'attribute is required whenzone ' + 'type is std_master', driver=self) ns_type_elem.text = 'pri' slave_nameservers_elem = ET.SubElement(zone_elem, 'slave-nameservers') slave_nameservers_elem.text = extra['slave-nameservers'] if ttl: default_ttl_elem = ET.SubElement(zone_elem, 'default-ttl') default_ttl_elem.text = str(ttl) if extra and 'tag-list' in extra: tags = extra['tag-list'] tags_elem = ET.SubElement(zone_elem, 'tag-list') tags_elem.text = ' '.join(tags) return zone_elem def _to_record_elem(self, name=None, type=None, data=None, extra=None): record_elem = ET.Element('host', {}) if name: name_elem = ET.SubElement(record_elem, 'hostname') name_elem.text = name if type: type_elem = ET.SubElement(record_elem, 'host-type') type_elem.text = RECORD_TYPE_MAP[type] if data: data_elem = ET.SubElement(record_elem, 'data') data_elem.text = data if extra: if 'ttl' in extra: ttl_elem = ET.SubElement(record_elem, 'ttl', {'type': 'integer'}) ttl_elem.text = str(extra['ttl']) if 'priority' in extra: # Only MX and SRV records support priority priority_elem = ET.SubElement(record_elem, 'priority', {'type': 'integer'}) priority_elem.text = str(extra['priority']) if 'notes' in extra: notes_elem = ET.SubElement(record_elem, 'notes') notes_elem.text = extra['notes'] return record_elem def _to_zones(self, elem): zones = [] for item in findall(element=elem, xpath='zone'): zone = self._to_zone(elem=item) zones.append(zone) return zones def _to_zone(self, elem): id = findtext(element=elem, xpath='id') domain = findtext(element=elem, xpath='domain') type = findtext(element=elem, xpath='ns-type') type = 'master' if type.find('pri') == 0 else 'slave' ttl = findtext(element=elem, xpath='default-ttl') hostmaster = findtext(element=elem, xpath='hostmaster') custom_ns = findtext(element=elem, xpath='custom-ns') custom_nameservers = findtext(element=elem, xpath='custom-nameservers') notes = findtext(element=elem, xpath='notes') nx_ttl = findtext(element=elem, xpath='nx-ttl') slave_nameservers = findtext(element=elem, xpath='slave-nameservers') tags = findtext(element=elem, xpath='tag-list') tags = tags.split(' ') if tags else [] extra = {'hostmaster': hostmaster, 'custom-ns': custom_ns, 'custom-nameservers': custom_nameservers, 'notes': notes, 'nx-ttl': nx_ttl, 'slave-nameservers': slave_nameservers, 'tags': tags} zone = Zone(id=str(id), domain=domain, type=type, ttl=int(ttl), driver=self, extra=extra) return zone def _to_records(self, elem, zone): records = [] for item in findall(element=elem, xpath='host'): record = self._to_record(elem=item, zone=zone) records.append(record) return records def _to_record(self, elem, zone): id = findtext(element=elem, xpath='id') name = findtext(element=elem, xpath='hostname') type = findtext(element=elem, xpath='host-type') type = self._string_to_record_type(type) data = findtext(element=elem, xpath='data') notes = findtext(element=elem, xpath='notes') state = findtext(element=elem, xpath='state') fqdn = findtext(element=elem, xpath='fqdn') priority = findtext(element=elem, xpath='priority') extra = {'notes': notes, 'state': state, 'fqdn': fqdn, 'priority': priority} record = Record(id=id, name=name, type=type, data=data, zone=zone, driver=self, extra=extra) return record def _get_more(self, last_key, value_dict): # Note: last_key in this case really is a "last_page". # TODO: Update base driver and change last_key to something more # generic - e.g. marker params = {} params['per_page'] = ITEMS_PER_PAGE params['page'] = last_key + 1 if last_key else 1 transform_func_kwargs = {} if value_dict['type'] == 'zones': path = API_ROOT + 'zones.xml' response = self.connection.request(path) transform_func = self._to_zones elif value_dict['type'] == 'records': zone = value_dict['zone'] path = API_ROOT + 'zones/%s/hosts.xml' % (zone.id) self.connection.set_context({'resource': 'zone', 'id': zone.id}) response = self.connection.request(path, params=params) transform_func = self._to_records transform_func_kwargs['zone'] = value_dict['zone'] exhausted = False result_count = int(response.headers.get('x-query-count', 0)) transform_func_kwargs['elem'] = response.object if (params['page'] * ITEMS_PER_PAGE) >= result_count: exhausted = True if response.status == httplib.OK: items = transform_func(**transform_func_kwargs) return items, params['page'], exhausted else: return [], None, True
{ "content_hash": "954bdd41ecefc44c4fe87be2839b5ac6", "timestamp": "", "source": "github", "line_count": 436, "max_line_length": 79, "avg_line_length": 38.440366972477065, "alnum_prop": 0.5378281622911695, "repo_name": "Keisuke69/libcloud", "id": "c0dcd762f221d8a376790aeb48a8876f73cec7c1", "size": "17542", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libcloud/dns/drivers/zerigo.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "1133783" }, { "name": "Shell", "bytes": "5637" } ], "symlink_target": "" }
import java.util.Arrays; import java.util.Scanner; public class SequenceInMatrix { public static String[][] matrix(Scanner scanner){ String[] input = scanner.nextLine().split(" "); int rows = Integer.parseInt(input[0]); int cols = Integer.parseInt(input[1]); String[][] matrix = new String[rows][cols]; for (int row = 0; row < matrix.length; row++) { String[] line = scanner.nextLine().split(" "); for (int col = 0; col < matrix[row].length; col++) { matrix[row][col] = line[col]; } } return matrix; } public static boolean isEqual(String currentWord, String word) { char[] currWord = currentWord.toCharArray(); if(word == null){ word = " "; } char[] compWord = word.toCharArray(); boolean equal = false; for (char letter1 : currWord) { for (char letter2 : compWord) { if ((int) letter1 == (int) letter2) { equal = true; } else { equal = false; return false; } } } if (equal == true) { return true; } else { return false; } } public static int calculateOccurrence(String currentWord, String[] row){ int occurences = 0; for(int index = 0; index < row.length;index++){ if(isEqual(currentWord, row[index])){ occurences++; } else{ break; } } return occurences; } public static int calculateMaxOccurrence(int rowOccurrences, int colOccurrences, int leftDiagonalOccurrences) { int max = Math.max(rowOccurrences, colOccurrences); if(leftDiagonalOccurrences >= max){ max = leftDiagonalOccurrences; } return max; } public static void main(String[] args) { String[][] matrix = matrix(new Scanner(System.in)); String resultWord = ""; int resultWordOccurrences = 0; for(int row = 0; row < matrix.length;row++){ System.out.print("ITERATION: "); System.out.println(row); String rowMostFrequentWord = ""; int rowWordOccurrences = 0; for(int col = 0; col < matrix[row].length;col++){ try { String currentWord = matrix[row][col]; String[] rowWords = new String[matrix.length - row]; int j = 0; for (int index = row; index < matrix.length; index++) { rowWords[j] = matrix[index][col]; j++; } int rowOccurrences = calculateOccurrence(currentWord, rowWords); String[] colWords = new String[matrix[row].length - col]; int p = 0; for (int index = col; index < matrix[row].length; index++) { colWords[p] = matrix[row][index]; p++; } int colOccurrences = calculateOccurrence(currentWord, colWords); String[] leftDiagonalWords = new String[matrix.length - col]; int i = 0; int columns = col; int addition = 0; for (int index = row; index < matrix.length; index++, columns++) { if (columns >= matrix[row].length) { break; } if(matrix[index][columns] == null){ matrix[index][columns] = " "; } leftDiagonalWords[i] = matrix[index][columns]; i++; } int leftDiagonalOccurrences = calculateOccurrence(currentWord, leftDiagonalWords); int maxColOccurrences = calculateMaxOccurrence(rowOccurrences, colOccurrences, leftDiagonalOccurrences); if(maxColOccurrences > rowWordOccurrences){ rowWordOccurrences = maxColOccurrences; rowMostFrequentWord = currentWord; } System.out.print(currentWord + "=> "); System.out.printf("Row: %1$d; Col: %2$d; Left-Diagonal: %3$d", rowOccurrences, colOccurrences, leftDiagonalOccurrences); System.out.println(); } catch (ArrayIndexOutOfBoundsException ex){ System.out.println(ex.getCause()); } } System.out.println("Most frequent word: " + rowMostFrequentWord + " occurred " + rowWordOccurrences + " times!"); if(rowWordOccurrences > resultWordOccurrences){ resultWord = rowMostFrequentWord; resultWordOccurrences = rowWordOccurrences; } } System.out.println("MOST FREQUENT WORD: " + resultWord + " OCCURRED: " + resultWordOccurrences + " TIMES!"); } }
{ "content_hash": "50dc093a9a43b72fe1d74883ea6952b1", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 125, "avg_line_length": 34.36601307189542, "alnum_prop": 0.48649676683149484, "repo_name": "StoyanVitanov/SoftwareUniversity", "id": "11b8403665401d130b56ae3f32a49fe3fec3b695", "size": "5258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Java Fundamentals/Java Advanced/Matrix/Exercise/SequenceInMatrix.java", "mode": "33261", "license": "mit", "language": [ { "name": "C#", "bytes": "520639" }, { "name": "CSS", "bytes": "638" }, { "name": "HTML", "bytes": "8027" }, { "name": "Java", "bytes": "705608" }, { "name": "JavaScript", "bytes": "9369" }, { "name": "PHP", "bytes": "10137" }, { "name": "PLSQL", "bytes": "449" }, { "name": "PLpgSQL", "bytes": "1478" }, { "name": "SQLPL", "bytes": "8271" } ], "symlink_target": "" }
package net.ymate.platform.cache; import net.ymate.platform.commons.serialize.ISerializer; import net.ymate.platform.core.beans.annotation.Ignored; import java.io.Serializable; import java.lang.reflect.Method; /** * 缓存Key生成器接口 * * @param <T> 键类型 * @author 刘镇 (suninformation@163.com) on 15/11/3 下午1:40 */ @Ignored public interface ICacheKeyGenerator<T extends Serializable> { /** * 初始化 * * @param owner 缓存管理器实例 * @param serializer 序列化接口实现 */ void initialize(ICaches owner, ISerializer serializer); /** * 生成缓存Key值 * * @param method 目标方法对象 * @param params 目标方法参数集合 * @return 返回生成的Key值 * @throws Exception 可能产生的异常 */ T generateKey(Method method, Object[] params) throws Exception; }
{ "content_hash": "9dda7c66cf24abda7f8bbd6f2162a497", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 67, "avg_line_length": 21.444444444444443, "alnum_prop": 0.6683937823834197, "repo_name": "suninformation/ymate-platform-v2", "id": "111e0e23672e1f73b3b8be9f27350e8c2816212c", "size": "1518", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ymate-platform-cache/src/main/java/net/ymate/platform/cache/ICacheKeyGenerator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "28968" }, { "name": "Java", "bytes": "3578119" }, { "name": "JavaScript", "bytes": "15986" } ], "symlink_target": "" }
package com.oprisnik.semdroid.feature.instance.method; import com.oprisnik.semdroid.app.CodeElement; import com.oprisnik.semdroid.app.DexMethod; import com.oprisnik.semdroid.app.LocalVariable; import com.oprisnik.semdroid.app.MethodCall; import com.oprisnik.semdroid.app.Opcode; import com.oprisnik.semdroid.app.manifest.AndroidReceiver; import com.oprisnik.semdroid.app.manifest.IntentFilter; import com.oprisnik.semdroid.feature.instance.MethodInstanceGenerator; import com.oprisnik.semdroid.permissions.PermissionMap; import com.oprisnik.semdroid.utils.DexUtils; import com.oprisnik.semdroid.utils.Log; import com.oprisnik.semdroid.utils.SparseIntHistogram; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import at.tuflowgraphy.semantic.base.domain.data.InstanceDataElement; /** * V1 method instance generator. Uses thresholds derived from statistics and * adds permissions, intent actions, local variables, opcode histogram and * invoked methods. * <p/> * . */ public class V1MIG extends MethodInstanceGenerator { private static final String TAG = "V1MIG"; @Override protected void getMethodInstance(DexMethod method, InstanceDataElement results) { int appcount = getStatistics().getAppCount(); int opcodeThresholdMin = appcount / 2; int methodCallClassNameThreshold = appcount / 2; int localVarThreshold = appcount / 2; Log.v(TAG, "------------------------------"); Log.v(TAG, "Method: " + method.toString()); Set<String> intentFilterAction = new HashSet<String>(); for (String permission : method.getPermissions()) { if (PermissionMap.SEE_INTENT_KEY.equals(permission)) { List<AndroidReceiver> receivers = method.getApp().getManifest() .getReceivers(); // Log.v(TAG, "Looking for Receiver: " // + method.getDexClass().getFullName()); for (AndroidReceiver r : receivers) { // Log.v(TAG, "Receiver defined: " + // r.getFullyQualifiedName()); if (r.getFullyQualifiedName().equals( method.getDexClass().getFullName())) { // Log.v(TAG, // "Receiver Found! Checking Intent filter..."); List<IntentFilter> inf = r.getIntentFilters(); for (IntentFilter f : inf) { // Log.v(TAG, "IntentFilter: " + f.getAction()); intentFilterAction.add(f.getAction()); } } } } else { results.addValue(getSymbolicFeatureDataElement( "usesPermission", permission)); Log.v(TAG, "usesPermission: " + permission); } } for (String ifa : intentFilterAction) { results.addValue(getSymbolicFeatureDataElement( "usesIntentFilterAction", ifa)); Log.v(TAG, "usesIntentFilterAction: " + ifa); } SparseIntHistogram opcodeHisto = new SparseIntHistogram(); Set<String> localVarSet = new HashSet<String>(); Set<String> invokesSet = new HashSet<String>(); for (CodeElement e : method.getCode()) { if (e instanceof Opcode) { Opcode op = (Opcode) e; String grouped = getOpcodeGroupName(op); if (grouped != null && getStatistics().getOpcodeCount(grouped) >= opcodeThresholdMin) { opcodeHisto.increase(getOpcodeGroup(op)); } } else if (e instanceof MethodCall) { MethodCall mc = (MethodCall) e; if (mc.getDexMethod() == null) { // API call // we use class names only: String classname = mc.getClassName(); if (classname != null && classname.startsWith("android")) { if (getStatistics().getMethodCallClassCount(classname) >= methodCallClassNameThreshold) { invokesSet.add(classname); } } } } else if (e instanceof LocalVariable) { LocalVariable l = (LocalVariable) e; String type = l.getType(); if (type != null && (DexUtils.isBasicDataType(type) || DexUtils .dataTypeStartsWith(type, "android"))) { if (getStatistics().getLocalVarTypeCount(type) >= localVarThreshold) localVarSet.add(type); } } else { Log.e(TAG, "Unknown type: " + e.getName()); } } double[] allOpGroupHisto = getNormedOpcodeArray(opcodeHisto); results.addValue(getDistanceBasedFeatureDataElement("opcodes", allOpGroupHisto)); Log.v(TAG, "opcode histo: " + Arrays.toString(allOpGroupHisto)); for (String classname : invokesSet) { results.addValue(getSymbolicFeatureDataElement("invokes", classname)); Log.v(TAG, "invokes: " + classname); } for (String type : localVarSet) { results.addValue(getSymbolicFeatureDataElement("localVar", type)); Log.v(TAG, "LocalVar: " + type); } Log.v(TAG, "------------------------------"); } }
{ "content_hash": "0051af1d2010af54c3cdabcf4085a80f", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 113, "avg_line_length": 40.62676056338028, "alnum_prop": 0.5453284798058589, "repo_name": "oprisnik/semdroid", "id": "dfb241333ef262fd07ca6f2f20601b70ea0e1b39", "size": "6383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "semdroid-plugin-spa/src/main/java/com/oprisnik/semdroid/feature/instance/method/V1MIG.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11264" }, { "name": "Java", "bytes": "969252" }, { "name": "JavaScript", "bytes": "2576" }, { "name": "Shell", "bytes": "155" }, { "name": "XSLT", "bytes": "17601" } ], "symlink_target": "" }
package com.google.gwt.dev.jjs.impl; import com.google.gwt.core.ext.linker.StatementRanges; import com.google.gwt.core.ext.soyc.Range; import com.google.gwt.dev.jjs.SourceInfo; import com.google.gwt.dev.util.editdistance.GeneralEditDistance; import com.google.gwt.dev.util.editdistance.GeneralEditDistances; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.regex.Pattern; /** * Re-orders function declarations according to a given metric and clustering * algorithm in order to boost gzip/deflation compression efficiency. This * version uses the edit-distance algorithm as a metric, and a semi-greedy * strategy for grouping functions together. */ public class JsFunctionClusterer extends JsAbstractTextTransformer { /** * Used by isFunctionDeclaration to check a statement is a function * declaration or not. This should match standard declarations, such as * "function a() { ... }" and "jslink.a=function() { ... }". The latter form * is typically emitted by the cross-site linker. */ private static final Pattern functionDeclarationPattern = Pattern .compile("function |[a-zA-Z][.$_a-zA-Z0-9]*=function"); /** * Functions which have an edit-distance greater than this limit are * considered equally different. */ private static final int MAX_DISTANCE_LIMIT = 100; /** * Maximum number of functions to search for minimal edit-distance before * giving up. */ private static final int SEARCH_LIMIT = 10; /** * Tells whether a statement is a function declaration or not. */ private static boolean isFunctionDeclaration(String code) { return functionDeclarationPattern.matcher(code).lookingAt(); } /** * Number of function declarations found. */ private int numFunctions; /** * The statement indices after clustering. The element at index j represents * the index of the statement in the original code that is moved to index j * in the new code after clustering. */ private int[] reorderedIndices; public JsFunctionClusterer(JsAbstractTextTransformer xformer) { super(xformer); } public JsFunctionClusterer(String js, StatementRanges statementRanges, Map<Range, SourceInfo> sourceInfoMap) { super(js, statementRanges, sourceInfoMap); } @Override public void exec() { LinkedList<Integer> functionIndices = new LinkedList<Integer>(); // gather up all of the indices of function decl statements for (int i = 0; i < statementRanges.numStatements(); i++) { String code = getJsForRange(i); if (isFunctionDeclaration(code)) { functionIndices.add(i); } } numFunctions = functionIndices.size(); if (functionIndices.size() < 2) { // No need to sort 0 or 1 functions. return; } // sort the indices according to size of statement range Collections.sort(functionIndices, new Comparator<Integer>() { public int compare(Integer index1, Integer index2) { return stmtSize(index1) - (stmtSize(index2)); } }); // used to hold the new output order int[] clusteredIndices = new int[functionIndices.size()]; int currentFunction = 0; // remove the first function and stick it in the output array clusteredIndices[currentFunction] = functionIndices.get(0); functionIndices.remove(0); while (!functionIndices.isEmpty()) { // get the last outputted function to match against String currentCode = getJsForRange(clusteredIndices[currentFunction]); final GeneralEditDistance editDistance = GeneralEditDistances.getLevenshteinDistance(currentCode); int bestIndex = 0; int bestFunction = functionIndices.getFirst(); int bestDistance = MAX_DISTANCE_LIMIT; int count = 0; for (int functionIndex : functionIndices) { if (count >= SEARCH_LIMIT) { break; } String testCode = getJsForRange(functionIndex); int dist = editDistance.getDistance(testCode, bestDistance); if (dist < bestDistance) { bestDistance = dist; bestIndex = count; bestFunction = functionIndex; } count++; } // output the best match and remove it from worklist of functions currentFunction++; clusteredIndices[currentFunction] = bestFunction; functionIndices.remove(bestIndex); } reorderedIndices = Arrays.copyOf(clusteredIndices, statementRanges.numStatements()); recomputeJsAndStatementRanges(clusteredIndices); } /** * Returns the array of reordered statement indices after clustering. * @return The array of indices, where the element at index j represents * the index of the statement in the original code that is moved to index j * in the new code after clustering. */ public int[] getReorderedIndices() { return reorderedIndices; } @Override protected void endStatements(StringBuilder newJs, ArrayList<Integer> starts, ArrayList<Integer> ends) { int j = numFunctions; // Then output everything else that is not a function. for (int i = 0; i < statementRanges.numStatements(); i++) { String code = getJsForRange(i); if (!isFunctionDeclaration(code)) { addStatement(j, code, newJs, starts, ends); reorderedIndices[j] = i; j++; } } super.endStatements(newJs, starts, ends); } /** * Fixes the index ranges of individual expressions in the generated * JS after function clustering has reordered statements. Loops over * each expression, determines which statement it falls in, and shifts * the indices according to where that statement moved. */ @Override protected void updateSourceInfoMap() { if (sourceInfoMap != null) { // create mapping of statement ranges Map<Range, Range> statementShifts = new HashMap<Range, Range>(); for (int j = 0; j < statementRanges.numStatements(); j++) { int permutedStart = statementRanges.start(j); int permutedEnd = statementRanges.end(j); int originalStart = originalStatementRanges.start(reorderedIndices[j]); int originalEnd = originalStatementRanges.end(reorderedIndices[j]); statementShifts.put(new Range(originalStart, originalEnd), new Range(permutedStart, permutedEnd)); } Range[] oldStatementRanges = statementShifts.keySet().toArray(new Range[0]); Arrays.sort(oldStatementRanges, Range.SOURCE_ORDER_COMPARATOR); Range[] oldExpressionRanges = sourceInfoMap.keySet().toArray(new Range[0]); Arrays.sort(oldExpressionRanges, Range.SOURCE_ORDER_COMPARATOR); // iterate over expression ranges and shift Map<Range, SourceInfo> updatedInfoMap = new HashMap<Range, SourceInfo>(); Range entireProgram = new Range(0, oldStatementRanges[oldStatementRanges.length - 1].getEnd()); for (int i = 0, j = 0; j < oldExpressionRanges.length; j++) { Range oldExpression = oldExpressionRanges[j]; if (oldExpression.equals(entireProgram)) { updatedInfoMap.put(oldExpression, sourceInfoMap.get(oldExpression)); continue; } if (!oldStatementRanges[i].contains(oldExpressionRanges[j])) { // expression should fall in the next statement i++; assert oldStatementRanges[i].contains(oldExpressionRanges[j]); } Range oldStatement = oldStatementRanges[i]; Range newStatement = statementShifts.get(oldStatement); int shift = newStatement.getStart() - oldStatement.getStart(); Range oldExpressionRange = oldExpressionRanges[j]; Range newExpressionRange = new Range(oldExpressionRange.getStart() + shift, oldExpressionRange.getEnd() + shift); updatedInfoMap.put(newExpressionRange, sourceInfoMap.get(oldExpressionRange)); } sourceInfoMap = updatedInfoMap; } } private int stmtSize(int index1) { return statementRanges.end(index1) - statementRanges.start(index1); } }
{ "content_hash": "e084d6b1fb054995f861d3cb436c3a79", "timestamp": "", "source": "github", "line_count": 230, "max_line_length": 88, "avg_line_length": 35.88260869565217, "alnum_prop": 0.6871440688234581, "repo_name": "syntelos/gwtcc", "id": "4e61d6e517fb722abee581a397077e5b9880b066", "size": "8846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/google/gwt/dev/jjs/impl/JsFunctionClusterer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "9692033" }, { "name": "Shell", "bytes": "9417" } ], "symlink_target": "" }
package co.mewf.minirs.internal.javax.ws.rs.ext; import co.mewf.minirs.rs.core.Response; /** * Contract for a provider that maps Java exceptions to {@link co.mewf.minirs.rs.core.ws.rs.core.Response}. * <p> * Providers implementing {@code ExceptionMapper} contract must be either programmatically * registered in a JAX-RS runtime or must be annotated with * {@link javax.ws.rs.ext.Provider &#64;Provider} annotation to be automatically discovered * by the JAX-RS runtime during a provider scanning phase. * </p> * * @param <E> exception type supported by the provider. * @author Paul Sandoz * @author Marc Hadley * @see Provider * @see co.mewf.minirs.rs.core.ws.rs.core.Response * @since 1.0 */ public interface ExceptionMapper<E extends Throwable> { /** * Map an exception to a {@link co.mewf.minirs.rs.core.ws.rs.core.Response}. Returning * {@code null} results in a {@link co.mewf.minirs.rs.core.ws.rs.core.Response.Status#NO_CONTENT} * response. Throwing a runtime exception results in a * {@link co.mewf.minirs.rs.core.ws.rs.core.Response.Status#INTERNAL_SERVER_ERROR} response. * * @param exception the exception to map to a response. * @return a response mapped from the supplied exception. */ Response toResponse(E exception); }
{ "content_hash": "e883a9fc79a52b35e0d5f64bd55f400e", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 107, "avg_line_length": 38.3235294117647, "alnum_prop": 0.7152724481964697, "repo_name": "mewf/minirs-core", "id": "8308928a5aab9b8cfdf391313ddbcb69c6a293f5", "size": "3282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/co/mewf/minirs/internal/javax/ws/rs/ext/ExceptionMapper.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "885851" } ], "symlink_target": "" }
CREATE TABLE hobbies_r ( name text, person text ); CREATE TABLE equipment_r ( name text, hobby text ); CREATE TABLE onek ( unique1 int4, unique2 int4, two int4, four int4, ten int4, twenty int4, hundred int4, thousand int4, twothousand int4, fivethous int4, tenthous int4, odd int4, even int4, stringu1 name, stringu2 name, string4 name ); CREATE TABLE tenk1 ( unique1 int4, unique2 int4, two int4, four int4, ten int4, twenty int4, hundred int4, thousand int4, twothousand int4, fivethous int4, tenthous int4, odd int4, even int4, stringu1 name, stringu2 name, string4 name ) WITH OIDS; CREATE TABLE tenk2 ( unique1 int4, unique2 int4, two int4, four int4, ten int4, twenty int4, hundred int4, thousand int4, twothousand int4, fivethous int4, tenthous int4, odd int4, even int4, stringu1 name, stringu2 name, string4 name ); CREATE TABLE person ( name text, age int4, location point ); CREATE TABLE emp ( salary int4, manager name ) INHERITS (person) WITH OIDS; CREATE TABLE student ( gpa float8 ) INHERITS (person); CREATE TABLE stud_emp ( percent int4 ) INHERITS (emp, student); CREATE TABLE city ( name name, location box, budget city_budget ); CREATE TABLE dept ( dname name, mgrname text ); CREATE TABLE slow_emp4000 ( home_base box ); CREATE TABLE fast_emp4000 ( home_base box ); CREATE TABLE road ( name text, thepath path ); CREATE TABLE ihighway () INHERITS (road); CREATE TABLE shighway ( surface text ) INHERITS (road); CREATE TABLE real_city ( pop int4, cname text, outline path ); -- -- test the "star" operators a bit more thoroughly -- this time, -- throw in lots of NULL fields... -- -- a is the type root -- b and c inherit from a (one-level single inheritance) -- d inherits from b and c (two-level multiple inheritance) -- e inherits from c (two-level single inheritance) -- f inherits from e (three-level single inheritance) -- CREATE TABLE a_star ( class char, a int4 ); CREATE TABLE b_star ( b text ) INHERITS (a_star); CREATE TABLE c_star ( c name ) INHERITS (a_star); CREATE TABLE d_star ( d float8 ) INHERITS (b_star, c_star); CREATE TABLE e_star ( e int2 ) INHERITS (c_star); CREATE TABLE f_star ( f polygon ) INHERITS (e_star); CREATE TABLE aggtest ( a int2, b float4 ); CREATE TABLE hash_i4_heap ( seqno int4, random int4 ) distributed by (seqno); CREATE TABLE hash_name_heap ( seqno int4, random name ) distributed by (seqno); CREATE TABLE hash_txt_heap ( seqno int4, random text ) distributed by (seqno); CREATE TABLE hash_f8_heap ( seqno int4, random float8 ) distributed by (seqno); -- don't include the hash_ovfl_heap stuff in the distribution -- the data set is too large for what it's worth -- -- CREATE TABLE hash_ovfl_heap ( -- x int4, -- y int4 -- ); CREATE TABLE bt_i4_heap ( seqno int4, random int4 ); CREATE TABLE bt_name_heap ( seqno name, random int4 ); CREATE TABLE bt_txt_heap ( seqno text, random int4 ); CREATE TABLE bt_f8_heap ( seqno float8, random int4 ); CREATE TABLE array_op_test ( seqno int4, i int4[], t text[] ); CREATE TABLE array_index_op_test ( seqno int4, i int4[], t text[] ); --MPP-22020: Dis-allow duplicate constraint names for the same table. create table dupconstr ( i int, j int constraint test CHECK (j > 10), CONSTRAINT test UNIQUE (i,j)) distributed by (i); -- MPP-2764: distributed randomly is not compatible with primary key or unique -- constraints create table distrand(i int, j int, primary key (i)) distributed randomly; create table distrand(i int, j int, unique (i)) distributed randomly; create table distrand(i int, j int, primary key (i, j)) distributed randomly; create table distrand(i int, j int, unique (i, j)) distributed randomly; create table distrand(i int, j int, constraint "test" primary key (i)) distributed randomly; create table distrand(i int, j int, constraint "test" unique (i)) distributed randomly; -- this should work though create table distrand(i int, j int, constraint "test" unique (i, j)) distributed by(i, j); drop table distrand; create table distrand(i int, j int) distributed randomly; create unique index distrand_idx on distrand(i); drop table distrand; -- Make sure distribution policy determined from CTAS actually works, MPP-101 create table distpol as select random(), 1 as a, 2 as b distributed by (random); select attrnums from gp_distribution_policy where localoid = 'distpol'::regclass; drop table distpol; create table distpol as select random(), 2 as foo distributed by (foo); select attrnums from gp_distribution_policy where localoid = 'distpol'::regclass; drop table distpol; -- now test that MPP-101 /actually/ works create table distpol (i int, j int, k int) distributed by (i); alter table distpol add primary key (j); select attrnums from gp_distribution_policy where localoid = 'distpol'::regclass; -- make sure we can't overwrite it create unique index distpol_uidx on distpol(k); -- should be able to now alter table distpol drop constraint distpol_pkey; create unique index distpol_uidx on distpol(k); select attrnums from gp_distribution_policy where localoid = 'distpol'::regclass; drop index distpol_uidx; -- expressions shouldn't be able to update the distribution key create unique index distpol_uidx on distpol(ln(k)); drop index distpol_uidx; -- lets make sure we don't change the policy when the table is full insert into distpol values(1, 2, 3); create unique index distpol_uidx on distpol(i); alter table distpol add primary key (i); drop table distpol; -- MPP-2872: set ops with distributed by should work as advertised create table distpol1 (i int, j int); create table distpol2 (i int, j int); create table distpol3 as select i, j from distpol1 union select i, j from distpol2 distributed by (j); select attrnums from gp_distribution_policy where localoid = 'distpol3'::regclass; drop table distpol3; create table distpol3 as (select i, j from distpol1 union select i, j from distpol2) distributed by (j); select attrnums from gp_distribution_policy where localoid = 'distpol3'::regclass; -- MPP-7268: CTAS produces incorrect distribution. drop table if exists foo; drop table if exists bar; create table foo (a varchar(15), b int) distributed by (b); create table bar as select * from foo distributed by (b); select attrnums from gp_distribution_policy where localoid='bar'::regclass; drop table if exists foo; drop table if exists bar; create table foo (a int, b varchar(15)) distributed by (b); create table bar as select * from foo distributed by (b); select attrnums from gp_distribution_policy where localoid='bar'::regclass; drop table if exists foo; drop table if exists bar; CREATE TABLE foo ( col_with_default numeric DEFAULT 0, col_with_default_drop_default character varying(30) DEFAULT 'test1', col_with_constraint numeric UNIQUE ) DISTRIBUTED BY (col_with_constraint); CREATE TABLE bar AS SELECT * FROM foo distributed by (col_with_constraint); select attrnums from gp_distribution_policy where localoid='bar'::regclass; drop table if exists foo; drop table if exists bar; -- MPP-14770: check for duplicate columns in DISTRIBUTED BY clause create table foo (a int, b text) distributed by (b,B); create table foo (a int, b int) distributed by (a,aA,A); create table foo (a int, b int) distributed by (b,a,aabb); create table foo (a int, b int) distributed by (c,C); create table foo ("I" int, i int) distributed by ("I",I); select attrnums from gp_distribution_policy where localoid='foo'::regclass; drop table if exists foo;
{ "content_hash": "7c2c92847bdd544f83e29160d48d8a40", "timestamp": "", "source": "github", "line_count": 333, "max_line_length": 80, "avg_line_length": 23.264264264264263, "alnum_prop": 0.7147282819155802, "repo_name": "foyzur/gpdb", "id": "0ef011c9aa4ce6981ff5ea63b0a60e2dc6ed4897", "size": "7797", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/test/regress/sql/create_table.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "5196" }, { "name": "Batchfile", "bytes": "11532" }, { "name": "C", "bytes": "34176888" }, { "name": "C++", "bytes": "4798415" }, { "name": "CMake", "bytes": "28254" }, { "name": "CSS", "bytes": "7068" }, { "name": "Cucumber", "bytes": "896816" }, { "name": "DTrace", "bytes": "1154" }, { "name": "Fortran", "bytes": "14777" }, { "name": "Groff", "bytes": "601878" }, { "name": "HTML", "bytes": "340701" }, { "name": "Java", "bytes": "943457" }, { "name": "Lex", "bytes": "202575" }, { "name": "M4", "bytes": "94554" }, { "name": "Makefile", "bytes": "463264" }, { "name": "Objective-C", "bytes": "7388" }, { "name": "PLSQL", "bytes": "174787" }, { "name": "PLpgSQL", "bytes": "47986854" }, { "name": "Perl", "bytes": "778165" }, { "name": "Python", "bytes": "5461340" }, { "name": "Ruby", "bytes": "3283" }, { "name": "SQLPL", "bytes": "122363" }, { "name": "Shell", "bytes": "471931" }, { "name": "XS", "bytes": "8309" }, { "name": "XSLT", "bytes": "5779" }, { "name": "Yacc", "bytes": "471668" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "b149e9749cfc0bfdc2d46ee1e5027275", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "389b8b305cd7cbc2891eefbe3b44e05dacc308c7", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Epacridaceae/Acrotriche/Acrotriche aristata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace NBasnet\CodeWriter; /** * Class CodeWriterSettings * @package NBasnet\CodeWriter */ class CodeWriterSettings { /** @var ISyntaxGrammar $syntax_grammar */ private $syntax_grammar; private $syntax_language; private $indent = 1; private $indent_space = 4; private $blank_indent = 0; /** * CodeWriterSettings constructor. * @param string $syntax_language * @param int $indent * @param int $indent_space */ public function __construct($syntax_language, $indent = 1, $indent_space = 4) { $this->syntax_language = $syntax_language; $this->indent = $indent; $this->indent_space = $indent_space; if ($this->syntax_language === ISyntaxGrammar::PHP) { $this->syntax_grammar = new PHPSyntaxGrammar(); } } /** * @param string $syntax_language * @param int $indent * @param int $indent_space * @return static */ public static function create($syntax_language, $indent = 1, $indent_space = 4) { return new static($syntax_language, $indent, $indent_space); } /** * @return int */ public function getIndent() { return $this->indent; } /** * @param int $indent * @return $this */ private function setIndent($indent) { $this->indent = $indent; return $this; } /** * @return int */ public function getIndentSpace() { return $this->indent_space; } /** * @return int */ public function getBlankIndent() { return $this->blank_indent; } /** * @param int $blank_indent * @return $this */ public function setBlankIndent($blank_indent) { $this->blank_indent = $blank_indent; return $this; } /** * @return ISyntaxGrammar */ public function getSyntaxGrammar() { return $this->syntax_grammar; } /** * @param ISyntaxGrammar $syntax_grammar * @return $this */ public function setSyntaxGrammar($syntax_grammar) { $this->syntax_grammar = $syntax_grammar; return $this; } /** * @return mixed */ public function getSyntaxLanguage() { return $this->syntax_language; } /** * @param string $syntax_language * @return $this */ public function setSyntaxLanguage($syntax_language) { $this->syntax_language = $syntax_language; return $this; } /** * @param int $indent * @return CodeWriterSettings */ public function replicate($indent = -1) { $indent = ($indent < 0) ? $this->indent : $indent; //clone the setting and set default values $new_settings = clone $this; $new_settings->setIndent($indent); return $new_settings; } }
{ "content_hash": "4b6cd21e734b9aa5ac0ac96db31f1062", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 83, "avg_line_length": 20.38888888888889, "alnum_prop": 0.5500681198910081, "repo_name": "nischalbasnet/php-codewriter", "id": "2c0f1a7c0d9ad42f90fee8b933883ebd9e91b505", "size": "2936", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/NBasnet/CodeWriter/CodeWriterSettings.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "35469" } ], "symlink_target": "" }
Eloquent push relations is an way to quickly save your relations based on eloquent declared relations. Of course you have to follow an specific standart. ### Instalation You can use the `composer` package manager to install. From console run: ``` $ php composer.phar require parfumix/laravel-push-relations "v1.0" ``` or add to your composer.json file "parfumix/laravel-push-relations": "v1.0" ##Basic usage Before you start working you have to include the main trait ***RelationTrait*** which will give the functionality. Below are showed an example. ```php <?php namespace App; use Laravel\Relations\RelationTrait; use Illuminate\Database\Eloquent\Model; class Page extends Model { use RelationTrait; public $relationShips = [ 'comments' => App\Comment::class ]; public function comments() { return $this->hasMany(Comments::class); } } class Comment extends Model { public function page() { return $this->belongsTo(Page::class) } } ``` To store the relations you have to ```php if($_POST) { $page = App\Page::find($request->get('page_id')) $page->fill($request->all()) ->refresh($request->all()) ->save(); } ``` But before to send your post you have to know which format you have to follow . ###Formats ***1:1*** Relation: ```html <!-- update the phone number --> <input type="hidden" name="phone[id]" value="1"> <input name="phone[prefix]" value="+373"> <input name="phone[phone]" value="123456789"> <!-- create the phone number --> <input name="phone[prefix]" value="+373"> <input name="phone[phone]" value="123456789"> ``` ***1:n*** Relation: ```html <!-- update the comment --> <input type="hidden" name="comments[1][id]" value="1"> <input name="comments[1][author]" value="Administrator"> <input name="comments[1][comment]" value="My comment updated"> <!-- create the comment --> <input name="comments[1][author]" value="Administrator"> <input name="comments[1][comment]" value="My comment inserted"> ``` ***n:n*** Relation: ```html <!-- update the roles and their pivots --> <input type="hidden" name="roles[1][sync]" value="1"> <!-- If use sync will be used laravel sync() --> <input name="roles[1][id]" value="1"> <input name="roles[1][pivot][expire]" value="2015-10-10"> <!-- will be attached role using sync by default --> <input name="roles[id]" value="1"> <!-- will be create new role and attached to curent model --> <input type="hidden" name="roles[1][sync]" value="1"> <!-- If use sync will be used laravel sync() --> <input name="roles[1][slug]" value="admin"> <input name="roles[1][name]" value="admin"> <input name="roles[1][pivot][expire]" value="2015-10-10"> ```
{ "content_hash": "0b9da83a89d1207c0386de181bd6760d", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 154, "avg_line_length": 25.91509433962264, "alnum_prop": 0.6516199490353113, "repo_name": "parfumix/laravel-push-relations", "id": "496f3e773275f04a1e2100a2d7942ddac590450e", "size": "2763", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "4627" } ], "symlink_target": "" }
/*global jQuery */ ;(function( $ ){ "use strict"; /** * Initialize the lifestream plug-in * @param {Object} config Configuration object */ $.fn.lifestream = function( config ) { // Make the plug-in chainable return this.each(function() { // The element where the lifestream is linked to var outputElement = $(this), // Extend the default settings with the values passed settings = jQuery.extend({ // The name of the main lifestream class // We use this for the main ul class e.g. lifestream // and for the specific feeds e.g. lifestream-twitter classname: "lifestream", // Callback function which will be triggered when a feed is loaded feedloaded: null, // The amount of feed items you want to show limit: 10, // An array of feed items which you want to use list: [] }, config), // The data object contains all the feed items data = { count: settings.list.length, items: [] }, // We use the item settings to pass the global settings variable to // every feed itemsettings = jQuery.extend( true, {}, settings ), /** * This method will be called every time a feed is loaded. This means * that several DOM changes will occur. We did this because otherwise it * takes to look before anything shows up. * We allow 1 request per feed - so 1 DOM change per feed * @private * @param {Array} inputdata an array containing all the feeditems for a * specific feed. */ finished = function( inputdata ) { // Merge the feed items we have from other feeds, with the feeditems // from the new feed $.merge( data.items, inputdata ); // Sort the feeditems by date - we want the most recent one first data.items.sort( function( a, b ) { return ( b.date - a.date ); }); var items = data.items, // We need to check whether the amount of current feed items is // smaller than the main limit. This parameter will be used in the // for loop length = ( items.length < settings.limit ) ? items.length : settings.limit, i = 0, item, // We create an unordered list which will create all the feed // items ul = $('<ul class="' + settings.classname + '"/>'); // Run over all the feed items + add them as list items to the // unordered list for ( ; i < length; i++ ) { item = items[i]; if ( item.html ) { $('<li class="'+ settings.classname + '-' + item.config.service + '">').data( "name", item.config.service ) .data( "url", item.url || "#" ) .data( "time", item.date ) .append( item.html ) .appendTo( ul ); } } // Change the innerHTML with a list of all the feeditems in // chronological order outputElement.html( ul ); // Trigger the feedloaded callback, if it is a function if ( $.isFunction( settings.feedloaded ) ) { settings.feedloaded(); } }, /** * Fire up all the feeds and pass them the right arugments. * @private */ load = function() { var i = 0, j = settings.list.length; // We don't pass the list array to each feed because this will create // a recursive JavaScript object delete itemsettings.list; // Run over all the items in the list for( ; i < j; i++ ) { var config = settings.list[i]; // Check whether the feed exists, if the feed is a function and if a // user has been filled in if ( $.fn.lifestream.feeds[config.service] && $.isFunction( $.fn.lifestream.feeds[config.service] ) && config.user) { // You'll be able to get the global settings by using // config._settings in your feed config._settings = itemsettings; // Call the feed with a config object and finished callback $.fn.lifestream.feeds[config.service]( config, finished ); } } }; // Load the jQuery templates plug-in if it wasn't included in the page. // At then end we call the load method. if( !jQuery.tmpl ) { jQuery.getScript( '//ajax.aspnetcdn.com/ajax/jquery.templates/beta1/' + 'jquery.tmpl.min.js', load); } else { load(); } }); }; /** * Create a valid YQL URL by passing in a query * @param {String} query The query you want to convert into a valid yql url * @return {String} A valid YQL URL */ $.fn.lifestream.createYqlUrl = function( query ) { return ( ('https:' === document.location.protocol ? 'https' : 'http') + '://query.yahooapis.com/v1/public/yql?q=__QUERY__' + '&env=' + 'store://datatables.org/alltableswithkeys&format=json') .replace( "__QUERY__" , encodeURIComponent( query ) ); }; /** * A big container which contains all available feeds */ $.fn.lifestream.feeds = $.fn.lifestream.feeds || {}; /** * Add compatible Object.keys support in older environments that do not natively support it * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys#section_6 */ if(!Object.keys) { Object.keys = function(o){ if (o !== Object(o)) { throw new TypeError('Object.keys called on non-object'); } var ret=[],p; for(p in o) { if(Object.prototype.hasOwnProperty.call(o,p)) { ret.push(p); } } return ret; }; } }( jQuery )); (function($) { $.fn.lifestream.feeds.atom = function( config, callback ) { var template = $.extend({}, { posted: 'posted <a href="${link.href}">${title.content}</a>' }, config.template), /** * Parse the input from atom feed */ parseAtom = function( input ) { var output = [], list = [], i = 0, j = 0, url = ''; if(input.query && input.query.count && input.query.count > 0) { list = input.query.results.feed.entry; j = list.length; for( ; i<j; i++) { var item = list[i]; output.push({ url: item.link.href, date: new Date( item.updated ), config: config, html: $.tmpl( template.posted, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where url="' + config.user + '"'), dataType: 'jsonp', success: function( data ) { callback(parseAtom(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.bitbucket = function( config, callback ) { var template = $.extend({}, { commit: '<a href="http://bitbucket.org/${owner}/${name}/changeset/${node}/">committed</a> at <a href="http://bitbucket.org/${owner}/${name}/">${owner}/${name}</a>', pullrequest_fulfilled: 'fulfilled a pull request at <a href="http://bitbucket.org/${owner}/${name}/">${owner}/${name}</a>', pullrequest_rejected: 'rejected a pull request at <a href="http://bitbucket.org/${owner}/${name}/">${owner}/${name}</a>', pullrequest_created: 'created a pull request at <a href="http://bitbucket.org/${owner}/${name}/">${owner}/${name}</a>', create: 'created a new project at <a href="http://bitbucket.org/${owner}/${name}/">${owner}/${name}</a>', fork: 'forked <a href="http://bitbucket.org/${owner}/${name}/">${owner}/${name}</a>' }, config.template), supported_events = [ "commit", "pullrequest_fulfilled", "pullrequest_rejected", "pullrequest_created", "create", "fork" ], parseBitbucketStatus = function( status ) { if ($.inArray(status.event, supported_events) !== -1) { //bb generates some weird create events, check for repository if (status.repository) { if (status.event === "commit") { return $.tmpl( template.commit, { owner: status.repository.owner, name: status.repository.name, node: status.node }); } else { return $.tmpl( template[status.event], { owner: status.repository.owner, name: status.repository.name }); } } } }, parseBitbucket = function( input ) { var output = []; if (input.query && input.query.count && input.query.count > 0) { $.each(input.query.results.json, function () { output.push({ date: new Date(this.events.created_on.replace(/-/g, '/')), config: config, html: parseBitbucketStatus(this.events) }); }); } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select events.event,' + 'events.node, events.created_on,' + 'events.repository.name, events.repository.owner ' + 'from json where url = "https://api.bitbucket.org/1.0/users/' + config.user + '/events/"'), dataType: 'jsonp', success: function( data ) { callback(parseBitbucket(data)); } }); return { 'template' : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.bitly = function( config, callback ) { var template = $.extend({}, { created: 'created URL <a href="${short_url}" title="${title}">' + '${short_url}</a>' }, config.template); $.ajax({ url: $.fn.lifestream.createYqlUrl('select data.short_url, data.created, '+ 'data.title from json where url="' + 'http://bitly.com/u/' + config.user + '.json"'), dataType: "jsonp", success: function( input ) { var output = [], i = 0, j, list; if ( input.query && input.query.count && input.query.results.json ) { list = input.query.results.json; j = list.length; for( ; i < j; i++) { var item = list[i].data; output.push({ date: new Date(item.created * 1000), config: config, html: $.tmpl( template.created, item ) }); } } callback(output); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.blogger = function( config, callback ) { var template = $.extend({}, { posted: 'posted <a href="${origLink}">${title}</a>' }, config.template), parseBlogger = function ( input ) { var output = [], list, i = 0, j, item, k, l; if ( input.query && input.query.count && input.query.count > 0 && input.query.results.feed.entry ) { list = input.query.results.feed.entry; j = list.length; for ( ; i < j; i++) { item = list[i]; if( !item.origLink ) { k = 0; l = item.link.length; for ( ; k < l ; k++ ) { if( item.link[k].rel === 'alternate' ) { item.origLink = item.link[k].href; } } } // ignore items that have no link. if ( item.origLink ){ if( item.title.content ) { item.title = item.title.content; } output.push({ date: new Date( item.published ), config: config, html: $.tmpl( template.posted, item ) }); } } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where url="http://' + config.user + '.blogspot.com/feeds/posts/default"'), dataType: "jsonp", success: function ( data ) { callback(parseBlogger(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.citeulike = function( config, callback ) { var template = $.extend({}, { saved: 'saved <a href="${href}">${title}</a> by ${authors}' }, config.template), parseCiteulike = function( data ) { var output = [], i = 0, j; if(data && data.length && data.length > 0) { j = data.length; for( ; i<j; i++) { var item = data[i]; output.push({ date: new Date(item.date), config: config, url: 'http://www.citeulike.org/user/' + config.user, html: $.tmpl( template.saved, item ) }); } } return output; }; $.ajax({ url: 'http://www.citeulike.org/json/user/' + config.user, dataType: 'jsonp', success: function( data ) { callback(parseCiteulike(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.dailymotion = function( config, callback ) { var template = $.extend({}, { uploaded: 'uploaded a video <a href="${link}">${title[0]}</a>' }, config.template), parseDailymotion = function( input ) { var output = [], list, i = 0, j, item; if ( input.query && input.query.count && input.query.count > 0 && input.query.results.rss.channel.item ) { list = input.query.results.rss.channel.item; j = list.length; for ( ; i < j; i++) { item = list[i]; output.push({ date: new Date ( item.pubDate ), config: config, html: $.tmpl( template.uploaded, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where ' + 'url="http://www.dailymotion.com/rss/user/' + config.user + '"'), dataType: "jsonp", success: function( data ) { callback(parseDailymotion(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.delicious = function( config, callback ) { var template = $.extend({}, { bookmarked: 'bookmarked <a href="${u}">${d}</a>' }, config.template); $.ajax({ url: "http://feeds.delicious.com/v2/json/" + config.user, dataType: "jsonp", success: function( data ) { var output = [], i = 0, j; if (data && data.length && data.length > 0) { j = data.length; for( ; i < j; i++) { var item = data[i]; output.push({ date: new Date(item.dt), config: config, html: $.tmpl( template.bookmarked, item ) }); } } callback(output); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.deviantart = function( config, callback ) { var template = $.extend({}, { posted: 'posted <a href="${link}">${title}</a>' }, config.template); $.ajax({ url: $.fn.lifestream.createYqlUrl( 'select title,link,pubDate from rss where ' + 'url="http://backend.deviantart.com/rss.xml?q=gallery%3A' + encodeURIComponent(config.user) + '&type=deviation' + '" | unique(field="title")' ), dataType: 'jsonp', success: function( resp ) { var output = [], items, item, i = 0, j; if (resp.query && resp.query.count > 0) { items = resp.query.results.item; j = items.length; for ( ; i < j; i++) { item = items[i]; output.push({ date: new Date(item.pubDate), config: config, html: $.tmpl( template.posted, item ) }); } } callback(output); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.disqus = function( config, callback ) { var template = $.extend({}, { post: 'commented on <a href="${url}">${thread.title}</a>', thread_like: 'liked <a href="${url}">${thread.title}</a>' }, config.template), parseDisqus = function( input ) { var output = [], i = 0, j, item; if(input) { j = input.length; for( ; i<j; i++) { item = input[i]; // replies to your comments are included by default if (item.type !== 'reply') { output.push({ date: new Date( item.createdAt ), config: config, html: $.tmpl( template[item.type], item.object ) }); } } } return output; }; $.ajax({ url: "https://disqus.com/api/3.0/users/listActivity.json", data: { user: config.user, api_key: config.key }, dataType: 'jsonp', success: function( data ) { if (data.code === 2) { callback([]); // log error to console if not on IE if (console && console.error) { console.error('Error loading Disqus stream.', data.response); } return; } else { callback(parseDisqus(data.response)); } } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.dribbble = function( config, callback ) { var template = $.extend({}, { posted: 'posted a shot <a href="${url}">${title}</a>' }, config.template); $.ajax({ url: "http://api.dribbble.com/players/" + config.user + "/shots", dataType: "jsonp", success: function( data ) { var output = [], i = 0, j; if(data && data.total) { j = data.shots.length; for( ; i<j; i++) { var item = data.shots[i]; output.push({ date: new Date(item.created_at), config: config, html: $.tmpl( template.posted, item ) }); } } callback(output); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.facebook_page = function( config, callback ) { var template = $.extend({}, { wall_post: 'post on wall <a href="${link}">${title}</a>' }, config.template), /** * Parse the input from facebook */ parseFBPage = function( input ) { var output = [], list, i = 0, j; if(input.query && input.query.count && input.query.count >0) { list = input.query.results.rss.channel.item; j = list.length; for( ; i<j; i++) { var item = list[i]; if( $.trim( item.title ) ){ output.push({ date: new Date(item.pubDate), config: config, html: $.tmpl( template.wall_post, item ) }); } } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where url="' + 'www.facebook.com/feeds/page.php?id=' + config.user + '&format=rss20"'), dataType: 'jsonp', success: function( data ) { callback(parseFBPage(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { 'use strict'; $.fn.lifestream.feeds.fancy = function( config, callback ) { var template = $.extend({}, { fancied: 'fancy\'d <a href="${link}">${title}</a>' }, config.template), parseFancy = function( input ) { var output = [], i = 0, j; if(input.query && input.query.count && input.query.count > 0) { j = input.query.count; for( ; i<j; i++) { var item = input.query.results.item[i]; output.push({ date: new Date(item.pubDate), config: config, html: $.tmpl( template.fancied, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('SELECT * FROM xml ' + 'WHERE url="http://www.fancy.com/rss/' + config.user + '" AND itemPath="/rss/channel/item"'), dataType: 'jsonp', success: function( data ) { callback(parseFancy(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.flickr = function( config, callback ) { var template = $.extend({}, { posted: 'posted a photo <a href="${link}">${title}</a>' }, config.template); $.ajax({ url: "http://api.flickr.com/services/feeds/photos_public.gne?id=" + config.user + "&lang=en-us&format=json", dataType: "jsonp", jsonp: 'jsoncallback', success: function( data ) { var output = [], i = 0, j; if(data && data.items && data.items.length > 0) { j = data.items.length; for( ; i<j; i++) { var item = data.items[i]; output.push({ date: new Date( item.published ), config: config, html: $.tmpl( template.posted, item ) }); } } callback(output); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.foomark = function( config, callback ) { var template = $.extend({}, { bookmarked: 'bookmarked <a href="${url}">${url}</a>' }, config.template); $.ajax({ url: "http://api.foomark.com/urls/list/", data: { format: "jsonp", username: config.user }, dataType: "jsonp", success: function( data ) { var output = [], i=0, j; if( data && data.length && data.length > 0 ) { j = data.length; for( ; i < j; i++ ) { var item = data[i]; output.push({ date: new Date( item.created_at.replace(/-/g, '/') ), config: config, html: $.tmpl( template.bookmarked, item ) }); } } callback( output ); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.formspring = function( config, callback ) { var template = $.extend({}, { answered: 'answered a question <a href="${link}">${title}</a>' }, config.template); var parseFormspring = function ( input ) { var output = [], list, i = 0, j, item; if ( input.query && input.query.count && input.query.count > 0 && input.query.results.rss.channel.item ) { list = input.query.results.rss.channel.item; j = list.length; for ( ; i < j; i++) { item = list[i]; output.push({ date: new Date( item.pubDate ), config: config, html: $.tmpl( template.answered, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where ' + 'url="http://www.formspring.me/profile/' + config.user + '.rss"'), dataType: "jsonp", success: function ( data ) { callback(parseFormspring(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.forrst = function( config, callback ) { var template = $.extend({}, { posted: 'posted a ${post_type} <a href="${post_url}">${title}</a>' }, config.template); $.ajax({ url: "http://forrst.com/api/v2/users/posts?username=" + config.user, dataType: "jsonp", success: function( data ) { var output = [], i=0, j; if( data && data.resp.length && data.resp.length > 0 ) { j = data.resp.length; for( ; i < j; i++ ) { var item = data.resp[i]; output.push({ date: new Date( item.created_at.replace(' ', 'T') ), config: config, html: $.tmpl( template.posted, item ) }); } } callback( output ); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.foursquare = function( config, callback ) { var template = $.extend({}, { checkedin: 'checked in @ <a href="${link}">${title}</a>' }, config.template), parseFoursquare = function( input ) { var output = [], i = 0, j; if(input.query && input.query.count && input.query.count >0) { j = input.query.count; for( ; i<j; i++) { var item = input.query.results.item[i]; output.push({ date: new Date(item.pubDate), config: config, html: $.tmpl( template.checkedin, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from rss where url=' + '"https://feeds.foursquare.com/history/' + config.user + '.rss"'), dataType: 'jsonp', success: function( data ) { callback(parseFoursquare(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.gimmebar = function( config, callback ) { var template = $.extend({}, { bookmarked: 'bookmarked <a href="${short_url}">${title}</a>' }, config.template); $.ajax({ url: "https://gimmebar.com/api/v0/public/assets/" + config.user + ".json?jsonp_callback=?", dataType: "json", success: function( data ) { data = data.records; var output = [], i = 0, j; if (data && data.length && data.length > 0) { j = data.length; for( ; i < j; i++) { var item = data[i]; output.push({ date: new Date(item.date * 1000), config: config, html: $.tmpl( template.bookmarked, item ) }); } } callback(output); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.github = function( config, callback ) { var template = $.extend({}, { commitCommentEvent: 'commented on <a href="http://github.com/' + '${status.repo.name}">${status.repo.name}</a>', createBranchEvent: 'created branch <a href="http://github.com/' + '${status.repo.name}/tree/${status.payload.ref}">' + '${status.payload.ref}</a> at <a href="http://github.com/' + '${status.repo.name}">${status.repo.name}</a>', createRepositoryEvent: 'created repository ' + '<a href="http://github.com/' + '${status.repo.name}">${status.repo.name}</a>', createTagEvent: 'created tag <a href="http://github.com/' + '${status.repo.name}/tree/${status.payload.ref}">' + '${status.payload.ref}</a> at <a href="http://github.com/' + '${status.repo.name}">${status.repo.name}</a>', deleteBranchEvent: 'deleted branch ${status.payload.ref} at ' + '<a href="http://github.com/${status.repo.name}">' + '${status.repo.name}</a>', deleteTagEvent: 'deleted tag ${status.payload.ref} at ' + '<a href="http://github.com/${status.repo.name}">' + '${status.repo.name}</a>', followEvent: 'started following <a href="http://github.com/' + '${status.payload.target.login}">${status.payload.target.login}</a>', forkEvent: 'forked <a href="http://github.com/${status.repo.name}">' + '${status.repo.name}</a>', gistEvent: '${status.payload.action} gist ' + '<a href="http://gist.github.com/${status.payload.gist.id}">' + '${status.payload.gist.id}</a>', issueCommentEvent: 'commented on issue <a href="http://github.com/' + '${status.repo.name}/issues/${status.payload.issue.number}">' + '${status.payload.issue.number}</a> on <a href="http://github.com/' + '${status.repo.name}">${status.repo.name}</a>', issuesEvent: '${status.payload.action} issue ' + '<a href="http://github.com/${status.repo.name}/issues/' + '${status.payload.issue.number}">${status.payload.issue.number}</a> '+ 'on <a href="http://github.com/${status.repo.name}">' + '${status.repo.name}</a>', pullRequestEvent: '${status.payload.action} pull request ' + '<a href="http://github.com/${status.repo.name}/pull/' + '${status.payload.number}">${status.payload.number}</a> on ' + '<a href="http://github.com/${status.repo.name}">' + '${status.repo.name}</a>', pushEvent: 'pushed to <a href="http://github.com/${status.repo.name}' + '/tree/${status.payload.ref}">${status.payload.ref}</a> at ' + '<a href="http://github.com/${status.repo.name}">' + '${status.repo.name}</a>', watchEvent: 'started watching <a href="http://github.com/' + '${status.repo.name}">${status.repo.name}</a>' }, config.template), parseGithubStatus = function( status ) { if (status.type === 'CommitCommentEvent' ) { return $.tmpl( template.commitCommentEvent, {status: status} ); } else if (status.type === 'CreateEvent' && status.payload.ref_type === 'branch') { return $.tmpl( template.createBranchEvent, {status: status} ); } else if (status.type === 'CreateEvent' && status.payload.ref_type === 'repository') { return $.tmpl( template.createRepositoryEvent, {status: status} ); } else if (status.type === 'CreateEvent' && status.payload.ref_type === 'tag') { return $.tmpl( template.createTagEvent, {status: status} ); } else if (status.type === 'DeleteEvent' && status.payload.ref_type === 'branch') { return $.tmpl( template.deleteBranchEvent, {status: status} ); } else if (status.type === 'DeleteEvent' && status.payload.ref_type === 'tag') { return $.tmpl( template.deleteTagEvent, {status: status} ); } else if (status.type === 'FollowEvent' ) { return $.tmpl( template.followEvent, {status: status} ); } else if (status.type === 'ForkEvent' ) { return $.tmpl( template.forkEvent, {status: status} ); } else if (status.type === 'GistEvent' ) { if (status.payload.action === 'create') { status.payload.action = 'created'; } else if (status.payload.action === 'update') { status.payload.action = 'updated'; } return $.tmpl( template.gistEvent, {status: status} ); } else if (status.type === 'IssueCommentEvent' ) { return $.tmpl( template.issueCommentEvent, {status: status} ); } else if (status.type === 'IssuesEvent' ) { return $.tmpl( template.issuesEvent, {status: status} ); } else if (status.type === 'PullRequestEvent' ) { return $.tmpl( template.pullRequestEvent, {status: status} ); } else if (status.type === 'PushEvent' ) { status.payload.ref = status.payload.ref.split('/')[2]; return $.tmpl( template.pushEvent, {status: status} ); } else if (status.type === 'WatchEvent' ) { return $.tmpl( template.watchEvent, {status: status} ); } }, parseGithub = function( input ) { var output = [], i = 0, j; if (input.query && input.query.count && input.query.count >0) { j = input.query.count; for ( ; i<j; i++) { var status = input.query.results.json[i].json; output.push({ date: new Date(status.created_at), config: config, html: parseGithubStatus(status), url: 'https://github.com/' + config.user }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select ' + 'json.type, json.actor, json.repo, json.payload, json.created_at ' + 'from json where url="https://api.github.com/users/' + config.user + '/events/public?per_page=100"'), dataType: 'jsonp', success: function( data ) { callback(parseGithub(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.googleplus = function( config, callback ) { var template = $.extend({}, { posted: '<a href="${actor.url}">${actor.displayName}</a>' + ' has posted a new entry <a href="${url}" ' + 'title="${id}">${title}</a> <!--With--> ' + '${object.replies.totalItems} replies, ' + '${object.plusoners.totalItems} +1s, ' + '${object.resharers.totalItems} Reshares' }, config.template), parseGooglePlus = function( input ) { var output = [], i = 0, j, item; if(input && input.items) { j = input.items.length; for( ; i<j; i++) { item = input.items[i]; output.push({ date: new Date( item.published ), config: config, html: $.tmpl( template.posted, item ) }); } } return output; }; $.ajax({ url: "https://www.googleapis.com/plus/v1/people/" + config.user + "/activities/public", data: { key: config.key }, dataType: 'jsonp', success: function( data ) { if (data.error) { callback([]); if (console && console.error) { console.error('Error loading Google+ stream.', data.error); } return; } else { callback(parseGooglePlus(data)); } } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.hypem = function( config, callback ) { if( !config.type || config.type !== "history" || config.type !== "loved" ) { config.type = "loved"; } var template = $.extend({}, { loved: 'loved <a href="http://hypem.com/item/${mediaid}">${title}</a> by <a href="http://hypem.com/artist/${artist}">${artist}</a>', history: 'listened to <a href="http://hypem.com/item/${mediaid}">${title}</a> by <a href="http://hypem.com/artist/${artist}">${artist}</a>' }, config.template); $.ajax({ url: "http://hypem.com/playlist/" + config.type + "/" + config.user + "/json/1/data.js", dataType: "json", success: function( data ) { var output = [], i = 0, j = -1; for (var k in data) { if (data.hasOwnProperty(k)) { j++; } } if (data && j > 0) { for( ; i < j; i++) { var item = data[i]; output.push({ date: new Date( (config.type === "history" ? item.dateplayed : item.dateloved) * 1000 ), config: config, html: $.tmpl( (config.type === "history" ? template.history : template.loved) , item ) }); } } callback(output); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.instapaper = function( config, callback ) { var template = $.extend({}, { loved: 'loved <a href="${link}">${title}</a>' }, config.template), parseInstapaper = function( input ) { var output = [], list, i = 0, j, item; if(input.query && input.query.count && input.query.count > 0 && input.query.results.rss.channel.item) { list = input.query.results.rss.channel.item; j = list.length; for( ; i<j; i++) { item = list[i]; output.push({ date: new Date( item.pubDate ), config: config, html: $.tmpl( template.loved, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where url=' + '"http://www.instapaper.com/starred/rss/' + config.user + '"'), dataType: 'jsonp', success: function( data ) { callback(parseInstapaper(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.iusethis = function( config, callback ) { var template = $.extend({}, { global: '${action} <a href="${link}">${what}</a> on (${os})' }, config.template); var parseIusethis = function( input ) { var output = [], list, i, j, k, l, m = 0, n, item, title, actions, action, what, os, oss = ["iPhone", "OS X", "Windows"]; if (input.query && input.query.count && input.query.count > 0 && input.query.results.rss) { n = input.query.results.rss.length; actions = ['started using', 'stopped using', 'stopped loving', 'Downloaded', 'commented on', 'updated entry for', 'started loving', 'registered']; l = actions.length; for( ; m < n; m++) { os = oss[m]; list = input.query.results.rss[m].channel.item; i = 0; j = list.length; for ( ; i < j; i++) { item = list[i]; title = item.title.replace(config.user + ' ', ''); k = 0; for( ; k < l; k++) { if(title.indexOf(actions[k]) > -1) { action = actions[k]; break; } } what = title.split(action); output.push({ date: new Date(item.pubDate), config: config, html: $.tmpl( template.global, { action: action.toLowerCase(), link: item.link, what: what[1], os: os } ) }); } } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where ' + 'url="http://iphone.iusethis.com/user/feed.rss/' + config.user + '" or ' + 'url="http://osx.iusethis.com/user/feed.rss/' + config.user + '" or ' + 'url="http://win.iusethis.com/user/feed.rss/' + config.user + '"'), dataType: "jsonp", success: function( data ) { callback(parseIusethis(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.lastfm = function( config, callback ) { var template = $.extend({}, { loved: 'loved <a href="${url}">${name}</a> by ' + '<a href="${artist.url}">${artist.name}</a>' }, config.template), parseLastfm = function( input ) { var output = [], list, i = 0, j; if(input.query && input.query.count && input.query.count > 0 && input.query.results.lovedtracks && input.query.results.lovedtracks.track) { list = input.query.results.lovedtracks.track; j = list.length; for( ; i<j; i++) { var item = list[i], itemDate = item.nowplaying ? new Date() : item.date.uts; output.push({ date: new Date(parseInt((itemDate * 1000), 10)), config: config, html: $.tmpl( template.loved, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where url=' + '"http://ws.audioscrobbler.com/2.0/user/' + config.user + '/lovedtracks.xml"'), dataType: 'jsonp', success: function( data ) { callback(parseLastfm(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.librarything = function( config, callback ) { var template = $.extend({}, { book: 'added <a href="http://www.librarything.com/work/book/${book.book_id}"' + ' title="${book.title} by ${book.author_fl}">' + '${book.title} by ${book.author_fl}</a> to my library' }, config.template), parseLibraryThing = function( input ) { var output = [], i = ""; if(input.books) { // LibraryThing returns a hash that maps id to Book objects // which leads to the following slightly weird for loop. for (i in input.books) { if (input.books.hasOwnProperty(i)) { var book = input.books[i]; output.push({ date : new Date(book.entry_stamp * 1000), config : config, html : $.tmpl(template.book, {book : book}), url : 'http://www.librarything.com/profile/' + config.user }); } } } return output; }; $.ajax({ url: 'http://www.librarything.com/api_getdata.php?booksort=entry_REV&userid=' + config.user, dataType: 'jsonp', success: function( data ) { callback(parseLibraryThing(data)); } }); return { "template" : template }; }; })(jQuery); (function($) { 'use strict'; $.fn.lifestream.feeds.linkedin = function( config, callback ) { var template = $.extend({}, { 'posted': '<a href="${link}">${title}</a>' }, config.template), jsonpCallbackName = 'jlsLinkedinCallback' + config.user, createYql = function(){ var query = 'SELECT * FROM feed WHERE url="' + config.url + '"'; // I bet some will not read the instructions if(config.user) { query += ' AND link LIKE "%' + config.user + '%"'; } return query; }, parseLinkedinItem = function(item) { return { 'date': new Date(item.pubDate), 'config': config, 'html': $.tmpl(template.posted, item) }; }; // !!! Global function for jsonp callback window[jsonpCallbackName] = function(input) { var output = [], i = 0; if(input.query && input.query.count && input.query.count > 0) { if (input.query.count === 1) { output.push(parseLinkedinItem(input.query.results.item)); } else { for(i; i < input.query.count; i++) { var item = input.query.results.item[i]; output.push(parseLinkedinItem(item)); } } } callback(output); }; $.ajax({ 'url': $.fn.lifestream.createYqlUrl(createYql()), 'cache': true, 'data': { // YQL will cache this for 5 minutes '_maxage': 300 }, 'dataType': 'jsonp', // let YQL cache 'jsonpCallback': jsonpCallbackName }); // Expose the template. // We use this to check which templates are available return { 'template': template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.mendeley = function( config, callback ) { var template = $.extend({}, { flagged1: 'flagged <a href="http://www.mendeley.com${link}">${title}</a>', flagged2: 'flagged <a href="${link}">${title}</a>' }, config.template), parseMendeley = function( input ) { var output = [], list, i = 0, j; if(input.query && input.query.count && input.query.count > 0) { list = input.query.results.rss.channel.item; j = list.length; for( ; i<j; i++) { var item = list[i]; var tmplt = ( (item.link.charAt(0) === '/') ? template.flagged1 : template.flagged2 ); output.push({ date: new Date(item.pubDate), config: config, url: 'http://mendeley.com/groups/' + config.user, html: $.tmpl( tmplt, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where url=' + '"http://www.mendeley.com/groups/' + config.user + '/feed/rss/"'), dataType: 'jsonp', success: function( data ) { callback(parseMendeley(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.miso = function( config, callback ) { var template = $.extend({}, { watched: 'checked in to <a href="${link}">${title}</a>' }, config.template), /** * Parse the input from rss feed */ parseMiso = function( input ) { var output = [], list, i = 0, j; if(input.query && input.query.count && input.query.count > 0) { list = input.query.results.rss.channel.item; j = list.length; for( ; i<j; i++) { var item = list[i]; output.push({ url: 'http://www.gomiso.com/feeds/user/' + config.user + '/checkins.rss', date: new Date( item.pubDate ), config: config, html: $.tmpl( template.watched, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where url="' + 'http://www.gomiso.com/feeds/user/' + config.user + '/checkins.rss"'), dataType: 'jsonp', success: function( data ) { callback(parseMiso(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.mlkshk = function( config, callback ) { var template = $.extend({}, { posted: 'posted <a href="${link}">${title}</a>' }, config.template); var parseMlkshk = function ( input ) { var output = [], list, i = 0, j, item; if ( input.query && input.query.count && input.query.count > 0 && input.query.results.rss.channel.item ) { list = input.query.results.rss.channel.item; j = list.length; for ( ; i < j; i++) { item = list[i]; output.push({ date: new Date( item.pubDate ), config: config, html: $.tmpl( template.posted, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where ' + 'url="http://mlkshk.com/user/' + config.user + '/rss"'), dataType: "jsonp", success: function ( data ) { callback(parseMlkshk(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.pinboard = function( config, callback ) { var template = $.extend({}, { bookmarked: 'bookmarked <a href="${link}">${title}</a>' }, config.template); var parsePinboard = function( input ) { var output = [], list, i = 0, j, item; if (input.query && input.query.count && input.query.count > 0) { list = input.query.results.RDF.item; j = list.length; for ( ; i < j; i++) { item = list[i]; output.push({ date: new Date(item.date), config: config, html: $.tmpl( template.bookmarked, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where ' + 'url="http://feeds.pinboard.in/rss/u:' + config.user + '"'), dataType: "jsonp", success: function( data ) { callback(parsePinboard(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.pocket = function( config, callback ) { var template = $.extend({}, { pocketed: 'pocketed <a href="${link}">${title}</a>' }, config.template), parsePocket = function( input ) { var output = [], list, i = 0, j; if(input.query && input.query.results) { list = input.query.results.rss.channel.item; j = list.length; for( ; i<j; i++) { var item = list[i]; var tmplt = template.pocketed; output.push({ date: new Date(item.pubDate), config: config, url: 'http://getpocket.com', html: $.tmpl( tmplt, item ), }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where url=' + '"http://www.getpocket.com/users/' + config.user + '/feed/all/"'), dataType: 'json', success: function( data ) { callback(parsePocket(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.posterous = function( config, callback ) { var template = $.extend({}, { posted: 'posted <a href="${link}">${title}</a>' }, config.template); var parsePosterous = function ( input ) { var output = [], list, i = 0, j, item; if ( input.query && input.query.count && input.query.count > 0 && input.query.results.rss.channel.item ) { list = input.query.results.rss.channel.item; j = list.length; for ( ; i < j; i++) { item = list[i]; output.push({ date: new Date( item.pubDate ), config: config, html: $.tmpl( template.posted, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where ' + 'url="http://' + config.user + '.posterous.com/rss.xml"'), dataType: "jsonp", success: function ( data ) { callback(parsePosterous(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.quora = function( config, callback ) { var template = $.extend({}, { posted: '<a href="${link}">${title}</a>' }, config.template), /** * Get the link * Straigth copy from RSS * * @param {Object} channel * @return {String} */ getChannelUrl = function(channel){ var i = 0, j = channel.link.length; for( ; i < j; i++) { var link = channel.link[i]; if( typeof link === 'string' ) { return link; } } return ''; }, /** * Parse the input from quora feed */ parseRSS = function( input ) { var output = [], list = [], i = 0, j = 0, url = ''; if(input.query && input.query.count && input.query.count > 0) { list = input.query.results.rss.channel.item; j = list.length; url = getChannelUrl(input.query.results.rss.channel); for( ; i<j; i++) { var item = list[i]; output.push({ url: url, date: new Date( item.pubDate ), config: config, html: $.tmpl( template.posted, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where ' + 'url="http://www.quora.com/' + config.user + '/rss"'), dataType: 'jsonp', success: function( data ) { callback(parseRSS(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.reddit = function( config, callback ) { var template = $.extend({}, { commented: '<a href="http://www.reddit.com/r/${item.data.subreddit}' + '/comments/${item.data.link_id.substring(3)}/u/' + '${item.data.name.substring(3)}?context=3">commented ' + '(${score})</a> in <a href="http://www.reddit.com/r/' + '${item.data.subreddit}">${item.data.subreddit}</a>', created: '<a href="http://www.reddit.com${item.data.permalink}">' + 'created new thread (${score})</a> in ' + '<a href="http://www.reddit.com/r/${item.data.subreddit}">' + '${item.data.subreddit}</a>' }, config.template); /** * Parsed one item from the Reddit API. * item.kind == t1 is a reply, t2 is a new thread */ var parseRedditItem = function( item ) { var score = item.data.ups - item.data.downs, pass = { item: item, score: (score > 0) ? "+" + score : score }; // t1 = reply, t3 = new thread if (item.kind === "t1") { return $.tmpl( template.commented, pass ); } else if (item.kind === "t3") { return $.tmpl( template.created, pass ); } }, /** * Reddit date's are simple epochs. * seconds*1000 = milliseconds */ convertDate = function( date ) { return new Date(date * 1000); }; $.ajax({ url: "http://www.reddit.com/user/" + config.user + ".json", dataType: "jsonp", jsonp:"jsonp", success: function( data ) { var output = [], i = 0, j; if(data && data.data && data.data.children && data.data.children.length > 0) { j = data.data.children.length; for( ; i<j; i++) { var item = data.data.children[i]; output.push({ date: convertDate(item.data.created_utc), config: config, html: parseRedditItem(item), url: 'http://reddit.com/user/' + config.user }); } } callback(output); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.rss = function( config, callback ) { var template = $.extend({}, { posted: 'posted <a href="${link}">${title}</a>' }, config.template), /** * Get the link * @param {Object} channel * @return {String} */ getChannelUrl = function(channel){ var i = 0, j = channel.link.length; for( ; i < j; i++) { var link = channel.link[i]; if( typeof link === 'string' ) { return link; } } return ''; }, /** * Parse the input from rss feed */ parseRSS = function( input ) { var output = [], list = [], i = 0, j = 0, url = ''; if(input.query && input.query.count && input.query.count > 0) { list = input.query.results.rss.channel.item; j = list.length; url = getChannelUrl(input.query.results.rss.channel); for( ; i<j; i++) { var item = list[i]; output.push({ url: url, date: new Date( item.pubDate ), config: config, html: $.tmpl( template.posted, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where url="' + config.user + '"'), dataType: 'jsonp', success: function( data ) { callback(parseRSS(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.slideshare = function( config, callback ) { var template = $.extend({}, { uploaded: 'uploaded a presentation <a href="${link}">${title}</a>' }, config.template); var parseSlideshare = function( input ) { var output = [], list, i = 0, j, item; if (input.query && input.query.count && input.query.count > 0) { list = input.query.results.rss.channel.item; j = list.length; for ( ; i < j; i++) { item = list[i]; output.push({ date: new Date(item.pubDate), config: config, html: $.tmpl( template.uploaded, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where ' + 'url="http://www.slideshare.net/rss/user/' + config.user + '"'), dataType: "jsonp", success: function( data ) { callback(parseSlideshare(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.snipplr = function( config, callback ) { var template = $.extend({}, { posted: 'posted a snippet <a href="${link}">${title}</a>' }, config.template); var parseSnipplr = function ( input ) { var output = [], list, i = 0, j, item; if ( input.query && input.query.count && input.query.count > 0 && input.query.results.rss.channel.item ) { list = input.query.results.rss.channel.item; j = list.length; for ( ; i < j; i++) { item = list[i]; output.push({ date: new Date( item.pubDate ), config: config, html: $.tmpl( template.posted, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where ' + 'url="http://snipplr.com/rss/users/' + config.user + '"'), dataType: "jsonp", success: function ( data ) { callback(parseSnipplr(data)); } }); }; })(jQuery);(function($) { $.fn.lifestream.feeds.stackoverflow = function( config, callback ) { var template = $.extend({}, { global: '<a href="${link}">${text}</a> - ${title}' }, config.template); var parseStackoverflowItem = function( item ) { var text="", title="", link="", stackoverflow_link = "http://stackoverflow.com/users/" + config.user, question_link = "http://stackoverflow.com/questions/"; if(item.timeline_type === "badge") { text = "was " + item.action + " the '" + item.description + "' badge"; title = item.detail; link = stackoverflow_link + "?tab=reputation"; } else if (item.timeline_type === "comment") { text = "commented on"; title = item.description; link = question_link + item.post_id; } else if (item.timeline_type === "revision" || item.timeline_type === "accepted" || item.timeline_type === "askoranswered") { text = (item.timeline_type === 'askoranswered' ? item.action : item.action + ' ' + item.post_type); title = item.detail || item.description || ""; link = question_link + item.post_id; } return { link: link, title: title, text: text }; }, convertDate = function( date ) { return new Date(date * 1000); }; $.ajax({ url: "https://api.stackoverflow.com/1.1/users/" + config.user + "/timeline?jsonp", dataType: "jsonp", jsonp: 'jsonp', success: function( data ) { var output = [], i = 0, j; if(data && data.total && data.total > 0 && data.user_timelines) { j = data.user_timelines.length; for( ; i<j; i++) { var item = data.user_timelines[i]; output.push({ date: convertDate(item.creation_date), config: config, html: $.tmpl( template.global, parseStackoverflowItem(item) ) }); } } callback(output); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.tumblr = function( config, callback ) { var template = $.extend({}, { posted: 'posted a ${type} <a href="${url}">${title}</a>' }, config.template), limit = config.limit || 20, getImage = function( post ) { switch(post.type) { case 'photo': var images = post['photo-url']; return $('<img width="75" height="75"/>') .attr({ src: images[images.length - 1].content, title: getTitle(post), alt: getTitle(post) }).wrap('<div/>').parent().html(); // generate an HTML string case 'video': var videos = post['video-player']; var video = videos[videos.length - 1].content; // Videos hosted on Tumblr use JavaScript to render the // video, but the JavaScript doesn't work when we call it // from a lifestream - so don't try to embed these. if (video.match(/<\s*script/)) { return null; } return video; case 'audio': // Unlike photo and video, audio gives you no visual indication // of what it contains, so we append the "title" text. return post['audio-player'] + ' ' + // HTML-escape the text. $('<div/>').text(getTitle(post)).html(); default: return null; } }, getFirstElementOfBody = function( post, bodyAttribute ) { return $(post[bodyAttribute]).filter(':not(:empty):first').text(); }, getTitleForPostType = function( post ) { var title; switch(post.type) { case 'regular': return post['regular-title'] || getFirstElementOfBody(post, 'regular-body'); case 'link': title = post['link-text'] || getFirstElementOfBody(post, 'link-description'); if (title === '') { title = post['link-url']; } return title; case 'video': return getFirstElementOfBody(post, 'video-caption'); case 'audio': return getFirstElementOfBody(post, 'audio-caption'); case 'photo': return getFirstElementOfBody(post, 'photo-caption'); case 'quote': return '"' + post['quote-text'].replace(/<.+?>/g, ' ').trim() + '"'; case 'conversation': title = post['conversation-title']; if (!title) { title = post.conversation.line; if (typeof(title) !== 'string') { title = title[0].label + ' ' + title[0].content + ' ...'; } } return title; case 'answer': return post.question; default: return post.type; } }, /** * get title text */ getTitle = function( post ) { var title = getTitleForPostType(post) || ''; // remove tags return title.replace( /<.+?>/gi, " "); }, createTumblrOutput = function( config, post ) { return { date: new Date(post.date), config: config, html: $.tmpl( template.posted, { type: post.type.replace('regular', 'blog entry'), url: post.url, image: getImage(post), title: getTitle(post) } ) }; }, parseTumblr = function( input ) { var output = [], i = 0, j, post; if(input.query && input.query.count && input.query.count > 0) { // If a user only has one post, post is a plain object, otherwise it // is an array if ( $.isArray(input.query.results.posts.post) ) { j = input.query.results.posts.post.length; for( ; i < j; i++) { post = input.query.results.posts.post[i]; output.push(createTumblrOutput(config, post)); } } else if ( $.isPlainObject(input.query.results.posts.post) ) { output.push( createTumblrOutput(config,input.query.results.posts.post) ); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select *' + ' from tumblr.posts where username="' + config.user + '"' + ' and num="' + limit + '"'), dataType: 'jsonp', success: function( data ) { callback(parseTumblr(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { "use strict"; $.fn.lifestream.feeds.twitter = function( config, callback ) { var template = $.extend({}, { "posted": '{{html tweet}}' }, config.template), jsonpCallbackName = 'jlsTwitterCallback' + config.user.replace(/[^a-zA-Z0-9]+/g, ''), /** * Add links to the twitter feed. * Hashes, @ and regular links are supported. * @private * @param {String} tweet A string of a tweet * @return {String} A linkified tweet */ linkify = function( tweet ) { var link = function( t ) { return t.replace( /([a-z]+:\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, function( m ) { return '<a href="' + m + '">' + ( ( m.length > 25 ) ? m.substr( 0, 24 ) + '...' : m ) + '</a>'; } ); }, at = function( t ) { return t.replace( /(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g, function( m, m1, m2 ) { return m1 + '<a href="http://twitter.com/' + m2 + '">@' + m2 + '</a>'; } ); }, hash = function( t ) { return t.replace( /(^|[^\w'"]+)\#([a-zA-Z0-9ÅåÄäÖöØøÆæÉéÈèÜüÊêÛûÎî_]+)/g, function( m, m1, m2 ) { return m1 + '<a href="http://search.twitter.com/search?q=%23' + m2 + '">#' + m2 + '</a>'; } ); }; return hash(at(link(tweet))); }, /** * Parse the input from twitter * @private * @param {Object[]} items * @return {Object[]} Array of Twitter status messages. */ parseTwitter = function( items ) { var output = [], i = 0, j = items.length; for( i; i < j; i++ ) { var status = items[i]; output.push({ "date": new Date(status.created_at * 1000), // unix time "config": config, "html": $.tmpl( template.posted, { "tweet": linkify($('<div/>').html(status.text).text()), "complete_url": 'http://twitter.com/' + config.user + "/status/" + status.id_str } ), "url": 'http://twitter.com/' + config.user }); } return output; }; /** * Global JSONP callback * This should allow for better response caching by YQL. * @param {Object[]} data YQL response items * @return {undefined} */ window[jsonpCallbackName] = function(data) { if ( data.query && data.query.count > 0 ) { callback(parseTwitter(data.query.results.items)); } }; $.ajax({ "url": $.fn.lifestream.createYqlUrl('USE ' + '"http://arminrosu.github.io/twitter-open-data-table/table.xml" ' + 'AS twitter; SELECT * FROM twitter WHERE screen_name = "' + config.user + '"'), "cache": true, 'data': { '_maxage': 300 // cache for 5 minutes }, "dataType": 'jsonp', "jsonpCallback": jsonpCallbackName // better caching }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.vimeo = function( config, callback ) { var template = $.extend({}, { liked: 'liked <a href="${url}" title="${description}">${title}</a>', posted: 'posted <a href="${url}" title="${description}">${title}</a>' }, config.template), parseVimeo = function( input, item_type ) { var output = [], i = 0, j, item, type = item_type || 'liked', date, description; if (input) { j = input.length; for( ; i < j; i++) { item = input[i]; if (type === 'posted') { date = new Date( item.upload_date.replace(' ', 'T') ); } else { date = new Date( item.liked_on.replace(' ', 'T') ); } if (item.description) { description = item.description.replace(/"/g, "'").replace( /<.+?>/gi, ''); } else { description = ''; } output.push({ date: date, config: config, html: $.tmpl( template[type], { url: item.url, description: item.description ? item.description .replace(/"/g, "'") .replace( /<.+?>/gi, '') : '', title: item.title }) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('SELECT * FROM xml WHERE ' + 'url="http://vimeo.com/api/v2/' + config.user + '/likes.xml" OR ' + 'url="http://vimeo.com/api/v2/' + config.user + '/videos.xml"'), dataType: 'jsonp', success: function( response ) { var output = []; // check for likes & parse if ( response.query.results.videos[0] != null && response.query.results.videos[0].video.length > 0 ) { output = output.concat(parseVimeo( response.query.results.videos[0].video )); } // check for uploads & parse if ( response.query.results.videos[1] != null && response.query.results.videos[1].video.length > 0 ) { output = output.concat( parseVimeo(response.query.results.videos[1].video, 'posted') ); } callback(output); } }); // Expose the template. // We use this to check which templates are available return { 'template' : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.wikipedia = function( config, callback ) { // default to english if no language was set var language = config.language || 'en', template = $.extend({}, { contribution: 'contributed to <a href="${url}">${title}</a>' }, config.template); $.ajax({ url: "http://" + language + ".wikipedia.org/w/api.php?action=query&ucuser=" + config.user + "&list=usercontribs&ucdir=older&format=json", dataType: "jsonp", success: function( data ) { var output = [], i = 0, j; if(data && data.query.usercontribs) { j = data.query.usercontribs.length; for( ; i<j; i++) { var item = data.query.usercontribs[i]; // Fastest way to get the URL. // Alternatively, we'd have to poll wikipedia for the pageid's link item.url = 'http://' + language + '.wikipedia.org/wiki/' + item.title.replace(' ', '_'); output.push({ date: new Date( item.timestamp ), config: config, html: $.tmpl( template.contribution, item ) }); } } callback(output); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.wordpress = function( config, callback ) { var template = $.extend({}, { posted: 'posted <a href="${link}">${title}</a>' }, config.template); var parseWordpress = function ( input ) { var output = [], list, i = 0, j, item; if ( input.query && input.query.count && input.query.count > 0 && input.query.results.rss.channel.item ) { list = input.query.results.rss.channel.item; j = list.length; for ( ; i < j; i++) { item = list[i]; output.push({ date: new Date( item.pubDate ), config: config, html: $.tmpl( template.posted, item ) }); } } return output; }; var url = ""; if ( config.user ){ // If the config.user property starts with http:// we assume that is the // full url to the user his blog. We append the /feed to the url. url = (config.user.indexOf('http://') === 0 ? config.user + '/feed' : 'http://' + config.user + '.wordpress.com/feed'); $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where ' + 'url="' + url + '"'), dataType: "jsonp", success: function ( data ) { callback(parseWordpress(data)); } }); } // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);(function($) { $.fn.lifestream.feeds.youtube = function( config, callback ) { var template = $.extend({}, { uploaded: 'uploaded <a href="${video.player.default}" ' + 'title="${video.description}">${video.title}</a>', favorited: 'favorited <a href="${video.player.default}" ' + 'title="${video.description}">${video.title}</a>' }, config.template), parseYoutube = function( input, activity ) { var output = [], i = 0, j, item, video, date, templateData; if(input.data && input.data.items) { j = input.data.items.length; for( ; i<j; i++) { item = input.data.items[i]; switch (activity) { case 'favorited': video = item.video; date = item.created; templateData = item; break; case 'uploaded': video = item; date = video.uploaded; templateData = {video: video}; break; } // Don't add unavailable items (private, rejected, failed) if (!video.player || !video.player['default']) { continue; } output.push({ date: new Date(date), config: config, html: $.tmpl( template[activity], templateData ) }); } } return output; }; $.ajax({ url: "http://gdata.youtube.com/feeds/api/users/" + config.user + "/favorites?v=2&alt=jsonc", dataType: 'jsonp', success: function( data ) { callback(parseYoutube(data, 'favorited')); } }); $.ajax({ url: "http://gdata.youtube.com/feeds/api/users/" + config.user + "/uploads?v=2&alt=jsonc", dataType: 'jsonp', success: function( data ) { callback(parseYoutube(data, 'uploaded')); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery); (function($) { $.fn.lifestream.feeds.zotero = function( config, callback ) { var template = $.extend({}, { flagged: 'flagged <a href="${id}">${title}</a> by ${creatorSummary}' }, config.template), parseZotero = function( input ) { var output = [], list, i = 0, j; if(input.query && input.query.count && input.query.count > 0) { list = input.query.results.feed.entry; j = list.length; for( ; i<j; i++) { var item = list[i]; output.push({ date: new Date(item.updated), config: config, url: 'http://zotero.com/users/' + config.user, html: $.tmpl( template.flagged, item ) }); } } return output; }; $.ajax({ url: $.fn.lifestream.createYqlUrl('select * from xml where url=' + '"https://api.zotero.org/users/' + config.user + '/items"'), dataType: 'jsonp', success: function( data ) { callback(parseZotero(data)); } }); // Expose the template. // We use this to check which templates are available return { "template" : template }; }; })(jQuery);
{ "content_hash": "e6895260f2788412bd2fd8e3020735bb", "timestamp": "", "source": "github", "line_count": 2779, "max_line_length": 170, "avg_line_length": 26.99388269161569, "alnum_prop": 0.5365522021968646, "repo_name": "eldabbagh/jquery-lifestream", "id": "f1f05497e21d2a8f1036a0ff1f00a6ddc8a412c4", "size": "75332", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "jquery.lifestream.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package ai.verta.swagger._public.uac.audit.model import scala.util.Try import net.liftweb.json._ import ai.verta.swagger.client.objects._ case class VersioningAuditLogPredicates ( resource_predicate: Option[VersioningResourcePredicate] = None, timestamp_predicate: Option[VersioningRangeTimeStampPredicate] = None, user_predicate: Option[VersioningUserPredicate] = None ) extends BaseSwagger { def toJson(): JValue = VersioningAuditLogPredicates.toJson(this) } object VersioningAuditLogPredicates { def toJson(obj: VersioningAuditLogPredicates): JObject = { new JObject( List[Option[JField]]( obj.resource_predicate.map(x => JField("resource_predicate", ((x: VersioningResourcePredicate) => VersioningResourcePredicate.toJson(x))(x))), obj.timestamp_predicate.map(x => JField("timestamp_predicate", ((x: VersioningRangeTimeStampPredicate) => VersioningRangeTimeStampPredicate.toJson(x))(x))), obj.user_predicate.map(x => JField("user_predicate", ((x: VersioningUserPredicate) => VersioningUserPredicate.toJson(x))(x))) ).flatMap(x => x match { case Some(y) => List(y) case None => Nil }) ) } def fromJson(value: JValue): VersioningAuditLogPredicates = value match { case JObject(fields) => { val fieldsMap = fields.map(f => (f.name, f.value)).toMap VersioningAuditLogPredicates( // TODO: handle required resource_predicate = fieldsMap.get("resource_predicate").map(VersioningResourcePredicate.fromJson), timestamp_predicate = fieldsMap.get("timestamp_predicate").map(VersioningRangeTimeStampPredicate.fromJson), user_predicate = fieldsMap.get("user_predicate").map(VersioningUserPredicate.fromJson) ) } case _ => throw new IllegalArgumentException(s"unknown type ${value.getClass.toString}") } }
{ "content_hash": "0942cbab7b171e2e4809aad135b51ccd", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 164, "avg_line_length": 42.54545454545455, "alnum_prop": 0.7115384615384616, "repo_name": "mitdbg/modeldb", "id": "e01e4f8ae404a1f1046b33072a2651b75638a87d", "size": "1916", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/scala/src/main/scala/ai/verta/swagger/_public/uac/audit/model/VersioningAuditLogPredicates.scala", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "43352" }, { "name": "Dockerfile", "bytes": "235" }, { "name": "HTML", "bytes": "30924" }, { "name": "Java", "bytes": "393927" }, { "name": "JavaScript", "bytes": "1017682" }, { "name": "Python", "bytes": "178774" }, { "name": "Scala", "bytes": "251259" }, { "name": "Shell", "bytes": "16870" }, { "name": "Thrift", "bytes": "55683" } ], "symlink_target": "" }
<?php /** * Configuration template for the Redis module for simpleSAMLphp */ $config = [ // Predis client parameters 'parameters' => 'tcp://localhost:6379', // Predis client options 'options' => null, // Old host /* 'oldHost' => [ // Predis client parameters 'parameters' => 'tcp://localhost:6379', // Predis client options 'options' => null, ], */ // Key prefix 'prefix' => 'simpleSAMLphp', // Lifitime for all non expiring keys 'lifetime' => 288000 ];
{ "content_hash": "678f200877d57c84e434dfc59d84dfd2", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 64, "avg_line_length": 19.5, "alnum_prop": 0.5567765567765568, "repo_name": "ColourboxDevelopment/simplesamlphp-module-redis", "id": "4d2c3b9a4637e9ea9457caf75ae6eb0b60331c69", "size": "546", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config-templates/module_redis.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "11106" } ], "symlink_target": "" }
Module 8 Lab: Configuring SharePoint Online ---------------------------------- Scenario With the deployment of Office 365 now in full swing and the excitement of the Exchange Online cutover migration behind them, the management team at Lucerne Publishing is looking to implement the other services in the Office 365 portfolio. The company definitely wants to adopt some of the features in SharePoint Online, including social media capabilities such as Yammer. Again, Heidi is heading up this effort to configure site collections, Yammer, and OneDrive for Business. She begins by creating site collections, both through the SharePoint Online user interface and PowerShell. Objectives To provide the students with the experience of planning, setting up, and configuring SharePoint Online. Lab Setup Estimated Time: 70 minutes Virtual machine: 20346C-LUC-CL1 Username: **Student1** Password: **Pa$$w0rd** Where you see references in the steps to lucernepublishingXXXX.onmicrosoft.com, you should replace XXXX with the unique Lucerne Publishing number that you are assigned when you set up your Office 365 accounts in Module 1, Lab 1B, Exercise 2, Task 3, Step 5. Where you see references to labXXXXX.o365ready.com, you should replace XXXXX with the unique O365ready.com number you are assigned when you registered your IP address at www.o365ready.com in Module 2, Lab 2B, Exercise 1, Task 2, Step 6. ### Exercise 1: Create SharePoint Site Collections Scenario After the excitement of the successful Exchange Online cutover migration, Heidi is settling down to review the deployment of SharePoint Online. The company does not plan to replace its existing on-premises document management environment, but wants to use SharePoint Online to connect more easily with associates, partners, and suppliers. Consequently, Heidi starts off by creating site collections, both with SharePoint admin center and with PowerShell. She works with Rick Torres to validate access rights to these sites. The main tasks for this exercise are as follows: 1. Create Site Collections in the SharePoint Online Admin Center 2. Create a Site Collection with PowerShell 3. Verify and Use Site Collections 4. Upload Documents to a Site Collection ####   Task 1: Create Site Collections in the SharePoint Online Admin Center 1. On your host computer, ensure you are logged into the **20346C-LUC-CL1** virtual machine as **Student1** with a password of **Pa$$word**. In **LUC-CL1**, click **Desktop**, in the Task bar, click Internet Explorer and browse to **https://login.microsoftonline.com**. Sign in as **hleitner@labXXXXX.o365ready.com** (where XXXXX is your unique O365ready.com number) with a password of **Pa$$w0rd**. In the **Office 365 Admin** console, click **Admin**, then click **SharePoint**. On the left-hand side, click **Site collections**. In the ribbon, in the **Contribute** section, click **New**, and then **Private Site Collection**. In the **Title** box, type **Publishing Sales**. In **Web Site Address** box, leave the first address as **https://lucernepublishingXXXX.sharepoint.com**, where XXXX is your unique Lucerne Publishing number). Leave the second box as **/sites/**. In the third box, type in **PubSales**. Under **Select a template**, select **Team Site**. In the **Administrator** box, type **Justin**, and then click the **Check names** button. In the **Storage Quota** box, type **500**. Click **OK**. Wait for the site collection to be created, which may take about 10 minutes. In the ribbon, in the **Contribute** section, click **New**, and then **Private Site Collection**. In the **Title** box, type **External User Share**. In the final **Web Site Address** box, type **ExtShare**. Under **Select a template**, select the **Enterprise** tab, then select **Document Center**. In the **Administrator** box, type **Justin**, and then click the **Check names** button. In the **Storage Quota** box, type **1000**. Click **OK**. Wait for the site collection to be created, which may take about 10 minutes. In the top-right corner, click **Heidi Leitner**, then **Sign Out**. Close Internet Explorer. ####   Task 2: Create a Site Collection with PowerShell 1. The **SharePoint Online Management Shell** is a tool that contains a Windows PowerShell Module to manage your SharePoint Online subscription in Office 365. To install the SharePoint Online Management Shell, you must first download it from the **Microsoft Download Center**. To do so, open a new Internet Explorer tab and browse to **http://www.microsoft.com/en-us/download/details.aspx?id=35588**. On the **SharePoint Online Management Shell** download page, in the **Select Language** drop-down box, select your appropriate language, and then click **Download**. On the **Choose the download you want** page, select the check box for the **64 bit version;** the file name is **sharepointonlinemanagementshell\_3716-1200\_x64\_en-us.msi**. Click **Next**. If a message about pop-ups appears, click **Allow once**. In the Internet Explorer dialog box asking whether you want to run or save the file, click **Run**. In the **SharePoint Online Management Shell Setup** page, select the **I accept the terms in the License Agreement** checkbox, and click **Install**. If a **User Account Control** dialog box appears, click **Yes**. When the installation completes, click **Finish**. Click **Start**, type **sharep**, right-click **SharePoint Online Management Shell** and then click **Run as administrator**. In the **User Account Control** dialog box, click **Yes**. At the prompt, type the following command and press Enter (where XXXX is your unique Lucerne Publishing number and XXXXX is your unique O365ready.com number): Connect-SPOService –Url https://lucernepublishingXXXX-admin.sharepoint.com –credential hleitner@labXXXXX.o365ready.com In the **Enter your credentials** dialog box, in the **Password** box, type **Pa$$w0rd**. Click **OK**. At the prompt, type the following command and press Enter (where XXXX is your unique Lucerne Publishing number and XXXXX is your unique O365ready.com number): New-SPOSite -Url https://lucernepublishingXXXX.sharepoint.com/sites/AcctsProj -Owner jmuller@labXXXXX.o365ready.com -StorageQuota 500 -NoWait -Template PROJECTSITE\#0 –Title “Accounts Project” At the prompt, type the following command and press Enter: Exit ####   Task 3: Verify and Use Site Collections 1. In **LUC-CL1**, on the Desktop, right-click **Internet** **Explorer** on the Task Bar and click **Start InPrivate Browsing**. Browse to **https://login.microsoftonline.com**. Sign in as **rtorres@labXXXXX.o365ready.com**, (where XXXXX is your unique O365ready.com number) and a password of **Pa$$w0rd**. In the same **InPrivate session** of Internet Explorer, press Ctrl+T to open a new tab and browse to **https://lucernepublishing*XXXX*.sharepoint.com/sites/PubSales**, (where XXXX is your unique Lucerne Publishing number). Note the **You need permission to access this site** message, and that you need to send an access request for permission to view the site. Click **Start**, then on the **Start** page, click **Internet** **Explorer** to start a modern browser session. Navigate to **https://login.microsoftonline.com**. Sign in as **jmuller@labXXXXX.o365ready.com** (where XXXXX is your unique O365ready.com number), with a password of **Pa$$w0rd**. If prompted for your **Language,** click **English (United States)** and select **(UTC) Coordinated Universal Time** as the time zone, then click **Save**. In the **modern browser**, press **Ctrl+T** to open a new tab and browse to **https://lucernepublishing*XXXX*.sharepoint.com/sites/PubSales**, (where XXXX is your unique Lucerne Publishing number). In the top-right corner, click the **Settings** icon (the cog), and then click **Site settings**. Under **User and Permissions**, click **Site permissions**. Click **Publishing Sales Members**. Click **New**, then click **Add Users**. In the text box at the top, type **rick** and then click **Rick Torres**. Click **Share**. In the **modern browser** tab, browse to **https://lucernepublishing*XXXX*.sharepoint.com/sites/ExtShare**, (where XXXX is your unique Lucerne Publishing number). In the top-right corner, click the **Settings** icon (the cog), and then click **Site settings**. Under **User and Permissions**, click **Site permissions**. Click **External User Share Owners**. Click **New**, then click **Add Users**. In the text box at the top, type **elisabeth** and then click **Elisabeth Labrecque**. Click **Share**. Press **Ctrl-F4** to close this tab only. Press the Windows key and click **Desktop**. Switch to Rick Torres’ Office 365 logon. In Internet Explorer, open a new tab and browse to **https://lucernepublishing*XXXX*.sharepoint.com/sites/PubSales**, (where XXXX is your unique Lucerne Publishing number). Verify that you can access the site. Close the current tab. In the Task Bar, right-click the **Internet** **Explorer** icon and click **Internet Explorer**. In the desktop session, browse to **https://login.microsoftonline.com**. Sign in as **elabrecque@labXXXXX.o365ready.com** (where XXXXX is your unique O365ready.com number), with a password of **Pa$$w0rd**. Press **Ctrl-T** to open a new tab and browse to **https://lucernepublishing*XXXX*.sharepoint.com/sites/ExtShare**, (where XXXX is your unique Lucerne Publishing number). Verify that you can access the site. ####   Task 4: Upload Documents to a Site Collection 1. Click **Upload a Document**. Click **Browse**. Navigate to **E:\\Labfiles\\Lab08** and select the first of these documents: > **Company Profile.docx** > > **Sales Fact Sheet.docx** > > **Sales Proposal.docx** Click **Open**. Click **OK**. In the **Documents** dialog box, click **Check In**. Repeat steps 1 to 6 for the remaining documents in the list above. Refresh the **External User Share** page. In the left navigation click **Documents**. Verify that there are three documents listed. In the top-right corner, click **Elisabeth Labrecque**, then **Sign Out**. Close the desktop instance of Internet Explorer. **Results**: Lucerne Publishing has created site collections and configured external access. ### Exercise 2: Configure External User Sharing Scenario Because partners and associates need to access some of the Lucerne Publishing sites, Heidi must configure external access to the site collections so that associates and partners can connect. She uses her personal external email address to test access rights and connectivity to the share. The main tasks for this exercise are as follows: 1. Configure a Site Collection for External User Sharing 2. Verify External User Sharing ####   Task 1: Configure a Site Collection for External User Sharing 1. Press the Windows key and in the Start page, click **Internet** **Explorer**. If you are not logged in as **Heidi Leitner**, sign out and sign in as **hleitner@labXXXXX.o365ready.com** (where XXXXX is your unique O365ready.com number) with a password of **Pa$$w0rd** In the **Office 365 Admin** console, click **Admin**, and then click **SharePoint**. On the left-hand side, click **Site Collections**. Select the check box for the **https://lucernepublishingXXXX.sharepoint.com/sites/ExtShare** site collection, (where XXX is your unique Lucerne Publishing number). In the ribbon, in the **Manage** section, click **Sharing**. In the **Sharing** dialog box, click **Allow both external users who accept sharing invitations and anonymous guest links**. Click **Save**. Wait for the operation to complete, which may take about 10 minutes. Click on Heidi Leitner’s profile picture icon in the top right screen and then **Sign-Out**. In Internet Explorer, press **Ctrl+T** to open a new tab and browse to **https://lucernepublishingXXXX.sharepoint.com/sites/ExtShare**, (where XXX is your unique Lucerne Publishing number). Sign in as **jmuller@labXXXXX.o365ready.com** (where XXXXX is your unique O365ready.com number) with a password of **Pa$$w0rd.** In the top-right corner, click **SHARE**. In the **Share ‘External User Share’** dialog box, type in the email address of the Microsoft Live account you used to set up Office 365 in Lab 1. In the message box, type **You can now access this shared site on Lucerne Publishing**. Click **SHOW OPTIONS**. Under **Select a group or permission level**, in the drop-down list, select **External User Share Members [Contribute]**. Click **Share**. In the left navigation click **Documents**. In the document list, click the ellipsis button (**…**) next to the document you want to share, then click **SHARE**. Click **Get a link**, then under **View Only**, click **CREATE LINK**. Select the link, then right-click it and choose **Copy**. Click **Close**. In **SharePoint Online**, click **Outlook**. If prompted, select your language and time zone, and then click **Save**. Click **New**. In the **To** box, type the email address for your personal external email account or your Microsoft Live account.  In the **Subject** box, type **Shared Document**. In the message box, right-click and choose **Paste**. Click **SEND**. In **Outlook Web App**, in the top-right corner, click **Justin Muller**, then **Sign out**. Press **Alt-F4** to close the modern browser. ####   Task 2: Verify External User Sharing 1. On the Start page, click **Internet** **Explorer** to open a **modern browser** session. Browse to **mail.live.com**. In **Microsoft account**, and **Password**, enter the email address and password you used to set up the Office 365 subscription in Lab 1. Open the invitation email message from the **Microsoft Online Services Team**. Click the **Go to External User Share** link. Click **Microsoft account**. Verify that you can access the shared site collection. Click **Upload a document**. In the **Add a document** dialog box, click **Browse**. Click **Go up** and click **Go up** again. Click **Computer**, click **Allfiles (E:**), then click **Labfiles** and click **Lab08**. Click **Sales Proposal** and click **Open**. Click **OK**. In the **Add a document** dialog box, in the **Name** field, enter **Sales Proposal V2**, and then click **Check In**. Refresh the page and verify that your uploaded document is listed. In the top-right corner, click your name, and click **Sign Out**. Press **Ctrl-F4** to close the browser tab. Access your personal email account and open the email message from **Justin Muller** with the subject of **Shared Document**. Copy the URL in the email message into a new browser tab and press Enter. Verify that the document opens in **Word Web App**, and that it is in view-only mode, and that you cannot edit it. Close the browser tab. Press **Alt-F4** to close the modern browser session. **Results**: Heidi has configured external user access to external SharePoint sites in Office 365. ### Exercise 3: Configure Social and Collaboration Features Scenario Lucerne Publishing is now ready to implement internal social networking tools. This initiative is being implemented at the request of Jesse Wagner, the COO, who is anxious to connect employees and associates together and improve collaboration on time-sensitive projects. By having Yammer open, employees and associates can keep track of what's developing within a project without having to send email messages or reply to instant messages. Here Heidi sets up Yammer, configures version control, and sets quotas on OneDrive. The main tasks for this exercise are as follows: 1. Configure Yammer in SharePoint Online 2. Configure Versioning Settings for Co-authoring 3. Configure OneDrive for Business ####   Task 1: Configure Yammer in SharePoint Online 1. On the **Start** page, click Internet Explorer and browse to **https://login.microsoftonline.com**. Sign in as **hleitner@labXXXXX.o365ready.com**, (where XXXXX is your unique O365ready.com number) with a password of **Pa$$w0rd**. In the **Office 365 admin center**, click **Admin**, and then click **SharePoint**. In the **SharePoint admin center**, click **Settings**. Under **Enterprise Social Collaboration**, select **Use Yammer.com service**. Click **OK**. It will take some time for the change to take effect. In the **Office 365 admin center**, click **Admin** and click **Office 365**. Verify that the blue Office 365 navigation menu bar at the top of the page now displays **Yammer** instead of Newsfeed. > **Note**: If the menu bar has not yet updated to display Yammer, try refreshing the page or navigating to another page and then back to the Sites page again. Alternatively, if it is taking longer than expected, continue with the rest of the lab exercises and come back to verify this step later in the lab.** ** Click the **Get information on** **Yammer** link. A new Internet Explorer page appears, displaying the **Yammer Sign-up** page. Close the new Internet Explorer page. ####   Task 2: Configure Versioning Settings for Co-authoring 1. Press the Windows key and click **Desktop**. Switch to **Elisabeth Labrecque’s** session in Internet Explorer. In Internet Explorer, press Ctrl-T to open a new tab and browse to **https://lucernepublishing*XXXX*.sharepoint.com/sites/ExtShare**, (where XXXX is your unique Lucerne Publishing number). On the **External User Share** page, click **Documents**. Click the **LIBRARY** tab. In the **Settings** section, click **Library Settings**. Under **General Settings**, click **Versioning settings**. Under **Document Version History**, click **Create major versions**. Select the **Keep the following number of major versions** check box, and in the text box, type **5**. Under **Require Check Out**, click **Yes**. Click **OK**. In the top-right corner, click **Elisabeth Labrecque** and then click **Sign Out**. Press **Alt-F4** to close Internet Explorer. ####   Task 3: Configure OneDrive for Business 1. Press the Windows key and click **Internet** **Explorer** to go to **Heidi Leitner’s** session. In the **Office 365 admin center**, click **OneDrive**. On the **Welcome to OneDrive for Business** page, click **Next**. In the menu bar, click **Sync**. Click **Sync now**. On the **Did you mean to switch apps?** banner, click **Yes**. On the **Sign in** dialog box, enter **hleitner@labXXXXX.o365ready.com** (where XXXXX is your unique O365ready.com number), and click **Next**. Enter a password of **Pa$$w0rd**, and click **Sign in**. On the **Ready to sync your OneDrive for Business documents?** page, click **Sync Now**. Click **Show my files…** Verify your synchronized files are in a **OneDrive for Business** subfolder under your username. Close the OneDrive for Business folder. **Results**: Heidi has successfully configured Yammer, OneDrive for Business, and version control.
{ "content_hash": "bb248cd12a14536de78f30f924787ef3", "timestamp": "", "source": "github", "line_count": 461, "max_line_length": 583, "avg_line_length": 41.03253796095445, "alnum_prop": 0.7385282300697822, "repo_name": "MicrosoftLearning/20346C", "id": "5d67db582648633a548f681dcf28d0294fcc4324", "size": "18981", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Lab Docs/20346C_08.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package proj; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Arrays; import java.util.Comparator; import javax.swing.table.DefaultTableModel; import java.awt.Color; import javax.swing.JOptionPane; /** * * @author aaditya */ public class Recommend extends javax.swing.JFrame { /** * Creates new form Recommend */ public Recommend() { initComponents(); getContentPane().setBackground(Color.GRAY); } private static final String USERNAME="root"; private static final String PASSWORD="1234"; private static final String CONN_STRING="jdbc:mysql://localhost:3306/time_analyzer?autoReconnect=true&useSSL=false"; /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); Exp = new javax.swing.JComboBox(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); Desp = new javax.swing.JComboBox(); Testp = new javax.swing.JComboBox(); Codp = new javax.swing.JComboBox(); Manp = new javax.swing.JComboBox(); Alp = new javax.swing.JComboBox(); up = new javax.swing.JComboBox(); jLabel9 = new javax.swing.JLabel(); Numpep = new javax.swing.JTextField(); Start = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); RecomendTabel = new javax.swing.JTable(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); end = new javax.swing.JButton(); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel1.setForeground(new java.awt.Color(51, 0, 153)); jLabel1.setText("Experience Need"); Exp.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N Exp.setForeground(new java.awt.Color(102, 0, 102)); Exp.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Highly", "Yes ", "No", " " })); Exp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ExpActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("PilGi", 0, 24)); // NOI18N jLabel2.setForeground(new java.awt.Color(51, 0, 153)); jLabel2.setText("Type Information"); jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel3.setForeground(new java.awt.Color(51, 0, 153)); jLabel3.setText("Design"); jLabel4.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(51, 0, 153)); jLabel4.setText("Testing"); jLabel5.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel5.setForeground(new java.awt.Color(51, 0, 153)); jLabel5.setText("Coding"); jLabel6.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel6.setForeground(new java.awt.Color(51, 0, 153)); jLabel6.setText("Management"); jLabel7.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel7.setForeground(new java.awt.Color(51, 0, 153)); jLabel7.setText("Algorithms"); jLabel8.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel8.setForeground(new java.awt.Color(51, 0, 153)); jLabel8.setText("UI/UX"); Desp.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N Desp.setForeground(new java.awt.Color(102, 0, 102)); Desp.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Highly", "Yes", "No" })); Testp.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N Testp.setForeground(new java.awt.Color(102, 0, 102)); Testp.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Highly", "Yes", "No" })); Codp.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N Codp.setForeground(new java.awt.Color(102, 0, 102)); Codp.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Highly", "Yes", "No" })); Manp.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N Manp.setForeground(new java.awt.Color(102, 0, 102)); Manp.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Highly", "Yes", "No" })); Alp.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N Alp.setForeground(new java.awt.Color(102, 0, 102)); Alp.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Highly", "Yes", "No" })); up.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N up.setForeground(new java.awt.Color(102, 0, 102)); up.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Highly", "Yes", "No" })); jLabel9.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel9.setForeground(new java.awt.Color(51, 0, 153)); jLabel9.setText("Number Of People"); Start.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N Start.setForeground(new java.awt.Color(102, 0, 102)); Start.setText("Recommend"); Start.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { StartActionPerformed(evt); } }); RecomendTabel.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null}, {null}, {null}, {null} }, new String [] { "Recommendations(ID)" } )); jScrollPane2.setViewportView(RecomendTabel); jLabel10.setFont(new java.awt.Font("Papyrus", 0, 24)); // NOI18N jLabel10.setForeground(new java.awt.Color(0, 102, 102)); jLabel10.setText("ProMan16"); jLabel11.setFont(new java.awt.Font("Lucida Grande", 0, 8)); // NOI18N jLabel11.setText("TM"); jLabel12.setFont(new java.awt.Font("PilGi", 0, 24)); // NOI18N jLabel12.setForeground(new java.awt.Color(51, 0, 153)); jLabel12.setText("Select the best people for your project"); end.setText("Done"); end.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { endActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(105, 105, 105) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12))) .addGroup(layout.createSequentialGroup() .addGap(247, 247, 247) .addComponent(end))) .addContainerGap(90, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 412, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(49, 49, 49) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel7) .addComponent(jLabel8) .addComponent(jLabel9))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel11))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(Start) .addGap(33, 33, 33))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Desp, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Exp, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Testp, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Codp, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Manp, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Alp, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(up, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Numpep)))) .addGap(121, 121, 121)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel11) .addComponent(jLabel10)) .addGap(28, 28, 28) .addComponent(jLabel12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGap(64, 64, 64) .addComponent(Exp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(Desp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Testp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(Codp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(Manp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(Alp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(up, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Numpep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(0, 35, Short.MAX_VALUE) .addComponent(Start, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(end)) ); pack(); }// </editor-fold>//GEN-END:initComponents private float [][] feature_matrix = new float [1000][8]; private float [] new_matrix = new float [8]; private float[][] distance_matrix = new float[1000][2]; private int putvalue(String s){ switch (s){ case "Highly": return 5; case "Yes": return 1; case "No": return 0; } return 0; } private void normalize(int len){ float [] avg = new float[len]; for(int i=2;i<8;i++){ int n=0; avg[i]=0; for(int j=0;j<len;j++){ avg[i]+=this.feature_matrix[j][i]; if(this.feature_matrix[j][i]!=0) {n+=1;} } avg[i]/=n; //System.out.print(avg[i]+" "); } for(int i=0;i<len;i++){ for(int j=2;j<8;j++){ this.feature_matrix[i][j]/=avg[j]; } } } private void dist_calc(int len){ // take values from swing new_matrix[1]=(putvalue(Exp.getSelectedItem().toString()))/2; // weightage to this is less new_matrix[2]=putvalue(Desp.getSelectedItem().toString()); new_matrix[3]=putvalue(Testp.getSelectedItem().toString()); new_matrix[4]=putvalue(Codp.getSelectedItem().toString()); new_matrix[5]=putvalue(Manp.getSelectedItem().toString()); new_matrix[6]=putvalue(Alp.getSelectedItem().toString()); new_matrix[7]=putvalue(up.getSelectedItem().toString()); System.out.println("*******************************"); for(int i=0;i<7;i++) System.out.print(new_matrix[i]+" "); System.out.println(); for(int i=0;i<len;i++){ distance_matrix[i][0]=feature_matrix[i][0]; System.out.println(feature_matrix[i][0]); distance_matrix[i][1]=0; for(int j=1;j<8;j++){ distance_matrix[i][1]+=((feature_matrix[i][j]-new_matrix[j])*(feature_matrix[i][j]-new_matrix[j])); } System.out.println(distance_matrix[i][0]+" "+distance_matrix[i][1]+" "); } } private void knn(int len){ dist_calc(len); int k = Integer.parseInt(Numpep.getText()); // find the k least distances from distance matrix // find 1 first // sort to get k smallest distances float [] res_arr = new float[k]; for(int j=0;j<k;j++){ float dist=Float.MAX_VALUE; int index=0; for(int i=0;i<len;i++){ if(distance_matrix[i][1]<dist){ index=i; dist=(distance_matrix[i][1]); } } res_arr[j]=feature_matrix[index][0]; distance_matrix[index][1]=Float.MAX_VALUE; } //System.out.println(feature_matrix[index][0]); /*java.util.Arrays.sort(distance_matrix, new java.util.Comparator<float[]>() { public int compare(float[] a, float[] b) { return Float.compare(a[0], b[0]); } });*/ System.out.println("**********************************"); for (int i=0;i<k;i++){ System.out.print(" "+res_arr[i]); } DefaultTableModel model = (DefaultTableModel) RecomendTabel.getModel(); model.setNumRows(0); for(int j=0;j<k;j++){ Object[] row = {(int)res_arr[j]}; if(res_arr[j]==1016.0) break; model.addRow(row); } } private void StartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StartActionPerformed if(Numpep.getText().equals("0")||Numpep.getText().equals("")) JOptionPane.showMessageDialog(null,"Please Input the proper amount of people"); Connection conn = null; try{ conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWORD); Statement stmt =(Statement) conn.createStatement(); String print_name; int i=0; print_name = "select emp_id,sum(hours_worked) as tot_hours,Experience,type_id from date_log natural join Employee group by emp_id;"; ResultSet rs = stmt.executeQuery(print_name); while(rs.next()){ feature_matrix[i][0]=Float.parseFloat(rs.getString("emp_id")); feature_matrix[i][1]=Float.parseFloat(rs.getString("Experience")); int id=Integer.parseInt(rs.getString("type_id")); for(int x=2;x<8;x++){ if(x==(id+1)){ feature_matrix[i][x]=Float.parseFloat(rs.getString("tot_hours")); } else feature_matrix[i][x]=0; } i++; } //lets normalize normalize(i); /*for(int j=0;j<i;j++){ for(int x=0;x<8;x++){ System.out.print(feature_matrix[j][x]+" "); } System.out.println(); }*/ // System.out.println(putvalue(Exp.getSelectedItem().toString())); // lets calculate distance now knn(i); } catch(SQLException e){ System.out.println("Didnot happen"+e); } }//GEN-LAST:event_StartActionPerformed private void ExpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExpActionPerformed // TODO add your handling code here: }//GEN-LAST:event_ExpActionPerformed private void endActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_endActionPerformed // TODO add your handling code here: System.exit(0); }//GEN-LAST:event_endActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Recommend.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Recommend.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Recommend.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Recommend.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Recommend().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox Alp; private javax.swing.JComboBox Codp; private javax.swing.JComboBox Desp; private javax.swing.JComboBox Exp; private javax.swing.JComboBox Manp; private javax.swing.JTextField Numpep; private javax.swing.JTable RecomendTabel; private javax.swing.JButton Start; private javax.swing.JComboBox Testp; private javax.swing.JButton end; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable1; private javax.swing.JComboBox up; // End of variables declaration//GEN-END:variables }
{ "content_hash": "b02b4d62c7d5449e96594f471e73ec6a", "timestamp": "", "source": "github", "line_count": 513, "max_line_length": 167, "avg_line_length": 50.96296296296296, "alnum_prop": 0.5944002447980417, "repo_name": "AadityaJ/time_analyzer", "id": "471debab4dae58401a6748f30bb0ce5d8c95792e", "size": "26144", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Proj/src/proj/Recommend.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "93730" }, { "name": "Python", "bytes": "662" } ], "symlink_target": "" }
define([ 'spoon/View', 'jquery', 'doT', 'text!./assets/tmpl/issue_details.html', 'css!./assets/css/issue_details.css' ], function (View, $, doT, tmpl) { 'use strict'; return View.extend({ $name: 'IssueDetailsView', _element: 'div.issue-details', _template: doT.template(tmpl), /** * Sets the view state to loading. */ loading: function () { this._element.empty(); this._element.removeClass('error'); this._element.addClass('loading'); }, /** * Sets the view state to error. */ error: function () { this._element.html('Oops, something went wrong..'); this._element.removeClass('loading'); this._element.addClass('error'); }, /** * {@inheritDoc} */ render: function (data) { this._element.removeClass('loading error'); return View.prototype.render.call(this, data); } }); });
{ "content_hash": "53aed9fd193974430c1d4439a72a4021", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 63, "avg_line_length": 24.068181818181817, "alnum_prop": 0.4948064211520302, "repo_name": "IndigoUnited/spoonjs-guide-repo-browser", "id": "4dcfd34e0697d5b5bf78897a8551bc2e8cc4ecec", "size": "1059", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Content/Issues/IssueDetailsView.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2700" }, { "name": "HTML", "bytes": "4762" }, { "name": "JavaScript", "bytes": "53792" } ], "symlink_target": "" }
<?php include("./include/auth.php"); include("./include/top_header.php"); api_plugin_hook('console_before'); ?> <html> <head> <title>Google Chart Example: 2 Charts</title> <style> ul {list-style-type: none;} </style> <script src="https://www.google.com/jsapi"></script> <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script src="jquery.csv-0.71.js"></script> <script> // load the visualization library from Google and set a listener google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { // grab the first CSV $.get("allNEW.csv", function(csvString) { // transform the CSV string into a 2-dimensional array var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar}); // use arrayData to load the select elements with the appropriate options for (var i = 0; i < arrayData[0].length; i++) { // this adds the given option to both select elements $("select.chart").append("<option value='" + i + "'>" + arrayData[0][i] + "</option>"); } // set the default selection $("#domain option[value='0']").attr("selected","selected"); $("#range option[value='1']").attr("selected","selected"); // this new DataTable object holds all the data var data = new google.visualization.arrayToDataTable(arrayData); // this view can select a subset of the data at a time var view = new google.visualization.DataView(data); view.setColumns([{calc:stringID, type: "string"},1,2,3]); // this function returns the first column values as strings (by row) function stringID(dataTable, rowNum){ // return dataTable.getValue(rowNum, 0).toString(); // return an empty string instead to avoid the bubble labels return ""; } var options = { title: "ACE Data", hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max}, vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max}, bubble: {stroke: "transparent", opacity: 0.2}, colorAxis: {colors:['blue','red']}, sizeAxis:{minSize:1}, sizeAxis:{maxSize:5}, }; var chart = new google.visualization.BubbleChart(document.getElementById('chart')); chart.draw(view, options); // set listener for the update button $("select").change(function(){ // determine selected domain and range var domain = +$("#domain option:selected").val(); var range = +$("#range option:selected").val(); var color = +$("#color option:selected").val(); var size = +$("#size option:selected").val(); //var size = 1; // update the view view.setColumns([{calc:stringID, type: "string", label: "Household ID"},domain,range,color,size]); // update the options options.hAxis.title = data.getColumnLabel(domain); options.hAxis.minValue = data.getColumnRange(domain).min; options.hAxis.maxValue = data.getColumnRange(domain).max; options.vAxis.title = data.getColumnLabel(range); options.vAxis.minValue = data.getColumnRange(range).min; options.vAxis.maxValue = data.getColumnRange(range).max; options.bubble = {stroke: "transparent", opacity: 0.2}; options.colorAxis = {colors:['blue','red']}; //options.sizeAxis.maxSize={10}; // update the chart chart.draw(view, options); }); }); } </script> <style> //div //{ //border:2px solid; //padding:10px 40px; //width:600px; //resize:both; //overflow:auto; //} </style> </head> <body> <div style="float:left;"> <div id="chart" style="width:850px; height:650px; resize:both; overflow:auto;"> </div> <ul> <li> Y-Axis <select class="chart" id="range"></select> </li> <li> X-Axis <select class="chart" id="domain"></select> </li> <li> Color <select class="chart" id="color"></select> </li> <li> Size <select class="chart" id="size"></select> </li> </ul> </div> </body> </html> <?php api_plugin_hook('console_after'); include("./include/bottom_footer.php"); ?>
{ "content_hash": "a73096a001441710cb0bdb98a161e510", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 130, "avg_line_length": 30.372670807453417, "alnum_prop": 0.5486707566462168, "repo_name": "AtanasAtanasov/amaterasu", "id": "96284d1cb3f7b273cf091aff5ffc8e06f8a171c9", "size": "6435", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cacti/index.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "176037" }, { "name": "JavaScript", "bytes": "7255707" }, { "name": "PHP", "bytes": "2139735" }, { "name": "Perl", "bytes": "4971" }, { "name": "Shell", "bytes": "92" } ], "symlink_target": "" }
/* * * * * MIT Licensed * */ var app = angular.module('IdeaBoard',['akoenig.deckgrid','btford.modal','ngSanitize','ngRoute']); app.factory('myModal', function (btfModal) { return btfModal({ controller: 'MyModalCtrl', controllerAs: 'modal', templateUrl: 'ideamodal.html' }); }); app.factory('myModalBoard', function (btfModal) { return btfModal({ controller: 'MyModalBoardCtrl', controllerAs: 'modal', templateUrl: 'ideaboardmodal.html' }); }); app.factory('IdeasFactory',function($http,$filter,$q){ var factory = {}; var ideaScope = {}; factory.getScope = function(){ return ideaScope; }; factory.setScope = function(scope){ ideaScope = scope; }; factory.getAllIdeas = function(hackathon){ var promise = $http.get("/api/"+hackathon) .then(function(response){ return response.data; }); return promise; }; factory.postIdea = function(data){ var promise = $http.post('/idea', data); return promise; }; return factory; }); app.factory('IdeaBoardFactory',function($http,$filter,$q){ var factory = {}; var ideaBoardScope = {}; factory.getScope = function(){ return ideaBoardScope; }; factory.setScope = function(scope){ ideaBoardScope = scope; }; factory.getAllIdeaBoards = function(){ var promise = $http.get("/ideaboard") .then(function(response){ return response.data; }); return promise; }; factory.postIdeaBoard = function(data){ var promise = $http.post('/ideaboard', data); return promise; }; return factory; }); app.config(['$routeProvider',function($routeProvider){ $routeProvider .when('/:param',{ templateUrl: '/views/board.html', controller: 'HomeControllerBoard' }) .when('/',{ templateUrl: '/views/boardhub.html', controller: 'HomeController' }) .otherwise({redirectTo: '/'}); // $locationProvider.html5Mode( true); }]); // typically you'll inject the modal service into its own // controller so that the modal can close itself app.controller('MyModalCtrl', function ($scope,IdeasFactory,myModal,$location) { $scope.addIdea = function(){ IdeasFactory.postIdea({ title: $scope.title, description: $scope.description, user_id: $scope.user_id, email: $scope.email, ideaboardName: decodeURI($location.url().split('\/')[1]) }).success(function(d){ IdeasFactory.getScope().FetchAllIdeas($location.url().split('\/')[1]); $scope.closeMe(); // $scope.toggle(); }).error(function(d){ $scope.error = d.fail; }); }; $scope.closeMe = myModal.deactivate; $scope.error = false; }); app.controller('MyModalBoardCtrl', function ($scope,IdeaBoardFactory,myModalBoard) { $scope.addIdeaBoard = function(){ IdeaBoardFactory.postIdeaBoard({ ideaboardName: $scope.ideaboardName, description: $scope.description, website: $scope.website }).success(function(d){ IdeaBoardFactory.getScope().FetchAllIdeaBoards(); $scope.closeMe(); // $scope.toggle(); }).error(function(d){ $scope.error = d.fail; }); }; $scope.closeMe = myModalBoard.deactivate; $scope.error = false; }); app.controller('HomeController', [ '$scope','$http','IdeasFactory','myModal', '$location', function initialize ($scope,$http,IdeasFactory,myModal,$location) { 'use strict'; $scope.ideas = []; // $scope.ideaboards = []; IdeasFactory.setScope($scope); // IdeaBoardFactory.setScope($scope); $scope.FetchAllIdeas = function(){ IdeasFactory.getAllIdeas($location.url().split('\/')[1]).then(function(d){ if(!d){ return; }else{ $scope.ideas = d; } }); }; // $scope.FetchAllIdeaBoards = function(){ // IdeaBoardFactory.getAllIdeaBoards().then(function(d){ // if(!d){ // return; // }else{ // $scope.ideaboards = d; // } // }); // }; $scope.FetchAllIdeas(); $scope.boardName = decodeURI($location.url().split('\/')[1]); $scope.toggle = myModal.activate; } ]); app.controller('HomeControllerBoard', [ '$scope','$http','IdeaBoardFactory','myModalBoard', function initialize ($scope,$http,IdeaBoardFactory,myModalBoard) { 'use strict'; $scope.ideaboards = []; IdeaBoardFactory.setScope($scope); $scope.FetchAllIdeaBoards = function(){ IdeaBoardFactory.getAllIdeaBoards().then(function(d){ if(!d){ return; }else{ $scope.ideaboards = d;//d.map(function(element) { return element.getAttribute('name'); }); } }); }; $scope.FetchAllIdeaBoards(); $scope.toggle = myModalBoard.activate; } ]);
{ "content_hash": "a09e484a82f2ea3af6e7697936e8f54f", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 110, "avg_line_length": 24.476635514018692, "alnum_prop": 0.5607101947308133, "repo_name": "tdjackey/ideahub", "id": "3f487fe1b16d55cc8e3f622bb44abe831f572da8", "size": "5238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/controllers/home.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "536" }, { "name": "JavaScript", "bytes": "16031" } ], "symlink_target": "" }
<!--docs: title: "Ink" layout: detail section: components excerpt: "The Ink component provides a radial action in the form of a visual ripple of ink expanding outward from the user's touch." iconId: ripple path: /catalog/ink/ api_doc_root: true --> # Ink <div class="article__asset article__asset--screenshot"> <img src="docs/assets/ink.png" alt="Ink" width="375"> </div> The Ink component provides a radial action in the form of a visual ripple of ink expanding outward from the user's touch. ## Design & API Documentation <ul class="icon-list"> <li class="icon-list-item icon-list-item--spec"><a href="https://material.io/guidelines/animation/responsive-interaction.html#responsive-interaction-radial-action">Material Design guidelines: Radial Action</a></li> <li class="icon-list-item icon-list-item--link"><a href="https://material.io/components/ios/catalog/ink/api-docs/Classes/MDCInkGestureRecognizer.html">API: MDCInkGestureRecognizer</a></li> <li class="icon-list-item icon-list-item--link"><a href="https://material.io/components/ios/catalog/ink/api-docs/Classes/MDCInkTouchController.html">API: MDCInkTouchController</a></li> <li class="icon-list-item icon-list-item--link"><a href="https://material.io/components/ios/catalog/ink/api-docs/Classes/MDCInkView.html">API: MDCInkView</a></li> </ul> - - - ## Installation ### Requirements - Xcode 7.0 or higher. - iOS SDK version 7.0 or higher. ### Installation with CocoaPods To add this component to your Xcode project using CocoaPods, add the following to your `Podfile`: ``` bash pod 'MaterialComponents/Ink' ``` <!--{: .code-renderer.code-renderer--install }--> Then, run the following command: ``` bash pod install ``` - - - ## Usage ### Importing Before using Ink, you'll need to import it: <!--<div class="material-code-render" markdown="1">--> #### Swift ``` swift import MaterialComponents ``` #### Objective-C ``` objc #import "MaterialInk.h" ``` <!--</div>--> The Ink component exposes two interfaces that you can use to add material-like feedback to the user: 1. `MDCInkView` is a subclass of `UIView` that draws and animates ink ripples and can be placed anywhere in your view hierarchy. 2. `MDCInkTouchController` bundles an `MDCInkView` instance with a `UITapGestureRecognizer` instance to conveniently drive the ink ripples from the user's touches. ### MDCInkTouchController The simplest method of using ink in your views is to use a `MDCInkTouchController`: <!--<div class="material-code-render" markdown="1">--> #### Swift ``` swift let myButton = UIButton(type: .system) myButton.setTitle("Tap Me", for: .normal) let inkTouchController = MDCInkTouchController(view: myButton) inkTouchController?.addInkView() ``` #### Objective-C ``` objc UIButton *myButton = [UIButton buttonWithType:UIButtonTypeSystem]; [myButton setTitle:@"Tap me" forState:UIControlStateNormal]; MDCInkTouchController *inkTouchController = [[MDCInkTouchController alloc] initWithView:myButton]; [inkTouchController addInkView]; ``` <!--</div>--> The `MDCInkTouchControllerDelegate` gives you control over aspects of the ink/touch relationship, such as how the ink view is created, where it is inserted in view hierarchy, etc. For example, to temporarily disable ink touches, the following code uses the delegate's `inkTouchController:shouldProcessInkTouchesAtTouchLocation:` method: <!--<div class="material-code-render" markdown="1">--> #### Swift ``` swift class MyDelegate: NSObject, MDCInkTouchControllerDelegate { func inkTouchController(_ inkTouchController: MDCInkTouchController, shouldProcessInkTouchesAtTouchLocation location: CGPoint) -> Bool { // Determine if we want to display the ink return true } } ... let myButton = UIButton(type: .system) myButton.setTitle("Tap Me", for: .normal) let myDelegate = MyDelegate() let inkTouchController = MDCInkTouchController(view: myButton) inkTouchController?.delegate = myDelegate inkTouchController?.addInkView() ``` #### Objective-C ``` objc @interface MyDelegate: NSObject <MDCInkTouchControllerDelegate> @end @implementation MyDelegate - (BOOL)inkTouchController:(MDCInkTouchController *)inkTouchController shouldProcessInkTouchesAtTouchLocation:(CGPoint)location { return YES; } @end ... UIButton *myButton = [UIButton buttonWithType:UIButtonTypeSystem]; [myButton setTitle:@"Tap me" forState:UIControlStateNormal]; MyDelegate *myDelegate = [[MyDelegate alloc] init]; MDCInkTouchController *inkTouchController = [[MDCInkTouchController alloc] initWithView:myButton]; inkTouchController.delegate = myDelegate; [inkTouchController addInkView]; ``` <!--</div>--> **NOTE:** The ink touch controller does not keep a strong reference to the view to which it is attaching the ink view. An easy way to prevent the ink touch controller from being deallocated prematurely is to make it a property of a view controller (like in these examples.) ### MDCInkView Alternatively, you can use MCDInkView directly to display ink ripples using your own touch processing: <!--<div class="material-code-render" markdown="1">--> #### Swift ``` swift let myCustomView = MyCustomView(frame: CGRect.zero) let inkView = MDCInkView() inkView.inkColor = UIColor.red myCustomView.addSubview(inkView) ... // When the touches begin, there is one animation inkView.startTouchBeganAnimation(at: touchPoint, completion: nil) ... // When the touches end, there is another animation inkView.startTouchEndedAnimation(at: touchPoint, completion: nil) ``` #### Objective-C ``` objc MyCustomView *myCustomView = [[MyCustomView alloc] initWithFrame:CGRectZero]; MDCInkView *inkView = [MDCInkView new]; inkView.inkColor = [UIColor redColor]; [myCustomView addSubview:inkView]; ... // When the touches begin, there is one animation [inkView startTouchBeganAnimationAtPoint:touchPoint completion:nil]; ... // When the touches end, there is another animation [inkView startTouchEndedAnimationAtPoint:touchPoint completion:nil]; ``` <!--</div>-->
{ "content_hash": "c506a33a52cf0af0845ba87b34435f76", "timestamp": "", "source": "github", "line_count": 202, "max_line_length": 216, "avg_line_length": 29.628712871287128, "alnum_prop": 0.7557226399331662, "repo_name": "Eccelor/material-components-ios", "id": "e5a387046b5765575f31f4f6dad9a3d55b8918b4", "size": "5985", "binary": false, "copies": "1", "ref": "refs/heads/stable", "path": "components/Ink/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "4954" }, { "name": "Objective-C", "bytes": "2608903" }, { "name": "Python", "bytes": "19000" }, { "name": "Ruby", "bytes": "30906" }, { "name": "Shell", "bytes": "63255" }, { "name": "Swift", "bytes": "311607" } ], "symlink_target": "" }
@interface MKPresentationPolicyHandler : MKCallbackHandler @property (readonly, strong, nonatomic) MKPresentationPolicy *presentationPolicy; + (instancetype)handlerWithPresentationPolicy:(MKPresentationPolicy *)policy; @end
{ "content_hash": "17c8ebec34600fd2c150742f4d4c721f", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 81, "avg_line_length": 32.42857142857143, "alnum_prop": 0.8458149779735683, "repo_name": "cneuwirt/MirukenCocoa", "id": "663e63630b6d7733daa54c361abfe86bcd4c85ac", "size": "447", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Miruken/Cocoa/MKPresentationPolicyHandler.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "30592" }, { "name": "C++", "bytes": "2173" }, { "name": "Objective-C", "bytes": "640152" }, { "name": "Ruby", "bytes": "195" } ], "symlink_target": "" }
package edu.isi.pegasus.planner.code.generator.condor.style; import edu.isi.pegasus.common.logging.LogManager; import edu.isi.pegasus.planner.catalog.site.classes.GridGateway; import edu.isi.pegasus.planner.catalog.site.classes.SiteCatalogEntry; import edu.isi.pegasus.planner.classes.Job; import edu.isi.pegasus.planner.code.generator.condor.CondorQuoteParser; import edu.isi.pegasus.planner.code.generator.condor.CondorQuoteParserException; import edu.isi.pegasus.planner.code.generator.condor.CondorStyleException; /** * Enables a job to be directly submitted to the condor pool of which the submit host is a part of. * This style is applied for jobs to be run - on the submit host in the scheduler universe (local * pool execution) - on the local condor pool of which the submit host is a part of * * @author Karan Vahi * @version $Revision$ */ public class CondorC extends Condor { /** The constant for the remote universe key. */ public static final String REMOTE_UNIVERSE_KEY = edu.isi.pegasus.planner.namespace.Condor.REMOTE_UNIVERSE_KEY; /** * The name of the key that designates that files should be transferred via Condor File Transfer * mechanism. */ public static final String SHOULD_TRANSFER_FILES_KEY = edu.isi.pegasus.planner.namespace.Condor.SHOULD_TRANSFER_FILES_KEY; /** * The corresponding remote kye name that designates that files should be transferred via Condor * File Transfer mechanism. */ public static final String REMOTE_SHOULD_TRANSFER_FILES_KEY = edu.isi.pegasus.planner.namespace.Condor.REMOTE_SHOULD_TRANSFER_FILES_KEY; /** The name of key that designates when to transfer output. */ public static final String WHEN_TO_TRANSFER_OUTPUT_KEY = edu.isi.pegasus.planner.namespace.Condor.WHEN_TO_TRANSFER_OUTPUT_KEY; /** The corresponding name of the remote key that designated when to transfer output. */ public static final String REMOTE_WHEN_TO_TRANSFER_OUTPUT_KEY = edu.isi.pegasus.planner.namespace.Condor.REMOTE_WHEN_TO_TRANSFER_OUTPUT_KEY; /** The key that designates the collector associated with the job */ public static final String COLLECTOR_KEY = edu.isi.pegasus.planner.namespace.Condor.COLLECTOR_KEY; /** The key that designates the collector associated with the job */ public static final String GRID_RESOURCE_KEY = edu.isi.pegasus.planner.namespace.Condor.GRID_RESOURCE_KEY; /** The name of the style being implemented. */ public static final String STYLE_NAME = "CondorC"; /** The default constructor. */ public CondorC() { super(); } /** * Applies the CondorC style to the job. * * @param job the job on which the style needs to be applied. * @throws CondorStyleException in case of any error occuring code generation. */ public void apply(Job job) throws CondorStyleException { // lets apply the Condor style first and then make // some modifications super.apply(job); // the job universe key is translated to +remote_universe String remoteUniverse = (String) job.condorVariables.removeKey(Condor.UNIVERSE_KEY); job.condorVariables.construct(CondorC.REMOTE_UNIVERSE_KEY, remoteUniverse); // the universe for CondorC is always grid job.condorVariables.construct(CondorC.UNIVERSE_KEY, "grid"); // construct the grid_resource for the job String gridResource = constructGridResource(job); job.condorVariables.construct(CondorC.GRID_RESOURCE_KEY, gridResource.toString()); // check if s_t_f and w_t_f keys are associated. try { String s_t_f = (String) job.condorVariables.removeKey(CondorC.SHOULD_TRANSFER_FILES_KEY); if (s_t_f != null) { // convert to remote key and quote it job.condorVariables.construct( CondorC.REMOTE_SHOULD_TRANSFER_FILES_KEY, CondorQuoteParser.quote(s_t_f, true)); } else { // create the default value job.condorVariables.construct(CondorC.REMOTE_SHOULD_TRANSFER_FILES_KEY, "YES"); } String w_t_f = (String) job.condorVariables.removeKey(CondorC.WHEN_TO_TRANSFER_OUTPUT_KEY); if (s_t_f != null) { // convert to remote key and quote it job.condorVariables.construct( CondorC.REMOTE_WHEN_TO_TRANSFER_OUTPUT_KEY, CondorQuoteParser.quote(w_t_f, true)); } else { job.condorVariables.construct( CondorC.REMOTE_WHEN_TO_TRANSFER_OUTPUT_KEY, "ON_EXIT"); } // so convert that to remote_initialdir String dir = job.getDirectory(); if (dir != null) { // for Condor C we only use remote_initialdir job.condorVariables.construct("remote_initialdir", dir); } } catch (CondorQuoteParserException ex) { throw new CondorStyleException("Condor Quote Exception", ex); } } /** * Constructs the grid_resource entry for the job. The grid resource is a tuple consisting of * three fields. * * <p>The first field is the grid type, which is condor. The second field is the name of the * remote condor_schedd daemon. The third field is the name of the remote pool's * condor_collector. * * @param job the job * @return the grid_resource entry * @throws CondorStyleException in case of any error occuring code generation. */ protected String constructGridResource(Job job) throws CondorStyleException { StringBuffer gridResource = new StringBuffer(); // first field is always condor gridResource.append("condor").append(" "); SiteCatalogEntry s = mSiteStore.lookup(job.getSiteHandle()); GridGateway g = s.selectGridGateway(job.getGridGatewayJobType()); String contact = (g == null) ? null : g.getContact(); if (contact == null) { StringBuffer error = new StringBuffer(); error.append("Grid Gateway not specified for site in site catalog ") .append(job.getSiteHandle()); throw new CondorStyleException(error.toString()); } gridResource.append(g.getContact()).append(" "); // the job should have the collector key associated String collector = (String) job.condorVariables.removeKey(CondorC.COLLECTOR_KEY); if (collector == null) { // we assume that collector is running at same place where remote_schedd // is running StringBuffer message = new StringBuffer(); message.append("Condor Profile ") .append(CondorC.COLLECTOR_KEY) .append(" not associated with job ") .append(job.getID()); mLogger.log(message.toString(), LogManager.TRACE_MESSAGE_LEVEL); collector = contact; } gridResource.append(collector); return gridResource.toString(); } }
{ "content_hash": "fe3209104bc135c55a3aaeb8cb5de402", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 100, "avg_line_length": 42.45348837209303, "alnum_prop": 0.6458504519309778, "repo_name": "pegasus-isi/pegasus", "id": "13afac4aa20021362386c50ade50ba41fecca53f", "size": "7923", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/edu/isi/pegasus/planner/code/generator/condor/style/CondorC.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "451637" }, { "name": "C++", "bytes": "241564" }, { "name": "CSS", "bytes": "3270" }, { "name": "Common Workflow Language", "bytes": "2464" }, { "name": "Dockerfile", "bytes": "3830" }, { "name": "HTML", "bytes": "95902" }, { "name": "Java", "bytes": "8737551" }, { "name": "JavaScript", "bytes": "25592" }, { "name": "Jupyter Notebook", "bytes": "2576298" }, { "name": "Makefile", "bytes": "9884" }, { "name": "PHP", "bytes": "32852" }, { "name": "Perl", "bytes": "90905" }, { "name": "Python", "bytes": "3039866" }, { "name": "R", "bytes": "105082" }, { "name": "Roff", "bytes": "36" }, { "name": "Shell", "bytes": "420738" }, { "name": "Singularity", "bytes": "446" } ], "symlink_target": "" }
/* This is an include file for windows.h with the SDL build settings */ #ifndef _INCLUDED_WINDOWS_H #define _INCLUDED_WINDOWS_H #if defined(__WIN32__) #define WIN32_LEAN_AND_MEAN #define STRICT #ifndef UNICODE #define UNICODE 1 #endif #undef _WIN32_WINNT #define _WIN32_WINNT 0x501 /* Need 0x410 for AlphaBlend() and 0x500 for EnumDisplayDevices(), 0x501 for raw input */ #endif #include <windows.h> #include <basetyps.h> /* for REFIID with broken mingw.org headers */ #include "SDL_rect.h" /* Routines to convert from UTF8 to native Windows text */ #define WIN_StringToUTF8W(S) SDL_iconv_string("UTF-8", "UTF-16LE", (const char *)(S), (SDL_wcslen(S)+1)*sizeof(WCHAR)) #define WIN_UTF8ToStringW(S) (WCHAR *)SDL_iconv_string("UTF-16LE", "UTF-8", (const char *)(S), SDL_strlen(S)+1) /* !!! FIXME: UTF8ToString() can just be a SDL_strdup() here. */ #define WIN_StringToUTF8A(S) SDL_iconv_string("UTF-8", "ASCII", (const char *)(S), (SDL_strlen(S)+1)) #define WIN_UTF8ToStringA(S) SDL_iconv_string("ASCII", "UTF-8", (const char *)(S), SDL_strlen(S)+1) #if UNICODE #define WIN_StringToUTF8 WIN_StringToUTF8W #define WIN_UTF8ToString WIN_UTF8ToStringW #define SDL_tcslen SDL_wcslen #define SDL_tcsstr SDL_wcsstr #else #define WIN_StringToUTF8 WIN_StringToUTF8A #define WIN_UTF8ToString WIN_UTF8ToStringA #define SDL_tcslen SDL_strlen #define SDL_tcsstr SDL_strstr #endif /* Sets an error message based on a given HRESULT */ extern int WIN_SetErrorFromHRESULT(const char *prefix, HRESULT hr); /* Sets an error message based on GetLastError(). Always return -1. */ extern int WIN_SetError(const char *prefix); #if !defined(__WINRT__) /* Load a function from combase.dll */ void *WIN_LoadComBaseFunction(const char *name); #endif /* Wrap up the oddities of CoInitialize() into a common function. */ extern HRESULT WIN_CoInitialize(void); extern void WIN_CoUninitialize(void); /* Wrap up the oddities of RoInitialize() into a common function. */ extern HRESULT WIN_RoInitialize(void); extern void WIN_RoUninitialize(void); /* Returns SDL_TRUE if we're running on Windows Vista and newer */ extern BOOL WIN_IsWindowsVistaOrGreater(void); /* Returns SDL_TRUE if we're running on Windows 7 and newer */ extern BOOL WIN_IsWindows7OrGreater(void); /* Returns SDL_TRUE if we're running on Windows 8 and newer */ extern BOOL WIN_IsWindows8OrGreater(void); /* You need to SDL_free() the result of this call. */ extern char *WIN_LookupAudioDeviceName(const WCHAR *name, const GUID *guid); /* Checks to see if two GUID are the same. */ extern BOOL WIN_IsEqualGUID(const GUID * a, const GUID * b); extern BOOL WIN_IsEqualIID(REFIID a, REFIID b); /* Convert between SDL_rect and RECT */ extern void WIN_RECTToRect(const RECT *winrect, SDL_Rect *sdlrect); extern void WIN_RectToRECT(const SDL_Rect *sdlrect, RECT *winrect); #endif /* _INCLUDED_WINDOWS_H */ /* vi: set ts=4 sw=4 expandtab: */
{ "content_hash": "7b26572c738c73aa451fd78e2ffd3d95", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 119, "avg_line_length": 35.292682926829265, "alnum_prop": 0.7328956461644782, "repo_name": "Jonazan2/PatBoy", "id": "917a8256f41a73e48076d2653fc806994b12bfdf", "size": "3832", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "libs/SDL2/src/core/windows/SDL_windows.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "32239" }, { "name": "Batchfile", "bytes": "58" }, { "name": "C", "bytes": "17567471" }, { "name": "C++", "bytes": "7869986" }, { "name": "CMake", "bytes": "36698" }, { "name": "Lua", "bytes": "5792" }, { "name": "M4", "bytes": "24713" }, { "name": "Makefile", "bytes": "6876" }, { "name": "Metal", "bytes": "3691" }, { "name": "Objective-C", "bytes": "818978" }, { "name": "Perl", "bytes": "24979" }, { "name": "Python", "bytes": "3061" }, { "name": "Shell", "bytes": "4472" } ], "symlink_target": "" }
<resources> <style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. --> <item name="colorPrimary">@color/twitter_blue</item> </style> <!-- Application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="colorPrimary">@color/twitter_blue</item> </style> <style name="twitter" parent="Theme.AppCompat.Light.NoActionBar" > <item name="colorPrimary">@color/twitter_blue</item> <item name="android:textColorPrimary">@android:color/white</item> </style> </resources>
{ "content_hash": "b96b917684b1e451542fd68291792661", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 76, "avg_line_length": 30.73076923076923, "alnum_prop": 0.6470588235294118, "repo_name": "EmilyRoth/MySimpleTweets", "id": "510fe841ac9c807ee01dc02a2d56abcc5cf1602e", "size": "799", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values/styles.xml", "mode": "33261", "license": "mit", "language": [ { "name": "Java", "bytes": "55091" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "03eac29510390c2c10be787b4d77e92e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "6503cd5005bbb36e02974e3e3a8297e937eaf9d6", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Robiquetia/Robiquetia bertholdii/ Syn. Saccolabium kajewskii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!--login modal--> <div id="loginModal" class="modal show" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button> <h1 class="text-center">Enter Pass Phrase</h1> </div> <div class="modal-body"> <form class="form col-md-12 center-block unlock"> <div class="form-group"> <label for="password" class="control-label">Pass Phrase:</label> <input name="password" type="password" class="passphrase form-control input-lg" placeholder="Pass Phrase"> </div> <div class="form-group"> <button class="btn btn-primary btn-lg btn-block">Unlock</button> <span class="pull-right"><a href="#" onclick="$('.container').load('newaccount.html');" class="newaccount">New Account</a></span><span><a class="login" onclick="$('.container').load('login.html');"href="#">Unlock Account</a></span> </div> </form> </div> <div class="modal-footer"> </div> </div> </div> </div> <script type="text/javascript"> $(".unlock").submit(function(event) { event.preventDefault(); //do cool things var phr = $(".passphrase").val(); APIRequest("initialize","secretPhrase="+phr, function(sc) { window.location = "../base/index.html"; }); }); </script>
{ "content_hash": "9db3095354ce0d5941594a66f82295a6", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 245, "avg_line_length": 34.857142857142854, "alnum_prop": 0.5949453551912568, "repo_name": "jonesnxt/jaywallet", "id": "3867948a33fd534c81e0b30b78bf66f7be0c6114", "size": "1464", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/startup/passphrase.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "124561" }, { "name": "Java", "bytes": "144911" }, { "name": "JavaScript", "bytes": "886308" } ], "symlink_target": "" }
using FluentMigrator; namespace Azimuth.Migrations { [Migration(201408131104)] public class Migration_201408131104_CreateUnauthorizedListenersTable : Migration { public override void Up() { Create.Table("UnauthorizedListeners") .WithColumn("Id").AsInt64().NotNullable().Identity().PrimaryKey() .WithColumn("PlaylistId").AsInt64().NotNullable().ForeignKey("Playlists", "PlaylistsId") .WithColumn("Amount").AsInt64().NotNullable(); } public override void Down() { Delete.Table("UnauthorizedListeners"); } } }
{ "content_hash": "316b80dbdfd6d47343dafa0c92099afd", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 104, "avg_line_length": 30.761904761904763, "alnum_prop": 0.6114551083591331, "repo_name": "B1naryStudio/Azimuth", "id": "f4298e4f4e8b91552a30a2c205da3f7a3f299298", "size": "648", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Azimuth.Migrations/Migrations/Migration_201408131104_CreateUnauthorizedListenersTable.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "98" }, { "name": "C#", "bytes": "481034" }, { "name": "CSS", "bytes": "85750" }, { "name": "JavaScript", "bytes": "402357" } ], "symlink_target": "" }
/*! * Material */ if (typeof jQuery === 'undefined') { throw new Error('Material\'s JavaScript requires jQuery') } +function ($) { var version = $.fn.jquery.split(' ')[0].split('.') if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] >= 4)) { throw new Error('Material\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0') } }(jQuery); +function ($) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /*! * floating label: * when a user engages with the text input field, * the floating inline labels move to float above the field */ var FloatingLabel = function ($) { // constants >>> var DATA_API_KEY = '.data-api'; var DATA_KEY = 'md.floatinglabel'; var EVENT_KEY = '.' + DATA_KEY; var NAME = 'floatinglabel'; var NO_CONFLICT = $.fn[NAME]; var ClassName = { IS_FOCUSED: 'is-focused', HAS_VALUE: 'has-value' }; var Event = { CHANGE: 'change' + EVENT_KEY, FOCUSIN: 'focusin' + EVENT_KEY, FOCUSOUT: 'focusout' + EVENT_KEY }; var Selector = { DATA_PARENT: '.floating-label', DATA_TOGGLE: '.floating-label .form-control' }; // <<< constants var FloatingLabel = function () { function FloatingLabel(element) { _classCallCheck(this, FloatingLabel); this._element = element; } _createClass(FloatingLabel, [{ key: 'change', value: function change(relatedTarget) { if ($(this._element).val() || $(this._element).is('select') && $('option:first-child', $(this._element)).html().replace(' ', '') !== '') { $(relatedTarget).addClass(ClassName.HAS_VALUE); } else { $(relatedTarget).removeClass(ClassName.HAS_VALUE); } } }, { key: 'focusin', value: function focusin(relatedTarget) { $(relatedTarget).addClass(ClassName.IS_FOCUSED); } }, { key: 'focusout', value: function focusout(relatedTarget) { $(relatedTarget).removeClass(ClassName.IS_FOCUSED); } }], [{ key: '_jQueryInterface', value: function _jQueryInterface(event) { return this.each(function () { var data = $(this).data(DATA_KEY); var _event = event ? event : 'change'; if (!data) { data = new FloatingLabel(this); $(this).data(DATA_KEY, data); } if (typeof _event === 'string') { if (data[_event] === undefined) { throw new Error('No method named "' + _event + '"'); } data[_event]($(this).closest(Selector.DATA_PARENT)); } }); } }]); return FloatingLabel; }(); $(document).on(Event.CHANGE + ' ' + Event.FOCUSIN + ' ' + Event.FOCUSOUT, Selector.DATA_TOGGLE, function (event) { var data = $(this).data(DATA_KEY); FloatingLabel._jQueryInterface.call($(this), event.type); }); $.fn[NAME] = FloatingLabel._jQueryInterface; $.fn[NAME].Constructor = FloatingLabel; $.fn[NAME].noConflict = function () { $.fn[NAME] = NO_CONFLICT; return FloatingLabel._jQueryInterface; }; return FloatingLabel; }(jQuery); /*! * navigation drawer * based on bootstrap's (v4.0.0-alpha.6) modal.js */ var NavDrawer = function ($) { // constants >>> var DATA_API_KEY = '.data-api'; var DATA_KEY = 'md.navdrawer'; var EVENT_KEY = '.' + DATA_KEY; var NAME = 'navdrawer'; var NO_CONFLICT = $.fn[NAME]; var TRANSITION_DURATION = 375; var TRANSITION_DURATION_BACKDROP = 225; var ClassName = { BACKDROP: 'navdrawer-backdrop', OPEN: 'navdrawer-open', SHOW: 'show' }; var Default = { breakpoint: 1280, keyboard: true, show: true, type: 'default' }; var DefaultType = { keyboard: 'boolean', show: 'boolean', type: 'string' }; var Event = { CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY, CLICK_DISMISS: 'click.dismiss' + EVENT_KEY, FOCUSIN: 'focusin' + EVENT_KEY, HIDDEN: 'hidden' + EVENT_KEY, HIDE: 'hide' + EVENT_KEY, KEYDOWN_DISMISS: 'keydown.dismiss' + EVENT_KEY, MOUSEDOWN_DISMISS: 'mousedown.dismiss' + EVENT_KEY, MOUSEUP_DISMISS: 'mouseup.dismiss' + EVENT_KEY, SHOW: 'show' + EVENT_KEY, SHOWN: 'shown' + EVENT_KEY }; var Selector = { CONTENT: '.navdrawer-content', DATA_DISMISS: '[data-dismiss="navdrawer"]', DATA_TOGGLE: '[data-toggle="navdrawer"]' }; // <<< constants var NavDrawer = function () { function NavDrawer(element, config) { _classCallCheck(this, NavDrawer); this._backdrop = null; this._config = this._getConfig(config); this._content = $(element).find(Selector.CONTENT)[0]; this._element = element; this._ignoreBackdropClick = false; this._isShown = false; } _createClass(NavDrawer, [{ key: 'hide', value: function hide(event) { if (event) { event.preventDefault(); } var hideClassName = ClassName.OPEN + '-' + this._config.type; var hideEvent = $.Event(Event.HIDE); $(this._element).trigger(hideEvent); if (!this._isShown || hideEvent.isDefaultPrevented()) { return; } this._isShown = false; this._setEscapeEvent(); $(document).off(Event.FOCUSIN); $(this._content).off(Event.MOUSEDOWN_DISMISS); $(this._element).off(Event.CLICK_DISMISS).removeClass(ClassName.SHOW); if (Util.supportsTransitionEnd()) { $(this._element).one(Util.TRANSITION_END, $.proxy(this._hideNavdrawer, this, hideClassName)).emulateTransitionEnd(TRANSITION_DURATION); } else { this._hideNavdrawer(); } } }, { key: 'show', value: function show(relatedTarget) { var _this = this; var showEvent = $.Event(Event.SHOW, { relatedTarget: relatedTarget }); $(this._element).trigger(showEvent); if (this._isShown || showEvent.isDefaultPrevented()) { return; } this._isShown = true; $(document.body).addClass(ClassName.OPEN + '-' + this._config.type); this._setEscapeEvent(); $(this._element).addClass(NAME + '-' + this._config.type); $(this._element).on(Event.CLICK_DISMISS, Selector.DATA_DISMISS, $.proxy(this.hide, this)); $(this._content).on(Event.MOUSEDOWN_DISMISS, function () { $(_this._element).one(Event.MOUSEUP_DISMISS, function (event) { if ($(event.target).is(_this._element)) { _this._ignoreBackdropClick = true; } }); }); this._showBackdrop($.proxy(this._showElement, this, relatedTarget)); } }, { key: 'toggle', value: function toggle(relatedTarget) { return this._isShown ? this.hide() : this.show(relatedTarget); } }, { key: '_enforceFocus', value: function _enforceFocus() { var _this2 = this; $(document).off(Event.FOCUSIN).on(Event.FOCUSIN, function (event) { if (_this2._config.type === 'default' || $(window).width() <= _this2._config.breakpoint) { if (_this2._element !== event.target && !$(_this2._element).has(event.target).length) { _this2._element.focus(); } } }); } }, { key: '_getConfig', value: function _getConfig(config) { config = $.extend({}, Default, config); Util.typeCheckConfig(NAME, config, DefaultType); return config; } }, { key: '_hideNavdrawer', value: function _hideNavdrawer(className) { var _this3 = this; this._element.style.display = 'none'; this._showBackdrop(function () { $(document.body).removeClass(className); $(_this3._element).trigger(Event.HIDDEN); }); } }, { key: '_removeBackdrop', value: function _removeBackdrop() { if (this._backdrop) { $(this._backdrop).remove(); this._backdrop = null; } } }, { key: '_setEscapeEvent', value: function _setEscapeEvent() { var _this4 = this; if (this._isShown && this._config.keyboard) { $(this._element).on(Event.KEYDOWN_DISMISS, function (event) { if (event.which === 27) { _this4.hide(); } }); } else if (!this._isShown) { $(this._element).off(Event.KEYDOWN_DISMISS); } } }, { key: '_showBackdrop', value: function _showBackdrop(callback) { var _this5 = this; var supportsTransition = Util.supportsTransitionEnd(); if (this._isShown) { this._backdrop = document.createElement('div'); $(this._backdrop).addClass(ClassName.BACKDROP).addClass(ClassName.BACKDROP + '-' + this._config.type).appendTo(document.body); $(this._element).on(Event.CLICK_DISMISS, function (event) { if (_this5._ignoreBackdropClick) { _this5._ignoreBackdropClick = false; return; } if (event.target !== event.currentTarget) { return; } _this5.hide(); }); if (supportsTransition) { Util.reflow(this._backdrop); } $(this._backdrop).addClass(ClassName.SHOW); if (!callback) { return; } if (!supportsTransition) { callback(); return; } $(this._backdrop).one(Util.TRANSITION_END, callback).emulateTransitionEnd(TRANSITION_DURATION_BACKDROP); } else if (this._backdrop && !this._isShown) { $(this._backdrop).removeClass(ClassName.SHOW); var callbackRemove = function callbackRemove() { _this5._removeBackdrop(); if (callback) { callback(); } }; if (supportsTransition) { $(this._backdrop).one(Util.TRANSITION_END, callbackRemove).emulateTransitionEnd(TRANSITION_DURATION_BACKDROP); } else { callbackRemove(); } } else if (callback) { callback(); } } }, { key: '_showElement', value: function _showElement(relatedTarget) { var _this6 = this; var supportsTransition = Util.supportsTransitionEnd(); if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) { document.body.appendChild(this._element); } this._element.style.display = 'block'; if (supportsTransition) { Util.reflow(this._element); } $(this._element).addClass(ClassName.SHOW); this._enforceFocus(); var shownEvent = $.Event(Event.SHOWN, { relatedTarget: relatedTarget }); var transitionComplete = function transitionComplete() { _this6._element.focus(); $(_this6._element).trigger(shownEvent); }; if (supportsTransition) { $(this._content).one(Util.TRANSITION_END, transitionComplete).emulateTransitionEnd(TRANSITION_DURATION); } else { transitionComplete(); } } }], [{ key: '_jQueryInterface', value: function _jQueryInterface(config, relatedTarget) { return this.each(function () { var data = $(this).data(DATA_KEY); var _config = $.extend({}, NavDrawer.Default, $(this).data(), (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config); if (!data) { data = new NavDrawer(this, _config); $(this).data(DATA_KEY, data); } if (typeof config === 'string') { if (data[config] === undefined) { throw new Error('No method named "' + config + '"'); } data[config](relatedTarget); } else if (_config.show) { data.show(relatedTarget); } }); } }, { key: 'Default', get: function get() { return Default; } }]); return NavDrawer; }(); $(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) { var _this7 = this; var selector = Util.getSelectorFromElement(this); var target = void 0; if (selector) { target = $(selector)[0]; } var config = $(target).data(DATA_KEY) ? 'toggle' : $.extend({}, $(target).data(), $(this).data()); if (this.tagName === 'A') { event.preventDefault(); } var $target = $(target).one(Event.SHOW, function (showEvent) { if (showEvent.isDefaultPrevented()) { return; } $target.one(Event.HIDDEN, function () { if ($(_this7).is(':visible')) { _this7.focus(); } }); }); NavDrawer._jQueryInterface.call($(target), config, this); }); $.fn[NAME] = NavDrawer._jQueryInterface; $.fn[NAME].Constructor = NavDrawer; $.fn[NAME].noConflict = function () { $.fn[NAME] = NO_CONFLICT; return NavDrawer._jQueryInterface; }; return NavDrawer; }(jQuery); /*! * tab indicator animation * requires bootstrap's (v4.0.0-alpha.6) tab.js */ var TabSwitch = function ($) { // constants >>> var DATA_KEY = 'md.tabswitch'; var NAME = 'tabswitch'; var NO_CONFLICT = $.fn[NAME]; var TRANSITION_DURATION = 300; var ClassName = { ANIMATE: 'animate', INDICATOR: 'nav-tabs-indicator', MATERIAL: 'nav-tabs-material', SCROLLABLE: 'nav-tabs-scrollable', SHOW: 'show' }; var Event = { SHOW_BS_TAB: 'show.bs.tab' }; var Selector = { DATA_TOGGLE: '.nav-tabs [data-toggle="tab"]', NAV: '.nav-tabs', NAV_ITEM: '.nav-item' }; // <<< constants var TabSwitch = function () { function TabSwitch(nav) { _classCallCheck(this, TabSwitch); if (typeof $.fn.tab === 'undefined') { throw new Error('Material\'s JavaScript requires Bootstrap\'s tab.js'); }; this._nav = nav; this._navindicator = null; } _createClass(TabSwitch, [{ key: 'switch', value: function _switch(element, relatedTarget) { var _this8 = this; var supportsTransition = Util.supportsTransitionEnd(); if (!this._navindicator) { this._createIndicator(); } var elLeft = $(element).closest(Selector.NAV_ITEM).offset().left; var elWidth = $(element).closest(Selector.NAV_ITEM).outerWidth(); var navLeft = $(this._nav).offset().left; var navScrollLeft = $(this._nav).scrollLeft(); var navWidth = $(this._nav).outerWidth(); if (relatedTarget !== undefined) { var relatedLeft = $(relatedTarget).closest(Selector.NAV_ITEM).offset().left; var relatedWidth = $(relatedTarget).closest(Selector.NAV_ITEM).outerWidth(); $(this._navindicator).css({ left: relatedLeft + navScrollLeft - navLeft, right: navWidth - (relatedLeft + navScrollLeft - navLeft + relatedWidth) }); $(this._navindicator).addClass(ClassName.SHOW); Util.reflow(this._navindicator); if (supportsTransition) { $(this._nav).addClass(ClassName.ANIMATE); } } $(this._navindicator).css({ left: elLeft + navScrollLeft - navLeft, right: navWidth - (elLeft + navScrollLeft - navLeft + elWidth) }); var complete = function complete() { $(_this8._nav).removeClass(ClassName.ANIMATE); $(_this8._navindicator).removeClass(ClassName.SHOW); }; if (!supportsTransition) { complete(); return; } $(this._navindicator).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION); } }, { key: '_createIndicator', value: function _createIndicator() { this._navindicator = document.createElement('div'); $(this._navindicator).addClass(ClassName.INDICATOR).appendTo(this._nav); $(this._nav).addClass(ClassName.MATERIAL); } }], [{ key: '_jQueryInterface', value: function _jQueryInterface(relatedTarget) { return this.each(function () { var nav = $(this).closest(Selector.NAV)[0]; if (!nav) { return; } var data = $(nav).data(DATA_KEY); if (!data) { data = new TabSwitch(nav); $(nav).data(DATA_KEY, data); } data.switch(this, relatedTarget); }); } }]); return TabSwitch; }(); $(document).on(Event.SHOW_BS_TAB, Selector.DATA_TOGGLE, function (event) { TabSwitch._jQueryInterface.call($(event.target), event.relatedTarget); }); $.fn[NAME] = TabSwitch._jQueryInterface; $.fn[NAME].Constructor = TabSwitch; $.fn[NAME].noConflict = function () { $.fn[NAME] = NO_CONFLICT; return TabSwitch._jQueryInterface; }; return TabSwitch; }(jQuery); /*! * global util js * based on bootstrap's (v4.0.0-alpha.6) util.js */ var Util = function ($) { var transition = false; var TransitionEndEvent = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' }; function getSpecialTransitionEndEvent() { return { bindType: transition.end, delegateType: transition.end, handle: function handle(event) { if ($(event.target).is(this)) { return event.handleObj.handler.apply(this, arguments); } return undefined; } }; } function isElement(obj) { return (obj[0] || obj).nodeType; } function setTransitionEndSupport() { transition = transitionEndTest(); $.fn.emulateTransitionEnd = transitionEndEmulator; if (Util.supportsTransitionEnd()) { $.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent(); } } function toType(obj) { return {}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase(); } function transitionEndEmulator(duration) { var _this9 = this; var called = false; $(this).one(Util.TRANSITION_END, function () { called = true; }); setTimeout(function () { if (!called) { Util.triggerTransitionEnd(_this9); } }, duration); return this; } function transitionEndTest() { if (window.QUnit) { return false; } var el = document.createElement('material'); for (var name in TransitionEndEvent) { if (el.style[name] !== undefined) { return { end: TransitionEndEvent[name] }; } }; return false; } var Util = { TRANSITION_END: 'mdTransitionEnd', getSelectorFromElement: function getSelectorFromElement(element) { var selector = element.getAttribute('data-target'); if (!selector) { selector = element.getAttribute('href') || ''; selector = /^#[a-z]/i.test(selector) ? selector : null; } return selector; }, getUID: function getUID(prefix) { do { prefix += ~~(Math.random() * 1000000); } while (document.getElementById(prefix)); return prefix; }, reflow: function reflow(element) { new Function('md', 'return md')(element.offsetHeight); }, supportsTransitionEnd: function supportsTransitionEnd() { return Boolean(transition); }, triggerTransitionEnd: function triggerTransitionEnd(element) { $(element).trigger(transition.end); }, typeCheckConfig: function typeCheckConfig(componentName, config, configTypes) { for (var property in configTypes) { if (configTypes.hasOwnProperty(property)) { var expectedTypes = configTypes[property]; var value = config[property]; var valueType = void 0; if (value && isElement(value)) { valueType = 'element'; } else { valueType = toType(value); } if (!new RegExp(expectedTypes).test(valueType)) { throw new Error(componentName.toUpperCase() + ': ' + ('Option "' + property + '" provided type "' + valueType + '" ') + ('but expected type "' + expectedTypes + '".')); } } }; } }; setTransitionEndSupport(); return Util; }(jQuery); }(jQuery);
{ "content_hash": "cb8a48eb468b0058feea0c2681ef7658", "timestamp": "", "source": "github", "line_count": 751, "max_line_length": 564, "avg_line_length": 28.55792276964048, "alnum_prop": 0.572341119970159, "repo_name": "moconnor-bmj/BMDL", "id": "7e773d9b0f82c0a57753035774474af96eb09d6f", "size": "21447", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/js/src.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "596154" }, { "name": "HTML", "bytes": "1947858" }, { "name": "JavaScript", "bytes": "140623" }, { "name": "Ruby", "bytes": "1331" } ], "symlink_target": "" }
<?php namespace App\Auth\Permission\Exception; use Illuminate\Database\Eloquent\ModelNotFoundException; class PermissionNotExistsException extends ModelNotFoundException { }
{ "content_hash": "6c42a4c80ef9bbbcba360350b8f35c85", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 65, "avg_line_length": 17.7, "alnum_prop": 0.8531073446327684, "repo_name": "tonyhhyip/ysitd-cloud-portal", "id": "1488078effcabd0e0fc8500c79d0cb6a17e0a58f", "size": "177", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "app/Auth/Permission/Exception/PermissionNotExistsException.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "HTML", "bytes": "26616" }, { "name": "JavaScript", "bytes": "101775" }, { "name": "PHP", "bytes": "119219" }, { "name": "PLpgSQL", "bytes": "7370" }, { "name": "Vue", "bytes": "8903" } ], "symlink_target": "" }
echo off set esbToolkitPath="C:\Program Files (x86)\Microsoft BizTalk ESB Toolkit\Bin" set logFile=".\Log" if not exist %logFile% mkdir %logFile% echo *** echo *** >> %logFile% echo Import Ajax itinerary echo Import Ajax itinerary >> %logFile% esbimportutil /f:Ajax.xml /c:deployed >> %logFile% echo Import done echo Import done >> %logFile% echo *** echo *** >> %logFile% pause
{ "content_hash": "989bcc41b236def7d5c693e15b66aff5", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 77, "avg_line_length": 17.545454545454547, "alnum_prop": 0.7020725388601037, "repo_name": "jamescorbould/Ajax.ESB.Licensing", "id": "edf966fe0c2cd65111a4538d1f17e8be651199a8", "size": "386", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ESBItineraries/DeployItinerary.bat", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "121" }, { "name": "Batchfile", "bytes": "386" }, { "name": "C#", "bytes": "10298" }, { "name": "HTML", "bytes": "3159" } ], "symlink_target": "" }
layout: compress --- <!DOCTYPE html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"><!--<![endif]--> <head> {% include head.html %} </head> <body> {% include nav.html %} <!-- Header --> <header class="header" role="banner"> <div class="wrapper animated fadeIn"> <div class="content"> <div class="post-title {% if page.feature %} feature {% endif %}"> <h1>{{ page.title }}</h1> </div> {{ content }} </div> </div> {% if page.comments and site.disqus_shortname %}<section id="disqus_thread" class="animated fadeInUp"></section><!-- /#disqus_thread -->{% endif %} </header> {% include scripts.html %} {% if site.mathjax == true %} <!-- MathJax --> <script async src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> {% endif %} </body> </html>
{ "content_hash": "944dd7518e7e859c86eb1c61cb11500b", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 155, "avg_line_length": 37.03225806451613, "alnum_prop": 0.5252613240418118, "repo_name": "jessica-hu/jessica-hu.github.io", "id": "4a51233cf1bf7de9adc0895f81765070cf42b076", "size": "1152", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "_layouts/page.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29949" }, { "name": "HTML", "bytes": "34390" }, { "name": "JavaScript", "bytes": "32598" }, { "name": "Ruby", "bytes": "1887" } ], "symlink_target": "" }
#include "maths/formatpacking.h" #include "maths/matrix.h" #include "vk_core.h" #include "vk_debug.h" #include "vk_replay.h" #define VULKAN 1 #include "data/glsl/glsl_ubos_cpp.h" void VulkanReplay::CreateTexImageView(VkImage liveIm, const VulkanCreationInfo::Image &iminfo, CompType typeCast, TextureDisplayViews &views) { VkDevice dev = m_pDriver->GetDev(); if(views.typeCast != typeCast) { // if the type hint has changed, recreate the image views // flush any pending commands that might use the old views m_pDriver->SubmitCmds(); m_pDriver->FlushQ(); for(size_t i = 0; i < ARRAY_COUNT(views.views); i++) { m_pDriver->vkDestroyImageView(dev, views.views[i], NULL); views.views[i] = VK_NULL_HANDLE; } } views.typeCast = typeCast; VkFormat fmt = views.castedFormat = GetViewCastedFormat(iminfo.format, typeCast); // all types have at least views[0] populated, so if it's still there, we can just return if(views.views[0] != VK_NULL_HANDLE) return; VkImageViewCreateInfo viewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, NULL, 0, liveIm, VK_IMAGE_VIEW_TYPE_2D_ARRAY, fmt, {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY}, { VK_IMAGE_ASPECT_COLOR_BIT, 0, RDCMAX(1U, iminfo.mipLevels), 0, RDCMAX(1U, iminfo.arrayLayers), }, }; // for the stencil-only format, the first view is stencil only if(fmt == VK_FORMAT_S8_UINT) viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT; // otherwise for depth or stencil formats, the first view is depth. else if(IsDepthOrStencilFormat(fmt)) viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; if(iminfo.type == VK_IMAGE_TYPE_1D) viewInfo.viewType = VK_IMAGE_VIEW_TYPE_1D_ARRAY; else if(iminfo.type == VK_IMAGE_TYPE_3D) viewInfo.viewType = VK_IMAGE_VIEW_TYPE_3D; VkResult vkr = VK_SUCCESS; if(IsYUVFormat(fmt)) { const uint32_t planeCount = GetYUVPlaneCount(fmt); for(uint32_t i = 0; i < planeCount; i++) { viewInfo.format = GetYUVViewPlaneFormat(fmt, i); if(planeCount > 1) viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_PLANE_0_BIT << i; // create as wrapped vkr = m_pDriver->vkCreateImageView(dev, &viewInfo, NULL, &views.views[i]); CheckVkResult(vkr); } } else { // create first view vkr = m_pDriver->vkCreateImageView(dev, &viewInfo, NULL, &views.views[0]); CheckVkResult(vkr); NameVulkanObject(views.views[0], StringFormat::Fmt("CreateTexImageView view 0 %s", ToStr(GetResID(liveIm)).c_str())); // for depth-stencil images, create a second view for stencil only if(IsDepthAndStencilFormat(fmt)) { viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT; vkr = m_pDriver->vkCreateImageView(dev, &viewInfo, NULL, &views.views[1]); CheckVkResult(vkr); NameVulkanObject(views.views[1], StringFormat::Fmt("CreateTexImageView view 1 %s", ToStr(GetResID(liveIm)).c_str())); } } } bool VulkanReplay::RenderTexture(TextureDisplay cfg) { auto it = m_OutputWindows.find(m_ActiveWinID); if(it == m_OutputWindows.end()) { RDCERR("output window not bound"); return false; } OutputWindow &outw = it->second; // if the swapchain failed to create, do nothing. We will try to recreate it // again in CheckResizeOutputWindow (once per render 'frame') if(outw.m_WindowSystem != WindowingSystem::Headless && outw.swap == VK_NULL_HANDLE) return false; VkRenderPassBeginInfo rpbegin = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, NULL, Unwrap(outw.rp), Unwrap(outw.fb), {{ 0, 0, }, {m_DebugWidth, m_DebugHeight}}, 0, NULL, }; LockedConstImageStateRef imageState = m_pDriver->FindConstImageState(cfg.resourceId); if(!imageState) { RDCWARN("Could not find image info for image %s", ToStr(cfg.resourceId).c_str()); return false; } if(!imageState->isMemoryBound) return false; return RenderTextureInternal(cfg, *imageState, rpbegin, eTexDisplay_MipShift | eTexDisplay_BlendAlpha); } bool VulkanReplay::RenderTextureInternal(TextureDisplay cfg, const ImageState &imageState, VkRenderPassBeginInfo rpbegin, int flags) { const bool blendAlpha = (flags & eTexDisplay_BlendAlpha) != 0; const bool mipShift = (flags & eTexDisplay_MipShift) != 0; const bool f16render = (flags & eTexDisplay_16Render) != 0; const bool greenonly = (flags & eTexDisplay_GreenOnly) != 0; const bool f32render = (flags & eTexDisplay_32Render) != 0; VkDevice dev = m_pDriver->GetDev(); const VkDevDispatchTable *vt = ObjDisp(dev); const ImageInfo &imageInfo = imageState.GetImageInfo(); VulkanCreationInfo::Image &iminfo = m_pDriver->m_CreationInfo.m_Image[cfg.resourceId]; TextureDisplayViews &texviews = m_TexRender.TextureViews[cfg.resourceId]; VkImage liveIm = m_pDriver->GetResourceManager()->GetCurrentHandle<VkImage>(cfg.resourceId); CreateTexImageView(liveIm, iminfo, cfg.typeCast, texviews); int displayformat = 0; uint32_t descSetBinding = 0; if(IsUIntFormat(texviews.castedFormat)) { descSetBinding = 10; displayformat |= TEXDISPLAY_UINT_TEX; } else if(IsSIntFormat(texviews.castedFormat)) { descSetBinding = 15; displayformat |= TEXDISPLAY_SINT_TEX; } else { descSetBinding = 5; } // by default we use view 0 int viewIndex = 0; // if we're displaying the stencil, set up for stencil display if(imageInfo.format == VK_FORMAT_S8_UINT || (IsStencilFormat(imageInfo.format) && !cfg.red && cfg.green)) { descSetBinding = 10; displayformat |= TEXDISPLAY_UINT_TEX; // for stencil we use view 1 as long as it's a depth-stencil texture if(IsDepthAndStencilFormat(imageInfo.format)) viewIndex = 1; // rescale the range so that stencil seems to fit to 0-1 cfg.rangeMin *= 255.0f; cfg.rangeMax *= 255.0f; // shuffle the channel selection, since stencil comes back in red cfg.red = true; cfg.green = false; } VkImageView liveImView = texviews.views[viewIndex]; RDCASSERT(liveImView != VK_NULL_HANDLE); uint32_t uboOffs = 0; TexDisplayUBOData *data = (TexDisplayUBOData *)m_TexRender.UBO.Map(&uboOffs); if(!data) return false; data->Padding = 0; float x = cfg.xOffset; float y = cfg.yOffset; data->Position.x = x; data->Position.y = y; data->HDRMul = cfg.hdrMultiplier; data->DecodeYUV = cfg.decodeYUV ? 1 : 0; Vec4u YUVDownsampleRate = {}; Vec4u YUVAChannels = {}; GetYUVShaderParameters(texviews.castedFormat, YUVDownsampleRate, YUVAChannels); data->YUVDownsampleRate = YUVDownsampleRate; data->YUVAChannels = YUVAChannels; int32_t tex_x = iminfo.extent.width; int32_t tex_y = iminfo.extent.height; int32_t tex_z = iminfo.extent.depth; if(cfg.scale <= 0.0f) { float xscale = float(m_DebugWidth) / float(tex_x); float yscale = float(m_DebugHeight) / float(tex_y); // update cfg.scale for use below float scale = cfg.scale = RDCMIN(xscale, yscale); if(yscale > xscale) { data->Position.x = 0; data->Position.y = (float(m_DebugHeight) - (tex_y * scale)) * 0.5f; } else { data->Position.y = 0; data->Position.x = (float(m_DebugWidth) - (tex_x * scale)) * 0.5f; } } data->Channels.x = cfg.red ? 1.0f : 0.0f; data->Channels.y = cfg.green ? 1.0f : 0.0f; data->Channels.z = cfg.blue ? 1.0f : 0.0f; data->Channels.w = cfg.alpha ? 1.0f : 0.0f; if(cfg.rangeMax <= cfg.rangeMin) cfg.rangeMax += 0.00001f; data->RangeMinimum = cfg.rangeMin; data->InverseRangeSize = 1.0f / (cfg.rangeMax - cfg.rangeMin); data->FlipY = cfg.flipY ? 1 : 0; const bool linearSample = cfg.subresource.mip == 0 && cfg.scale < 1.0f && (displayformat & (TEXDISPLAY_UINT_TEX | TEXDISPLAY_SINT_TEX)) == 0; data->MipLevel = (int)cfg.subresource.mip; data->Slice = 0; if(iminfo.type != VK_IMAGE_TYPE_3D) { uint32_t numSlices = RDCMAX((uint32_t)iminfo.arrayLayers, 1U); uint32_t sliceFace = RDCCLAMP(cfg.subresource.slice, 0U, numSlices - 1); data->Slice = (float)sliceFace + 0.001f; } else { float slice = (float)RDCCLAMP(cfg.subresource.slice, 0U, iminfo.extent.depth - 1); // when sampling linearly, we need to add half a pixel to ensure we only sample the desired // slice if(linearSample) slice += 0.5f; else slice += 0.001f; data->Slice = slice; } data->TextureResolutionPS.x = float(RDCMAX(1, tex_x >> cfg.subresource.mip)); data->TextureResolutionPS.y = float(RDCMAX(1, tex_y >> cfg.subresource.mip)); data->TextureResolutionPS.z = float(RDCMAX(1, tex_z >> cfg.subresource.mip)); if(mipShift) data->MipShift = float(1 << cfg.subresource.mip); else data->MipShift = 1.0f; data->Scale = cfg.scale; int sampleIdx = (int)RDCCLAMP(cfg.subresource.sample, 0U, (uint32_t)SampleCount(iminfo.samples)); if(cfg.subresource.sample == ~0U) sampleIdx = -SampleCount(iminfo.samples); data->SampleIdx = sampleIdx; data->OutputRes.x = (float)m_DebugWidth; data->OutputRes.y = (float)m_DebugHeight; int textype = 0; if(iminfo.type == VK_IMAGE_TYPE_1D) { textype = RESTYPE_TEX1D; } else if(iminfo.type == VK_IMAGE_TYPE_3D) { textype = RESTYPE_TEX3D; } else if(iminfo.type == VK_IMAGE_TYPE_2D) { textype = RESTYPE_TEX2D; if(iminfo.samples != VK_SAMPLE_COUNT_1_BIT) textype = RESTYPE_TEX2DMS; } displayformat |= textype; descSetBinding += textype; if(!IsSRGBFormat(texviews.castedFormat) && cfg.linearDisplayAsGamma) displayformat |= TEXDISPLAY_GAMMA_CURVE; if(cfg.overlay == DebugOverlay::NaN) displayformat |= TEXDISPLAY_NANS; if(cfg.overlay == DebugOverlay::Clipping) displayformat |= TEXDISPLAY_CLIPPING; data->OutputDisplayFormat = displayformat; data->RawOutput = cfg.rawOutput ? 1 : 0; if(cfg.customShaderId != ResourceId()) { // must match struct declared in user shader (see documentation / Shader Viewer window helper // menus) RD_CustomShader_UBO_Type *customData = (RD_CustomShader_UBO_Type *)data; customData->TexDim.x = iminfo.extent.width; customData->TexDim.y = iminfo.extent.height; customData->TexDim.z = iminfo.type == VK_IMAGE_TYPE_3D ? iminfo.extent.depth : iminfo.arrayLayers; customData->TexDim.w = iminfo.mipLevels; customData->SelectedMip = cfg.subresource.mip; customData->SelectedSliceFace = cfg.subresource.slice; customData->SelectedSample = sampleIdx; customData->TextureType = (uint32_t)textype; customData->YUVDownsampleRate = YUVDownsampleRate; customData->YUVAChannels = YUVAChannels; customData->SelectedRange.x = cfg.rangeMin; customData->SelectedRange.y = cfg.rangeMax; } m_TexRender.UBO.Unmap(); HeatmapData heatmapData = {}; { if(cfg.overlay == DebugOverlay::QuadOverdrawDraw || cfg.overlay == DebugOverlay::QuadOverdrawPass) { heatmapData.HeatmapMode = HEATMAP_LINEAR; } else if(cfg.overlay == DebugOverlay::TriangleSizeDraw || cfg.overlay == DebugOverlay::TriangleSizePass) { heatmapData.HeatmapMode = HEATMAP_TRISIZE; } if(heatmapData.HeatmapMode) { memcpy(heatmapData.ColorRamp, colorRamp, sizeof(colorRamp)); RDCCOMPILE_ASSERT(sizeof(heatmapData.ColorRamp) == sizeof(colorRamp), "C++ color ramp array is not the same size as the shader array"); } } uint32_t heatUboOffs = 0; { HeatmapData *ptr = (HeatmapData *)m_TexRender.HeatmapUBO.Map(&heatUboOffs); if(!ptr) return false; memcpy(ptr, &heatmapData, sizeof(HeatmapData)); m_TexRender.HeatmapUBO.Unmap(); } VkDescriptorImageInfo imdesc = {0}; imdesc.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imdesc.imageView = Unwrap(liveImView); imdesc.sampler = Unwrap(m_General.PointSampler); if(linearSample) imdesc.sampler = Unwrap(m_TexRender.LinearSampler); VkDescriptorImageInfo altimdesc[2] = {}; for(uint32_t i = 1; i < GetYUVPlaneCount(texviews.castedFormat); i++) { RDCASSERT(texviews.views[i] != VK_NULL_HANDLE); altimdesc[i - 1].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; altimdesc[i - 1].imageView = Unwrap(texviews.views[i]); altimdesc[i - 1].sampler = Unwrap(m_General.PointSampler); if(linearSample) altimdesc[i - 1].sampler = Unwrap(m_TexRender.LinearSampler); } VkDescriptorSet descset = m_TexRender.GetDescSet(); VkDescriptorBufferInfo ubodesc = {}, heatubodesc = {}; m_TexRender.UBO.FillDescriptor(ubodesc); m_TexRender.HeatmapUBO.FillDescriptor(heatubodesc); VkWriteDescriptorSet writeSet[] = { // sampled view {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(descset), descSetBinding, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &imdesc, NULL, NULL}, // YUV secondary planes (if needed) {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(descset), 10, 0, GetYUVPlaneCount(texviews.castedFormat) - 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, altimdesc, NULL, NULL}, // UBOs {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(descset), 0, 0, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, NULL, &ubodesc, NULL}, {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(descset), 1, 0, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, NULL, &heatubodesc, NULL}, }; rdcarray<VkWriteDescriptorSet> writeSets; for(size_t i = 0; i < ARRAY_COUNT(writeSet); i++) { if(writeSet[i].descriptorCount > 0) writeSets.push_back(writeSet[i]); } for(size_t i = 0; i < ARRAY_COUNT(m_TexRender.DummyWrites); i++) { VkWriteDescriptorSet &write = m_TexRender.DummyWrites[i]; // don't write dummy data in the actual slot if(write.dstBinding == descSetBinding) continue; // don't overwrite YUV texture slots if it's a YUV planar format if(write.dstBinding == 10) { if(write.dstArrayElement == 0 && GetYUVPlaneCount(texviews.castedFormat) >= 2) continue; if(write.dstArrayElement == 1 && GetYUVPlaneCount(texviews.castedFormat) >= 3) continue; } write.dstSet = Unwrap(descset); writeSets.push_back(write); } vt->UpdateDescriptorSets(Unwrap(dev), (uint32_t)writeSets.size(), &writeSets[0], 0, NULL); VkCommandBuffer cmd = m_pDriver->GetNextCmd(); if(cmd == VK_NULL_HANDLE) return false; VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; vt->BeginCommandBuffer(Unwrap(cmd), &beginInfo); VkMarkerRegion::Begin("RenderTexture", cmd); ImageBarrierSequence setupBarriers, cleanupBarriers; imageState.TempTransition(m_pDriver->GetQueueFamilyIndex(), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_ACCESS_SHADER_READ_BIT, setupBarriers, cleanupBarriers, m_pDriver->GetImageTransitionInfo()); m_pDriver->InlineSetupImageBarriers(cmd, setupBarriers); m_pDriver->SubmitAndFlushImageStateBarriers(setupBarriers); { vt->CmdBeginRenderPass(Unwrap(cmd), &rpbegin, VK_SUBPASS_CONTENTS_INLINE); VkPipeline pipe = greenonly ? m_TexRender.PipelineGreenOnly : m_TexRender.Pipeline; if(cfg.customShaderId != ResourceId()) { GetDebugManager()->CreateCustomShaderPipeline(cfg.customShaderId, m_TexRender.PipeLayout); pipe = GetDebugManager()->GetCustomPipeline(); } else if(flags & (eTexDisplay_RemapFloat | eTexDisplay_RemapUInt | eTexDisplay_RemapSInt)) { int i = 0; if(flags & eTexDisplay_RemapFloat) i = 0; else if(flags & eTexDisplay_RemapUInt) i = 1; else if(flags & eTexDisplay_RemapSInt) i = 2; int f = 0; if(flags & eTexDisplay_32Render) f = 2; else if(flags & eTexDisplay_16Render) f = 1; else f = 0; bool srgb = (flags & eTexDisplay_RemapSRGB) != 0; pipe = m_TexRender.RemapPipeline[f][i][(greenonly || srgb) ? 1 : 0]; } else if(f16render) { pipe = greenonly ? m_TexRender.F16PipelineGreenOnly : m_TexRender.F16Pipeline; } else if(f32render) { pipe = greenonly ? m_TexRender.F32PipelineGreenOnly : m_TexRender.F32Pipeline; } else if(!cfg.rawOutput && blendAlpha && cfg.customShaderId == ResourceId()) { pipe = m_TexRender.BlendPipeline; } uint32_t offsets[] = {uboOffs, heatUboOffs}; vt->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(pipe)); vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_TexRender.PipeLayout), 0, 1, UnwrapPtr(descset), 2, offsets); VkViewport viewport = {(float)rpbegin.renderArea.offset.x, (float)rpbegin.renderArea.offset.y, (float)rpbegin.renderArea.extent.width, (float)rpbegin.renderArea.extent.height, 0.0f, 1.0f}; vt->CmdSetViewport(Unwrap(cmd), 0, 1, &viewport); vt->CmdDraw(Unwrap(cmd), 4, 1, 0, 0); if(m_pDriver->GetDriverInfo().QualcommLeakingUBOOffsets()) { offsets[0] = offsets[1] = 0; vt->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_TexRender.PipeLayout), 0, 1, UnwrapPtr(descset), 2, offsets); } vt->CmdEndRenderPass(Unwrap(cmd)); } m_pDriver->InlineCleanupImageBarriers(cmd, cleanupBarriers); VkMarkerRegion::End(cmd); vt->EndCommandBuffer(Unwrap(cmd)); if(!cleanupBarriers.empty()) { m_pDriver->SubmitCmds(); m_pDriver->FlushQ(); m_pDriver->SubmitAndFlushImageStateBarriers(cleanupBarriers); } #if ENABLED(SINGLE_FLUSH_VALIDATE) else { m_pDriver->SubmitCmds(); } #endif return true; }
{ "content_hash": "c431cf07cafd37e3f8e699f69e26e89f", "timestamp": "", "source": "github", "line_count": 586, "max_line_length": 102, "avg_line_length": 31.428327645051194, "alnum_prop": 0.6583048270619536, "repo_name": "Zorro666/renderdoc", "id": "b010e985e688f5c9ab2e962351172cc44c9e65d0", "size": "19723", "binary": false, "copies": "2", "ref": "refs/heads/v1.x", "path": "renderdoc/driver/vulkan/vk_rendertexture.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7657767" }, { "name": "C++", "bytes": "33782979" }, { "name": "CMake", "bytes": "101295" }, { "name": "CSS", "bytes": "1642" }, { "name": "Dockerfile", "bytes": "119" }, { "name": "GLSL", "bytes": "58063" }, { "name": "HLSL", "bytes": "80557" }, { "name": "Java", "bytes": "2241" }, { "name": "JavaScript", "bytes": "10593" }, { "name": "Objective-C", "bytes": "53867" }, { "name": "Objective-C++", "bytes": "156322" }, { "name": "Python", "bytes": "924182" }, { "name": "QMake", "bytes": "15225" }, { "name": "SWIG", "bytes": "54789" }, { "name": "Shell", "bytes": "51606" } ], "symlink_target": "" }
create table CP_CHARTPROVIDE_DIR ( ID VARCHAR2(32 CHAR) not null, NAME VARCHAR2(30 CHAR), PARENT_ID VARCHAR2(32 CHAR) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table CP_CHARTPROVIDE_DIR add primary key (ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table CP_CHARTPROVIDE_DIR add constraint FKC01788C3217044FB foreign key (PARENT_ID) references CP_CHARTPROVIDE_DIR (ID); create table CP_DATASOURCE ( ID VARCHAR2(32 CHAR) not null, NAME VARCHAR2(30 CHAR), DRIVERCLASS VARCHAR2(100 CHAR), JDBCURL VARCHAR2(500 CHAR), USER_NAME VARCHAR2(30 CHAR), PASSWORD VARCHAR2(30 CHAR), DS_TYPE VARCHAR2(10) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table CP_DATASOURCE add primary key (ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table CP_SQL_DIR ( ID VARCHAR2(32 CHAR) not null, NAME VARCHAR2(30 CHAR), PARENT_ID VARCHAR2(32 CHAR) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table CP_SQL_DIR add primary key (ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table CP_SQL_DIR add constraint FK8663E48A723E740E foreign key (PARENT_ID) references CP_SQL_DIR (ID); create table CP_TESTDATA ( EMPNO NUMBER(4), ENAME VARCHAR2(10), JOB VARCHAR2(9), MGR NUMBER(4), HIREDATE DATE, SAL NUMBER(7,2), COMM NUMBER(7,2), DEPTNO NUMBER(2) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table EXL_V2_DATABLOCK_INFO ( DB_ID VARCHAR2(32) not null, RPT_ID VARCHAR2(32), DB_NO VARCHAR2(50), START_SITE VARCHAR2(50), END_STIE VARCHAR2(50) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table EXL_V2_DATASOURCE ( DS_ID VARCHAR2(32) not null, DS_TYPE VARCHAR2(8), TABLE_NAME VARCHAR2(256), TABLE_REMARK VARCHAR2(256), SQL_CONTENT VARCHAR2(4000) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table EXL_V2_DB_DS_INFO ( DB_DS_ID VARCHAR2(32) not null, DB_ID VARCHAR2(32), DS_ID VARCHAR2(32), ELT VARCHAR2(255) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table EXL_V2_PROPERTY ( PROP_ID VARCHAR2(32), IF_LOCK VARCHAR2(1), TYPE_CODE VARCHAR2(2), TYPE_STYLE VARCHAR2(50), CENTER VARCHAR2(2), FONT VARCHAR2(50), FONT_COLOR VARCHAR2(50), BACKGROUND_COLOR VARCHAR2(50), ANNOTATION VARCHAR2(2000), IF_BOLD VARCHAR2(1), FONT_SIZE VARCHAR2(2), WIDTH VARCHAR2(20), HEIGHT VARCHAR2(20), CELL_TYPE VARCHAR2(20), IF_SHOW VARCHAR2(4), CAPTION_TYPE VARCHAR2(4) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table EXL_V2_RPT_INFO ( RPT_ID VARCHAR2(32) not null, RPT_NO VARCHAR2(32), RPT_NAME VARCHAR2(256), RPT_STATUS VARCHAR2(8), CREATE_TIME DATE, MODIFY_TIME DATE, SHEET_NAME VARCHAR2(100), DISK_PATH VARCHAR2(1000) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table EXL_V2_TITLE ( TITLE_ID VARCHAR2(32), RPT_ID VARCHAR2(32), BLOCK_ID VARCHAR2(32), PROPERTY_ID VARCHAR2(32), CONTENT VARCHAR2(200), START_SITE VARCHAR2(20), END_SITE VARCHAR2(20), DB_TABLE VARCHAR2(50), DB_FILED VARCHAR2(50), IS_CELL_MAPPING VARCHAR2(10), IMP_TABLE VARCHAR2(20), IMP_FILED VARCHAR2(20) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table EXL_V2_TMPL_INFO ( TMPL_ID VARCHAR2(32) not null, TMPL_NO VARCHAR2(32), TMPL_NAME VARCHAR2(256), TMPL_CODE VARCHAR2(8), TMPL_STATUS VARCHAR2(8), TMPL_ADDR VARCHAR2(256), CREATE_TIME DATE, MODIFY_TIME DATE, REMARK VARCHAR2(256) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table EXL_V2_TMPL_RPT_INFO ( TMPL_RPT_ID VARCHAR2(32), TMPL_ID VARCHAR2(32), RPT_ID VARCHAR2(32), DISP_SN VARCHAR2(8), SHEET_NAME VARCHAR2(256) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table E_A_ACCESSORY ( UUID VARCHAR2(33 CHAR) not null, TRANSFORMER_UUID VARCHAR2(33 CHAR), EQPT_LOG_NO VARCHAR2(32), ACCESSORIES_NAME VARCHAR2(64), ACCESSORY_MODEL VARCHAR2(64), ACCESSORY_NUM NUMBER(5), MANUFACTURER VARCHAR2(256), TRANSITION_RESISTANCE NUMBER(5), OUT_MANU_NO VARCHAR2(64), OUT_MANU_DATE DATE, MODIFY_DATE DATE, VALID_FLAG VARCHAR2(32) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table E_A_ACCESSORY add constraint PK_E_A_ACCESSORY primary key (UUID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table E_A_BREAK_DISCONNECTOR ( BREAK_DISCONNECTOR_UUID VARCHAR2(33 CHAR) not null, EQPT_LEDGER_UUID VARCHAR2(33 CHAR), INTERVAL_UNIT VARCHAR2(256), MAIN_PARAM VARCHAR2(4000), REMARK VARCHAR2(4000) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table E_A_BREAK_DISCONNECTOR add constraint PK_E_A_BREAK_DISCONNECTOR primary key (BREAK_DISCONNECTOR_UUID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table E_A_BUSHING ( UUID VARCHAR2(33 CHAR) not null, TRANSFORMER_UUID VARCHAR2(33 CHAR), EQPT_LOG_NO VARCHAR2(32), VOLTAGE VARCHAR2(64), PHASE_SEQUENCE VARCHAR2(64), EQPT_MODEL VARCHAR2(64), EQPT_CODE VARCHAR2(64), CAPACITANCE NUMBER(5), MANUFACTURER VARCHAR2(256), OUT_MANU_DATE DATE, MODIFY_DATE DATE, VALID_FLAG VARCHAR2(32) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table E_A_EQPT_LEDGER ( EQPT_LEDGER_UUID VARCHAR2(33 CHAR) not null, EQPT_P_NO VARCHAR2(64), EQPT_NO VARCHAR2(64), EQPT_NAME VARCHAR2(256), OPERATE_COMPANY VARCHAR2(256), OPERATE_NO VARCHAR2(256), SUBSTATION VARCHAR2(256), EQPT_MODEL VARCHAR2(64), MANUFACTURER VARCHAR2(256), FACTORY_SERIAL_NUMBER VARCHAR2(64), PRODUCT_CODE VARCHAR2(256), RELEASE_DATE DATE, RUNNING_DATE DATE, EQPT_TYPE VARCHAR2(32), EQPT_STATUS VARCHAR2(32), EQMT_TYPE NUMBER(5) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table E_A_EQPT_LEDGER_STATUS ( UUID VARCHAR2(33 CHAR) not null, TRANSFORMER_UUID VARCHAR2(33 CHAR), EQPT_LOG_NO VARCHAR2(32), STATUS_DATE DATE, STATUS_RECORD VARCHAR2(4000), VALID_FLAG VARCHAR2(32) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table E_A_EQPT_LEDGER_STATUS add constraint PK_E_A_EQPT_LEDGER_STATUS primary key (UUID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table E_A_TRANSFORMER ( TRANSFORMER_UUID VARCHAR2(33 CHAR) not null, UUID VARCHAR2(33 CHAR), INSULATION_LEVEL NUMBER(5), COOL_MODE VARCHAR2(256), CONN_GROUP_NO VARCHAR2(64), VOLTAGE VARCHAR2(64), VOLTAGE_RATIO VARCHAR2(256), CAPACITANCE_RATIO VARCHAR2(256), NO_LOAD_CURRENT NUMBER(15), NO_LOAD_LOSS NUMBER(15), RATE_CURRENT_H NUMBER(15), RATE_CURRENT_M NUMBER(15), RATE_CURRENT_L NUMBER(15), RESISTANCE_VOLTAGE_H_M NUMBER(15), RESISTANCE_VOLTAGE_H_L NUMBER(15), RESISTANCE_VOLTAGE_M_L NUMBER(15), LOAD_LOSS_H_M NUMBER(15), LOAD_LOSS_H_L NUMBER(15), LOAD_LOSS_M_L NUMBER(15), TRAN_WEIGHT_N NUMBER(5), TRAN_WEIGHT_OIL NUMBER(5), TANK_WEIGHT NUMBER(5), BODY_WEIGHT NUMBER(5), OIL_WEIGHT NUMBER(5), SF6_WEIGHT NUMBER(5), ALL_WEIGHT NUMBER(5) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table FLASH_MAP ( YD_MONTH VARCHAR2(7), DQ VARCHAR2(100), MONTH_RDL NUMBER, DQ_BM CHAR(2) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table HEA_ACCESSLOG ( LOGID VARCHAR2(32) not null, USER_UUID VARCHAR2(50), USER_NAME VARCHAR2(50), INDEX_UUID VARCHAR2(50), INDEX_NAME VARCHAR2(50), ACCESS_IP VARCHAR2(50), ACCESS_TIME VARCHAR2(20) default sysdate, REMARK VARCHAR2(1000), ACCESS_TYPE VARCHAR2(2), APP_ID VARCHAR2(100), APP_NAME VARCHAR2(200) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table HEA_APPS ( APP_ID VARCHAR2(32) not null, APP_NO VARCHAR2(32), APP_NAME VARCHAR2(256), APP_DESC VARCHAR2(256), APP_TYPE VARCHAR2(16), APP_ADDR VARCHAR2(256), APP_CATALOG VARCHAR2(1000), DB_INFO VARCHAR2(256), DB_USER VARCHAR2(32), DB_PASSWORD VARCHAR2(32), APP_STATUS VARCHAR2(16), RUN_STATUS VARCHAR2(16) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table HEA_APPS add constraint PK_HEA_APPS primary key (APP_ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table HEA_SYSTEM_CODE ( ID VARCHAR2(255) not null, REG_CODE VARCHAR2(255), REG_TYPE VARCHAR2(255), REG_NAME VARCHAR2(200) not null, REG_DESC VARCHAR2(500), REG_PROP VARCHAR2(50), REG_ORDER NUMBER(10), REG_VALUE VARCHAR2(1000), PARENT_ID VARCHAR2(32), INDEXLEVEL NUMBER(10), HASCHILD NUMBER(10), LEVEL_CODE VARCHAR2(255), REG_LABEL VARCHAR2(255), APP_ID VARCHAR2(32) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table HEA_SYSTEM_CODE add primary key (ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table HEA_SYSTEM_CODE add constraint FKB73CBD229DFCF1C3 foreign key (PARENT_ID) references HEA_SYSTEM_CODE (ID); create table LFS_IG ( GROUPUUID VARCHAR2(32 CHAR) not null, INDEXUUID VARCHAR2(33 CHAR) not null ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table LFS_IG add primary key (INDEXUUID, GROUPUUID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table LFS_INDEX ( INDEXUUID VARCHAR2(33 CHAR) not null, INDEXNAME VARCHAR2(100 CHAR), INDEXORDER NUMBER, INDEXURL VARCHAR2(2000 CHAR), INDEXMAPPEDURL VARCHAR2(2000 CHAR), PARENTINDEXUUID VARCHAR2(32 CHAR), TARGET VARCHAR2(50 CHAR), WAY VARCHAR2(255 CHAR), INDEXTYPE NUMBER(10), INDEXICON VARCHAR2(255 CHAR), INDEXLEVEL NUMBER(19), DESCRIPTION VARCHAR2(255 CHAR), HASCHILD NUMBER, CREATETIME DATE, INDEXICON_DISK_PATH VARCHAR2(500), LEVEL_CODE VARCHAR2(2000), APP_ID VARCHAR2(32) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table P_LAYOUT_DEFINITION ( LAYOUT_CODE VARCHAR2(32 CHAR) not null, LAYOUT_NAME VARCHAR2(256 CHAR), LAYOUT_CONTENT VARCHAR2(256 CHAR), LAYOUT_PICPATH VARCHAR2(256 CHAR), CREATE_DATE DATE, MODIFY_DATE DATE ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_LAYOUT_DEFINITION add primary key (LAYOUT_CODE) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table P_PLACEHOLDER_GROUP ( PG_ID VARCHAR2(32 CHAR) not null, PLACEHOLDER_ID VARCHAR2(255 CHAR), GROUP_ID VARCHAR2(255 CHAR), TMPL_ID VARCHAR2(255 CHAR) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_PLACEHOLDER_GROUP add primary key (PG_ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table P_POP_INFO ( POP_ID VARCHAR2(32) not null, SITE_ID VARCHAR2(32), TOP_ID VARCHAR2(32), POP_TITLE VARCHAR2(256), POP_CONTENT VARCHAR2(4000), POP_STATUS VARCHAR2(16), START_TIME VARCHAR2(50), END_TIME VARCHAR2(50), POP_URL VARCHAR2(1000), HEIGHT NUMBER(5), WIDTH NUMBER(5) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table P_PORTLET_PROPERTY ( PORTLET_ID VARCHAR2(32 CHAR) not null, PORTLET_NAME VARCHAR2(256 CHAR), FUNC_ACTION VARCHAR2(256 CHAR), PORTLET_TYPE VARCHAR2(16 CHAR), EDIT_ACTION VARCHAR2(256 CHAR), TITLE_URL VARCHAR2(256 CHAR), PORTLET_DESC VARCHAR2(1024 CHAR), WIDTH NUMBER(10), HEIGHT NUMBER(10), HTML_CODE VARCHAR2(4000 CHAR) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_PORTLET_PROPERTY add primary key (PORTLET_ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table P_RESOURCES ( RES_ID VARCHAR2(32 CHAR) not null, RES_TYPE VARCHAR2(255 CHAR), RES_NAME VARCHAR2(255 CHAR), RES_PATH VARCHAR2(255 CHAR), RES_STATUS VARCHAR2(255 CHAR), RES_WIDTH NUMBER(10), RES_HEIGHT NUMBER(10), FILE_SIZE NUMBER(19), SITE_ID VARCHAR2(255 CHAR), SITE_NAME VARCHAR2(255 CHAR), RES_CODE VARCHAR2(255 CHAR), APP_ID VARCHAR2(255) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_RESOURCES add primary key (RES_ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table P_SITE_MANAGE ( SITE_ID VARCHAR2(32 CHAR) not null, SITE_NO VARCHAR2(255 CHAR), SITE_NAME VARCHAR2(255 CHAR), P_SITE_NO VARCHAR2(255 CHAR), P_SITE_NAME VARCHAR2(255 CHAR), DISP_SN NUMBER(10), SITE_STATUS VARCHAR2(255 CHAR), CREATE_TIME TIMESTAMP(6), USER_NO VARCHAR2(255 CHAR), DEPT_NO VARCHAR2(255 CHAR), SITE_ADDR VARCHAR2(255 CHAR), LOGO_PATH VARCHAR2(255 CHAR), COPYRIGHT_CONTENT VARCHAR2(255 CHAR), TYPE_CODE VARCHAR2(255 CHAR), NAVI_ID VARCHAR2(255 CHAR), APP_ID VARCHAR2(255) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_SITE_MANAGE add primary key (SITE_ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_SITE_MANAGE add constraint FK21A8AFEECB2F2617 foreign key (P_SITE_NO) references P_SITE_MANAGE (SITE_ID); create table P_SYS_PARAM ( CODE_ID VARCHAR2(32 CHAR) not null, CODE_TYPE VARCHAR2(255 CHAR), CODE_VALUE VARCHAR2(255 CHAR), CODE_NAME VARCHAR2(255 CHAR), P_CODE VARCHAR2(255 CHAR), DISP_SN NUMBER(10), CONTENT1 VARCHAR2(255 CHAR), CONTENT2 VARCHAR2(255 CHAR), CONTENT3 VARCHAR2(255 CHAR), CONTENT4 VARCHAR2(255 CHAR), CONTENT5 VARCHAR2(255 CHAR) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_SYS_PARAM add primary key (CODE_ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table P_THEME_DEFINITION ( THEME_CODE VARCHAR2(32 CHAR) not null, THEME_NAME VARCHAR2(256 CHAR), THEME_PICPATH VARCHAR2(256 CHAR), THEME_CONTENT VARCHAR2(256 CHAR), CREATE_DATE DATE, MODIFY_DATE DATE, THEME_PATH VARCHAR2(255 CHAR), APP_ID VARCHAR2(255) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_THEME_DEFINITION add primary key (THEME_CODE) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table P_TMPL ( TMPL_ID VARCHAR2(32 CHAR) not null, TMPL_NAME VARCHAR2(100 CHAR), TMPL_ADDR VARCHAR2(4000 CHAR), TMPL_STATUS VARCHAR2(10 CHAR), TMPL_CODE VARCHAR2(8 CHAR), TMPL_PIC_ADDR VARCHAR2(255 CHAR), DISP_SN NUMBER(10), CREATE_TIME TIMESTAMP(6), UPDATE_TIME TIMESTAMP(6), TMPL_STYLE_ADDR VARCHAR2(255 CHAR), APP_ID VARCHAR2(255) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_TMPL add primary key (TMPL_ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table P_USER_PAGE ( PAGE_ID VARCHAR2(32 CHAR) not null, PAGE_NO VARCHAR2(32 CHAR), PAGE_TITLE VARCHAR2(256 CHAR), DISP_SN NUMBER(10), LAYOUT_CODE VARCHAR2(32 CHAR), THEME_CODE VARCHAR2(32 CHAR), USER_ID VARCHAR2(256 CHAR), USER_NO VARCHAR2(256 CHAR), USER_NAME VARCHAR2(256 CHAR), IF_DEFAULT NUMBER(10) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_USER_PAGE add primary key (PAGE_ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); create table P_USER_PORTLETINFO ( UP_ID VARCHAR2(32 CHAR) not null, PAGE_ID VARCHAR2(255 CHAR), PORTLET_ID VARCHAR2(32 CHAR), SHOW_NAME VARCHAR2(256 CHAR), USER_ID VARCHAR2(256 CHAR), USER_NO VARCHAR2(256 CHAR), USER_NAME VARCHAR2(256 CHAR), FUNC_ID VARCHAR2(16 CHAR), FUNC_NAME VARCHAR2(256 CHAR), FUNC_ACTION VARCHAR2(256 CHAR), PORTLET_STATUS VARCHAR2(8 CHAR), SORT_NO NUMBER(10), ROW_NO NUMBER(10), DISP_SN NUMBER(10), EDIT_ACTION VARCHAR2(256 CHAR), TITLE_URL VARCHAR2(256 CHAR) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_USER_PORTLETINFO add primary key (UP_ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table P_USER_PORTLETINFO add constraint FK_USER_POR_PORTLET_P_PORTLET_ foreign key (PORTLET_ID) references P_PORTLET_PROPERTY (PORTLET_ID); alter table P_USER_PORTLETINFO add constraint FK_USER_POR_USER_PERS_USER_PAG foreign key (PAGE_ID) references P_USER_PAGE (PAGE_ID); create table BUSINESS_SYSTEM_CODE ( ID VARCHAR2(255) not null, PARENT_ID VARCHAR2(255), REG_CODE VARCHAR2(255), REG_TYPE VARCHAR2(255), REG_NAME VARCHAR2(200) not null, REG_DESC VARCHAR2(500), REG_PROP VARCHAR2(50), REG_ORDER NUMBER(10), REG_VALUE VARCHAR2(1000), REG_STATUS VARCHAR2(32), INDEXLEVEL NUMBER(10), HASCHILD NUMBER(10), LEVEL_CODE VARCHAR2(255), REG_LABEL VARCHAR2(255), PARAM1 VARCHAR2(255 CHAR), PARAM2 VARCHAR2(255 CHAR), PARAM3 VARCHAR2(255 CHAR), PARAM4 VARCHAR2(255 CHAR), PARAM5 VARCHAR2(255 CHAR) ) tablespace $TS pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table BUSINESS_SYSTEM_CODE add primary key (ID) using index tablespace $TS pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); alter table BUSINESS_SYSTEM_CODE add constraint FKA4D2C1C29DFCF1C3 foreign key (PARENT_ID) references BUSINESS_SYSTEM_CODE (ID);
{ "content_hash": "bf5e38a2ad988af8c7a1db4ed43094c5", "timestamp": "", "source": "github", "line_count": 1241, "max_line_length": 80, "avg_line_length": 19.079774375503625, "alnum_prop": 0.6383140467944928, "repo_name": "winture/wt-studio", "id": "cb25dc88b1ea37536a2a1d2839b682e1f09e2330", "size": "23678", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "com.wt.studio.plugin.wizard.projects/src/com/wt/studio/plugin/wizard/projects/dbhelp/V2.3/0_hea_db.sql", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "351784" }, { "name": "Java", "bytes": "2526799" }, { "name": "JavaScript", "bytes": "924879" }, { "name": "Shell", "bytes": "28562" }, { "name": "XSLT", "bytes": "7140" } ], "symlink_target": "" }
package burai.app.project.editor.input.items; import javafx.scene.control.Slider; import burai.input.namelist.QEValue; import burai.input.namelist.QEValueBuffer; public abstract class QEFXSlider extends QEFXItem<Slider> { private QEValue defaultValue; protected QEFXSlider(QEValueBuffer valueBuffer, Slider controlItem, QEValue defaultValue) { super(valueBuffer, controlItem); this.defaultValue = defaultValue; this.setupSlider(); } protected abstract void setToValueBuffer(double value); protected abstract void setToControlItem(QEValue qeValue); private void setupSlider() { if (this.valueBuffer.hasValue()) { this.onValueChanged(this.valueBuffer.getValue()); } else { this.setToControlItem(this.defaultValue); this.setToValueBuffer(this.controlItem.getValue()); } this.controlItem.valueProperty().addListener(o -> { double value = this.controlItem.getValue(); this.setToValueBuffer(value); }); } @Override protected void onValueChanged(QEValue qeValue) { if (qeValue == null) { this.setToControlItem(this.defaultValue); } else { this.setToControlItem(qeValue); } } }
{ "content_hash": "a72295f43ebb031611e6193fcd9e9a6c", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 95, "avg_line_length": 29.130434782608695, "alnum_prop": 0.641044776119403, "repo_name": "BURAI-team/burai", "id": "bc1e8200d2f496a863eba9252192f71118e9255f", "size": "1960", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/burai/app/project/editor/input/items/QEFXSlider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "35888" }, { "name": "Java", "bytes": "2874039" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <Request xsi:schemaLocation="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17 http://docs.oasis-open.org/xacml/3.0/xacml-core-v3-schema-wd-17.xsd" ReturnPolicyIdList="false" CombinedDecision="false" xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Attributes Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"> <Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Julius Hibbert</AttributeValue> </Attribute> <Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:2.0:conformance-test:age"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">45</AttributeValue> </Attribute> <Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:2.0:conformance-test:age"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#double">45.3</AttributeValue> </Attribute> </Attributes> <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"> <Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">http://medico.com/record/patient/BartSimpson</AttributeValue> </Attribute> </Attributes> <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action"> <Attribute IncludeInResult="false" AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"> <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">read</AttributeValue> </Attribute> </Attributes> <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" /> </Request>
{ "content_hash": "e98fd6cd91df95320b7639dc33584bc0", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 306, "avg_line_length": 64.0952380952381, "alnum_prop": 0.7440564635958395, "repo_name": "OpenConext/incubator-openaz-openconext", "id": "f548caaf4ccdef9e117acccefbc3103fb4718da2", "size": "2692", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "openaz-xacml-test/src/test/resources/testsets/conformance/xacml3.0-ct-v.0.4/IIA012Request.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "248858" }, { "name": "Java", "bytes": "5560443" }, { "name": "PLpgSQL", "bytes": "198552" } ], "symlink_target": "" }
<?php require_once(__DIR__ . '/../../vendor/autoload.php');
{ "content_hash": "95ad19311a20d778f7d61dd9b313f36f", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 53, "avg_line_length": 30, "alnum_prop": 0.5666666666666667, "repo_name": "powder96/numbers.php", "id": "9e0037c908643735a8b85eaf1a0db24b010a5718", "size": "60", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/NumbersPHP/bootstrap.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "105814" }, { "name": "Shell", "bytes": "525" } ], "symlink_target": "" }
<!doctype html> <html> <head> <title> About | Afnan Ahmad </title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="/assets/css/main.css"> <link rel="stylesheet" href="/assets/css/syntax.css"> <!-- RSS-v2.0 <link href="/feed.xml" type="application/rss+xml" rel="alternate" title="Afnan Ahmad | "/> //--> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Serif:400,400italic,700%7CPT+Sans:400"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Code+Pro"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Quattrocento+Sans"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css"> <script type="text/javascript" async src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_CHTML"> </script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-109491985-1', 'auto'); ga('send', 'pageview'); </script> <!-- Use Atom --> <link type="application/atom+xml" rel="alternate" href="http://localhost:4000/feed.xml" title="Afnan Ahmad" /> <!-- Use Jekyll SEO plugin --> <!-- Begin Jekyll SEO tag v2.3.0 --> <title>About | Afnan Ahmad</title> <meta property="og:title" content="About" /> <meta property="og:locale" content="en_US" /> <meta name="description" content="RA at YorkU" /> <meta property="og:description" content="RA at YorkU" /> <link rel="canonical" href="http://localhost:4000/menu/about.html" /> <meta property="og:url" content="http://localhost:4000/menu/about.html" /> <meta property="og:site_name" content="Afnan Ahmad" /> <script type="application/ld+json"> {"name":null,"description":"RA at YorkU","author":null,"@type":"WebPage","url":"http://localhost:4000/menu/about.html","publisher":null,"image":null,"headline":"About","dateModified":null,"datePublished":null,"sameAs":null,"mainEntityOfPage":null,"@context":"http://schema.org"}</script> <!-- End Jekyll SEO tag --> </head> <body> <div class="container"> <header class="masthead"> <h3 class="masthead-title"> <a href="/">Afnan Ahmad</a> <small class="masthead-subtitle"></small> <div class="menu"> <nav class="menu-content"> <a href="/menu/about.html">About</a> <a href="/menu/writing.html">Writing</a> <a href="/menu/contact.html">Contact</a> </nav> <nav class="social-icons"> <a href="https://www.google.ca/maps/place/Toronto" target="_blank"><i class="fa fa-map-marker" aria-hidden="true"></i></a> <a href="https://www.github.com/afnanahmad" target="_blank"><i class="fa fa-github" aria-hidden="true"></i></a> <a href="https://www.linkedin.com/in/afnanahmad/" target="_blank"><i class="fa fa-linkedin" aria-hidden="true"></i></a> <a href="https://stackoverflow.com/users/1531669/afnan" target="_blank"><i class="fa fa-stack-overflow" aria-hidden="true"></i></a> <a href="mailto:afnanahmad@live.com" target="_blank"><i class="fa fa-envelope" aria-hidden="true"></i></a> <a href="https://afnanahmad.com/feed.xml" target="_blank"><i class="fa fa-rss-square" aria-hidden="true"></i></a> </nav> </div> </h3> </header> <div class="post-container"> <h1> About </h1> <p>I’m currently a Research Assistant at York University. Doing research in Augmented Reality and Virtual Reality.</p> </div> <footer class="footer"> <a href="https://www.google.ca/maps/place/Toronto" target="_blank"><i class="fa fa-map-marker" aria-hidden="true"></i></a> <a href="https://www.github.com/afnanahmad" target="_blank"><i class="fa fa-github" aria-hidden="true"></i></a> <a href="https://www.linkedin.com/in/afnanahmad/" target="_blank"><i class="fa fa-linkedin" aria-hidden="true"></i></a> <a href="https://stackoverflow.com/users/1531669/afnan" target="_blank"><i class="fa fa-stack-overflow" aria-hidden="true"></i></a> <a href="mailto:afnanahmad@live.com" target="_blank"><i class="fa fa-envelope" aria-hidden="true"></i></a> <a href="https://afnanahmad.com/feed.xml" target="_blank"><i class="fa fa-rss-square" aria-hidden="true"></i></a> <div class="post-date"><a href="/menu/about.html">Copyright © 2018 Afnan Ahmad</a></div> </footer> </div> </body> </html>
{ "content_hash": "b33ccaa51e8efe3c46b058e0002c84a8", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 287, "avg_line_length": 36.08461538461538, "alnum_prop": 0.6459177147729696, "repo_name": "afnanahmad/afnanahmad.github.io", "id": "ceed7b28fe0e8d0206b2c249afa5bbc64d3279b9", "size": "4694", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_site/menu/about.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18800" }, { "name": "HTML", "bytes": "41213" } ], "symlink_target": "" }
<?php namespace Library\Validators; use Library\Validator; class FileImageNotNullValidator extends Validator { protected $name; public function __construct($errorMessage, $name) { parent::__construct($errorMessage); $this->setName($name); } public function setName($name) { $this->name = $name; } public function isValid($value) { if (isset($_FILES[$this->name]) == true AND $_FILES[$this->name]["error"] == 0) { $formats = array("image/jpeg", "image/jpg", "image/png", "image/pjpeg"); return in_array($_FILES[$this->name]["type"], $formats); } return false; } }
{ "content_hash": "4972722b8e6559c44954f933b54d7d26", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 83, "avg_line_length": 18.17142857142857, "alnum_prop": 0.6163522012578616, "repo_name": "ludovicroland/rolandl-php-framework", "id": "dfb5654ea670e19b00eb51de7190e31e1f4da76e", "size": "636", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Library/Validators/FileImageNotNullValidator.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "38538" } ], "symlink_target": "" }
[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Cloud%20API%20Server%20Question) or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Cloud%20API%20Server%20Question) ## ON-PREMISE OFFLINE SDK [Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme) [Explore Documentation](https://bytescout.com/documentation/index.html?utm_source=github-readme) [Explore Source Code Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/) [Sign Up For Online Training](https://academy.bytescout.com/) ## ON-DEMAND REST WEB API [Get your API key](https://app.pdf.co/signup?utm_source=github-readme) [Security](https://pdf.co/security) [Explore Web API Documentation](https://apidocs.pdf.co?utm_source=github-readme) [Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API) ## VIDEO REVIEW [https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8) <!-- code block begin --> ##### **GetInvoiceInfoFromUploadedFile.ps1:** ``` # Please NOTE: In this sample we're assuming Cloud Api Server is hosted at "https://localhost". # If it's not then please replace this with with your hosting url. # The authentication key (API Key). # Get your own by registering at https://app.pdf.co/documentation/api $API_KEY = "***********************************" # Source PDF file to get information $SourceFile = ".\sample.pdf" # 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE. # * If you already have a direct file URL, skip to the step 3. # Prepare URL for `Get Presigned URL` API call $query = "https://localhost/file/upload/get-presigned-url?contenttype=application/octet-stream&name=" + ` [System.IO.Path]::GetFileName($SourceFile) $query = [System.Uri]::EscapeUriString($query) try { # Execute request $jsonResponse = Invoke-RestMethod -Method Get -Headers @{ "x-api-key" = $API_KEY } -Uri $query if ($jsonResponse.error -eq $false) { # Get URL to use for the file upload $uploadUrl = $jsonResponse.presignedUrl # Get URL of uploaded file to use with later API calls $uploadedFileUrl = $jsonResponse.url # 2. UPLOAD THE FILE TO CLOUD. $r = Invoke-WebRequest -Method Put -Headers @{ "x-api-key" = $API_KEY; "content-type" = "application/octet-stream" } -InFile $SourceFile -Uri $uploadUrl if ($r.StatusCode -eq 200) { # 3. GET INFORMATION FROM UPLOADED FILE # Prepare URL for `Invoice Parser` API call $query = "https://localhost/pdf/invoiceparser" # Prepare request body (will be auto-converted to JSON by Invoke-RestMethod) # See documentation: https://apidocs.pdf.co $body = @{ "url" = $uploadedFileUrl "inline" = True } | ConvertTo-Json # Execute request $response = Invoke-WebRequest -Method Post -Headers @{ "x-api-key" = $API_KEY; "Content-Type" = "application/json" } -Body $body -Uri $query $jsonResponse = $response.Content | ConvertFrom-Json if ($jsonResponse.error -eq $false) { # Display PDF document information Write-Host $jsonResponse.body } else { # Display service reported error Write-Host $jsonResponse.message } } else { # Display request error status Write-Host $r.StatusCode + " " + $r.StatusDescription } } else { # Display service reported error Write-Host $jsonResponse.message } } catch { # Display request error Write-Host $_.Exception } ``` <!-- code block end --> <!-- code block begin --> ##### **run.bat:** ``` @echo off powershell -NoProfile -ExecutionPolicy Bypass -Command "& .\GetInvoiceInfoFromUploadedFile.ps1" echo Script finished with errorlevel=%errorlevel% pause ``` <!-- code block end -->
{ "content_hash": "5bf56f0fbebedc7bb76e93b8ed0ceef4", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 160, "avg_line_length": 33.36, "alnum_prop": 0.640767386091127, "repo_name": "bytescout/ByteScout-SDK-SourceCode", "id": "3200913c3d09e3d633a1d741a49a8d18f220c9db", "size": "4764", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Cloud API Server/Invoice Parser API/PowerShell/Get Invoice Info From Uploaded File/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP.NET", "bytes": "364116" }, { "name": "Apex", "bytes": "243500" }, { "name": "Batchfile", "bytes": "151832" }, { "name": "C", "bytes": "224568" }, { "name": "C#", "bytes": "12909855" }, { "name": "C++", "bytes": "440474" }, { "name": "CSS", "bytes": "56817" }, { "name": "Classic ASP", "bytes": "46655" }, { "name": "Dockerfile", "bytes": "776" }, { "name": "Gherkin", "bytes": "3386" }, { "name": "HTML", "bytes": "17276296" }, { "name": "Java", "bytes": "1483408" }, { "name": "JavaScript", "bytes": "3033610" }, { "name": "PHP", "bytes": "838746" }, { "name": "Pascal", "bytes": "398090" }, { "name": "PowerShell", "bytes": "715204" }, { "name": "Python", "bytes": "703542" }, { "name": "QMake", "bytes": "880" }, { "name": "TSQL", "bytes": "3080" }, { "name": "VBA", "bytes": "383773" }, { "name": "VBScript", "bytes": "1504410" }, { "name": "Visual Basic .NET", "bytes": "9489450" } ], "symlink_target": "" }
package com.sun.tools.javadoc; import com.sun.javadoc.*; import static com.sun.javadoc.LanguageVersion.*; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.util.List; /** * Implementation of <code>WildcardType</code>, which * represents a wildcard type. * * @author Scott Seligman * @since 1.5 */ public class WildcardTypeImpl extends AbstractTypeImpl implements WildcardType { WildcardTypeImpl(DocEnv env, Type.WildcardType type) { super(env, type); } /** * Return the upper bounds of this wildcard type argument * as given by the <i>extends</i> clause. * Return an empty array if no such bounds are explicitly given. */ public com.sun.javadoc.Type[] extendsBounds() { return TypeMaker.getTypes(env, getExtendsBounds((Type.WildcardType)type)); } /** * Return the lower bounds of this wildcard type argument * as given by the <i>super</i> clause. * Return an empty array if no such bounds are explicitly given. */ public com.sun.javadoc.Type[] superBounds() { return TypeMaker.getTypes(env, getSuperBounds((Type.WildcardType)type)); } /** * Return the ClassDoc of the erasure of this wildcard type. */ public ClassDoc asClassDoc() { return env.getClassDoc((ClassSymbol)env.types.erasure(type).tsym); } public WildcardType asWildcardType() { return this; } public String typeName() { return "?"; } public String qualifiedTypeName() { return "?"; } public String simpleTypeName() { return "?"; } public String toString() { return wildcardTypeToString(env, (Type.WildcardType)type, true); } /** * Return the string form of a wildcard type ("?") along with any * "extends" or "super" clause. Delimiting brackets are not * included. Class names are qualified if "full" is true. */ static String wildcardTypeToString(DocEnv env, Type.WildcardType wildThing, boolean full) { if (env.legacyDoclet) { return TypeMaker.getTypeName(env.types.erasure(wildThing), full); } StringBuffer s = new StringBuffer("?"); List<Type> bounds = getExtendsBounds(wildThing); if (bounds.nonEmpty()) { s.append(" extends "); } else { bounds = getSuperBounds(wildThing); if (bounds.nonEmpty()) { s.append(" super "); } } boolean first = true; // currently only one bound is allowed for (Type b : bounds) { if (!first) { s.append(" & "); } s.append(TypeMaker.getTypeString(env, b, full)); first = false; } return s.toString(); } private static List<Type> getExtendsBounds(Type.WildcardType wild) { return wild.isSuperBound() ? List.<Type>nil() : List.of(wild.type); } private static List<Type> getSuperBounds(Type.WildcardType wild) { return wild.isExtendsBound() ? List.<Type>nil() : List.of(wild.type); } }
{ "content_hash": "a0eca86b79928bd9442f2ddc0b278f8f", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 83, "avg_line_length": 30.166666666666668, "alnum_prop": 0.6006752608962553, "repo_name": "ilivoo/ilivoo", "id": "8f92212e0bfe8cb2eee92f058d2a25af9c80b5ca", "size": "4470", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "java_tools/src/com/sun/tools/javadoc/WildcardTypeImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9273" }, { "name": "HTML", "bytes": "33783" }, { "name": "Java", "bytes": "8744908" }, { "name": "JavaScript", "bytes": "19" }, { "name": "Roff", "bytes": "370" } ], "symlink_target": "" }
source ../utils/helper.sh check_env || exit 1 check_mvn || exit 1 check_running_cp ${CONFLUENT} || exit check_timeout || exit 1 check_sqlite3 || exit 1 ./stop.sh mvn clean compile echo "auto.offset.reset=earliest" >> $CONFLUENT_HOME/etc/ksqldb/ksql-server.properties confluent-hub install --no-prompt confluentinc/kafka-connect-jdbc:$KAFKA_CONNECT_JDBC_VERSION confluent local services start # Create the SQL table TABLE_LOCATIONS=/usr/local/lib/table.locations prep_sqltable_locations # -------------------------------------------------------------- PACKAGE="consoleproducer" TOPIC="$PACKAGE-locations" echo -e "\n========== $PACKAGE: Example 1: Kafka console producer -> Key:String and Value:String" sleep 2 # Write the contents of the file TABLE_LOCATIONS to a Topic, where the id is the message key and the name and sale are the message value. cat $TABLE_LOCATIONS | \ confluent local services kafka produce $TOPIC \ --property parse.key=true \ --property key.separator='|' &>/dev/null # Run the Consumer to print the key as well as the value from the Topic confluent local services kafka consume $TOPIC \ --from-beginning \ --property print.key=true \ --max-messages 10 # Run the Java consumer application timeout 10s mvn -q exec:java -Dexec.mainClass=io.confluent.examples.connectandstreams.$PACKAGE.StreamsIngest # -------------------------------------------------------------- PACKAGE="jdbcjson" TOPIC="$PACKAGE-locations" echo -e "\n========== $PACKAGE: Example 2: JDBC source connector with Single Message Transformations -> Key:Long and Value:JSON" sleep 2 # Run source connector confluent local services connect connector unload $PACKAGE &>/dev/null confluent local services connect connector config $PACKAGE --config ./$PACKAGE-connector.properties &>/dev/null # Run the Consumer to print the key as well as the value from the Topic confluent local services kafka consume $TOPIC \ --from-beginning \ --property print.key=true \ --key-deserializer org.apache.kafka.common.serialization.LongDeserializer \ --max-messages 10 # Run the Java consumer application timeout 10s mvn -q exec:java -Dexec.mainClass=io.confluent.examples.connectandstreams.$PACKAGE.StreamsIngest # -------------------------------------------------------------- PACKAGE="jdbcspecificavro" TOPIC="$PACKAGE-locations" echo -e "\n========== $PACKAGE: Example 3: JDBC source connector with SpecificAvro -> Key:String(null) and Value:SpecificAvro" sleep 2 # Run source connector confluent local services connect connector unload $PACKAGE &>/dev/null confluent local services connect connector config $PACKAGE --config ./$PACKAGE-connector.properties &>/dev/null # Run the Consumer to print the key as well as the value from the Topic confluent local services kafka consume $TOPIC \ --value-format avro \ --from-beginning \ --property print.key=true \ --max-messages 10 # Run the Java consumer application timeout 10s mvn -q exec:java -Dexec.mainClass=io.confluent.examples.connectandstreams.$PACKAGE.StreamsIngest # -------------------------------------------------------------- PACKAGE="jdbcgenericavro" TOPIC="$PACKAGE-locations" echo -e "\n========== $PACKAGE: Example 4: JDBC source connector with GenericAvro -> Key:String(null) and Value:GenericAvro" sleep 2 # Run source connector confluent local services connect connector unload $PACKAGE &>/dev/null confluent local services connect connector config $PACKAGE --config ./$PACKAGE-connector.properties &>/dev/null # Run the Consumer to print the key as well as the value from the Topic confluent local services kafka consume $TOPIC \ --value-format avro \ --from-beginning \ --property print.key=true \ --max-messages 10 # Run the Java consumer application timeout 10s mvn -q exec:java -Dexec.mainClass=io.confluent.examples.connectandstreams.$PACKAGE.StreamsIngest # -------------------------------------------------------------- PACKAGE="javaproducer" TOPIC="$PACKAGE-locations" echo -e "\n========== $PACKAGE: Example 5: Java client producer with SpecificAvro -> Key:Long and Value:SpecificAvro" sleep 2 # Producer timeout 20s mvn -q exec:java -Dexec.mainClass=io.confluent.examples.connectandstreams.$PACKAGE.Driver -Dexec.args="localhost:9092 http://localhost:8081 /usr/local/lib/table.locations" curl -X GET http://localhost:8081/subjects/$TOPIC-value/versions/1 # Run the Consumer to print the key as well as the value from the Topic confluent local services kafka consume $TOPIC \ --value-format avro \ --key-deserializer org.apache.kafka.common.serialization.LongDeserializer \ --from-beginning \ --property print.key=true \ --max-messages 10 # Consumer timeout 10s mvn -q exec:java -Dexec.mainClass=io.confluent.examples.connectandstreams.$PACKAGE.StreamsIngest -Dexec.args="localhost:9092 http://localhost:8081" # -------------------------------------------------------------- PACKAGE="jdbcavroksql" TOPIC="$PACKAGE-locations" echo -e "\n========== $PACKAGE: Example 6: JDBC source connector with Avro to KSQL -> Key:String(null) and Value:Avro" sleep 2 # Run source connector confluent local services connect connector unload $PACKAGE &>/dev/null confluent local services connect connector config $PACKAGE --config ./$PACKAGE-connector.properties &>/dev/null # Run the Consumer to print the key as well as the value from the Topic confluent local services kafka consume $TOPIC \ --value-format avro \ --from-beginning \ --property print.key=true \ --max-messages 10 # Create KSQL queries ksql http://localhost:8088 <<EOF run script '${PACKAGE}_statements.sql'; exit ; EOF # Read queries timeout 5s ksql http://localhost:8088 <<EOF SELECT * FROM JDBCAVROKSQLLOCATIONSWITHKEY EMIT CHANGES LIMIT 10; exit ; EOF timeout 5s ksql http://localhost:8088 <<EOF SELECT * FROM COUNTLOCATIONS EMIT CHANGES LIMIT 5; exit ; EOF timeout 5s ksql http://localhost:8088 <<EOF SELECT * FROM SUMLOCATIONS EMIT CHANGES LIMIT 5; exit ; EOF
{ "content_hash": "5cd063d4c3bf39dc837f54456d422d0d", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 183, "avg_line_length": 35.35329341317365, "alnum_prop": 0.7164634146341463, "repo_name": "confluentinc/examples", "id": "e30faa338b0e5ae485b80e7f08325a2ce8c6e667", "size": "5934", "binary": false, "copies": "1", "ref": "refs/heads/7.3.0-post", "path": "connect-streams-pipeline/start.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "56092" }, { "name": "C#", "bytes": "6948" }, { "name": "Clojure", "bytes": "5045" }, { "name": "Dockerfile", "bytes": "1357" }, { "name": "Emacs Lisp", "bytes": "131" }, { "name": "Go", "bytes": "9030" }, { "name": "Groovy", "bytes": "12257" }, { "name": "Java", "bytes": "150716" }, { "name": "JavaScript", "bytes": "8721" }, { "name": "Kotlin", "bytes": "10370" }, { "name": "Makefile", "bytes": "44329" }, { "name": "Python", "bytes": "41625" }, { "name": "Ruby", "bytes": "6803" }, { "name": "Rust", "bytes": "6213" }, { "name": "Scala", "bytes": "10233" }, { "name": "Shell", "bytes": "333204" }, { "name": "Smarty", "bytes": "1478" } ], "symlink_target": "" }
import _ from 'underscore' import View from '../base' import moment from 'moment' import categoryProvider from '../../providers/category' import taskProvider from '../../providers/task' import teamProvider from '../../providers/team' class EventBaseView extends View { renderEvent (eventName, eventData, createdAt) { let r = null switch (eventName) { case 'updateContest': { r = window.volgactf.qualifier.templates.eventLogUpdateContest({ _: _, moment: moment, createdAt: createdAt, contest: eventData }) break } case 'createCategory': { r = window.volgactf.qualifier.templates.eventLogCreateCategory({ _: _, moment: moment, createdAt: createdAt, category: eventData }) break } case 'updateCategory': { r = window.volgactf.qualifier.templates.eventLogUpdateCategory({ _: _, moment: moment, createdAt: createdAt, category: eventData }) break } case 'deleteCategory': { r = window.volgactf.qualifier.templates.eventLogDeleteCategory({ _: _, moment: moment, createdAt: createdAt, category: eventData }) break } case 'createPost': { r = window.volgactf.qualifier.templates.eventLogCreatePost({ _: _, moment: moment, createdAt: createdAt, post: eventData }) break } case 'updatePost': { r = window.volgactf.qualifier.templates.eventLogUpdatePost({ _: _, moment: moment, createdAt: createdAt, post: eventData }) break } case 'deletePost': { r = window.volgactf.qualifier.templates.eventLogDeletePost({ _: _, moment: moment, createdAt: createdAt, post: eventData }) break } case 'createSupervisor': { r = window.volgactf.qualifier.templates.eventLogCreateSupervisor({ _: _, moment: moment, createdAt: createdAt, supervisor: eventData }) break } case 'deleteSupervisor': { r = window.volgactf.qualifier.templates.eventLogDeleteSupervisor({ _: _, moment: moment, createdAt: createdAt, supervisor: eventData }) break } case 'updateSupervisorPassword': { r = window.volgactf.qualifier.templates.eventLogUpdateSupervisorPassword({ _: _, moment: moment, createdAt: createdAt, supervisor: eventData }) break } case 'loginSupervisor': { r = window.volgactf.qualifier.templates.eventLogLoginSupervisor({ _: _, moment: moment, createdAt: createdAt, supervisor: eventData.supervisor, geoIP: eventData.geoIP }) break } case 'logoutSupervisor': { r = window.volgactf.qualifier.templates.eventLogLogoutSupervisor({ _: _, moment: moment, createdAt: createdAt, supervisor: eventData }) break } case 'createRemoteChecker': { r = window.volgactf.qualifier.templates.eventLogCreateRemoteChecker({ _: _, moment: moment, createdAt: createdAt, remoteChecker: eventData }) break } case 'updateRemoteChecker': { r = window.volgactf.qualifier.templates.eventLogUpdateRemoteChecker({ _: _, moment: moment, createdAt: createdAt, remoteChecker: eventData }) break } case 'deleteRemoteChecker': { r = window.volgactf.qualifier.templates.eventLogDeleteRemoteChecker({ _: _, moment: moment, createdAt: createdAt, remoteChecker: eventData }) break } case 'createTask': { r = window.volgactf.qualifier.templates.eventLogCreateTask({ _: _, moment: moment, createdAt: createdAt, task: eventData }) break } case 'updateTask': { r = window.volgactf.qualifier.templates.eventLogUpdateTask({ _: _, moment: moment, createdAt: createdAt, task: eventData }) break } case 'openTask': { r = window.volgactf.qualifier.templates.eventLogOpenTask({ _: _, moment: moment, createdAt: createdAt, task: eventData }) break } case 'closeTask': { r = window.volgactf.qualifier.templates.eventLogCloseTask({ _: _, moment: moment, createdAt: createdAt, task: eventData }) break } case 'createTaskCategory': { const task = _.findWhere(taskProvider.getTaskPreviews(), { id: eventData.taskId }) const category = _.findWhere(categoryProvider.getCategories(), { id: eventData.categoryId }) if (task && category) { r = window.volgactf.qualifier.templates.eventLogCreateTaskCategory({ _: _, moment: moment, createdAt: createdAt, task: task, category: category }) } break } case 'deleteTaskCategory': { const task = _.findWhere(taskProvider.getTaskPreviews(), { id: eventData.taskId }) const category = _.findWhere(categoryProvider.getCategories(), { id: eventData.categoryId }) if (task && category) { r = window.volgactf.qualifier.templates.eventLogDeleteTaskCategory({ _: _, moment: moment, createdAt: createdAt, task: task, category: category }) } break } case 'createTaskValue': { const task = _.findWhere(taskProvider.getTaskPreviews(), { id: eventData.taskId }) if (task) { r = window.volgactf.qualifier.templates.eventLogCreateTaskValue({ _: _, moment: moment, createdAt: createdAt, task: task, taskValue: eventData }) } break } case 'updateTaskValue': { const task = _.findWhere(taskProvider.getTaskPreviews(), { id: eventData.taskId }) if (task) { r = window.volgactf.qualifier.templates.eventLogUpdateTaskValue({ _: _, moment: moment, createdAt: createdAt, task: task, taskValue: eventData }) } break } case 'createTaskRewardScheme': { const task = _.findWhere(taskProvider.getTaskPreviews(), { id: eventData.taskId }) if (task) { r = window.volgactf.qualifier.templates.eventLogCreateTaskRewardScheme({ _: _, moment: moment, createdAt: createdAt, task: task, taskRewardScheme: eventData }) } break } case 'updateTaskRewardScheme': { const task = _.findWhere(taskProvider.getTaskPreviews(), { id: eventData.taskId }) if (task) { r = window.volgactf.qualifier.templates.eventLogUpdateTaskRewardScheme({ _: _, moment: moment, createdAt: createdAt, task: task, taskRewardScheme: eventData }) } break } case 'createTeam': { r = window.volgactf.qualifier.templates.eventLogCreateTeam({ _: _, moment: moment, createdAt: createdAt, team: eventData }) break } case 'updateTeamEmail': { r = window.volgactf.qualifier.templates.eventLogUpdateTeamEmail({ _: _, moment: moment, createdAt: createdAt, team: eventData }) break } case 'updateTeamProfile': { r = window.volgactf.qualifier.templates.eventLogUpdateTeamProfile({ _: _, moment: moment, createdAt: createdAt, team: eventData }) break } case 'updateTeamPassword': { r = window.volgactf.qualifier.templates.eventLogUpdateTeamPassword({ _: _, moment: moment, createdAt: createdAt, team: eventData }) break } case 'updateTeamLogo': { r = window.volgactf.qualifier.templates.eventLogUpdateTeamLogo({ _: _, moment: moment, createdAt: createdAt, team: eventData }) break } case 'qualifyTeam': { r = window.volgactf.qualifier.templates.eventLogQualifyTeam({ _: _, moment: moment, createdAt: createdAt, team: eventData }) break } case 'disqualifyTeam': { r = window.volgactf.qualifier.templates.eventLogDisqualifyTeam({ _: _, moment: moment, createdAt: createdAt, team: eventData }) break } case 'loginTeam': { r = window.volgactf.qualifier.templates.eventLogLoginTeam({ _: _, moment: moment, createdAt: createdAt, team: eventData.team, geoIP: eventData.geoIP }) break } case 'logoutTeam': { r = window.volgactf.qualifier.templates.eventLogLogoutTeam({ _: _, moment: moment, createdAt: createdAt, team: eventData }) break } case 'createTeamTaskHit': { const team = _.findWhere(teamProvider.getTeams(), { id: eventData.teamId }) const task = _.findWhere(taskProvider.getTaskPreviews(), { id: eventData.taskId }) if (team && task) { r = window.volgactf.qualifier.templates.eventLogCreateTeamTaskHit({ _: _, moment: moment, createdAt: createdAt, team: team, task: task, teamTaskHit: eventData }) } break } case 'createTeamTaskHitAttempt': { const team = _.findWhere(teamProvider.getTeams(), { id: eventData.teamId }) const task = _.findWhere(taskProvider.getTaskPreviews(), { id: eventData.taskId }) if (team && task) { r = window.volgactf.qualifier.templates.eventLogCreateTeamTaskHitAttempt({ _: _, moment: moment, createdAt: createdAt, team: team, task: task, teamTaskHitAttempt: eventData }) } break } case 'createTeamTaskReview': { const team = _.findWhere(teamProvider.getTeams(), { id: eventData.teamId }) const task = _.findWhere(taskProvider.getTaskPreviews(), { id: eventData.taskId }) if (team && task) { r = window.volgactf.qualifier.templates.eventLogCreateTeamTaskReview({ _: _, moment: moment, createdAt: createdAt, team: team, task: task, teamTaskReview: eventData }) } break } case 'createTaskFile': { const task = _.findWhere(taskProvider.getTaskPreviews(), { id: eventData.taskId }) if (task) { r = window.volgactf.qualifier.templates.eventLogCreateTaskFile({ _: _, moment: moment, createdAt: createdAt, task: task, taskFile: eventData }) } break } case 'deleteTaskFile': { const task = _.findWhere(taskProvider.getTaskPreviews(), { id: eventData.taskId }) if (task) { r = window.volgactf.qualifier.templates.eventLogDeleteTaskFile({ _: _, moment: moment, createdAt: createdAt, task: task, taskFile: eventData }) } break } default: { r = window.volgactf.qualifier.templates.eventLogUnknown({ _: _, moment: moment, eventName: eventName, createdAt: createdAt }) break } } return r } } export default EventBaseView
{ "content_hash": "1b355755d60e982fc89d67556c135056", "timestamp": "", "source": "github", "line_count": 432, "max_line_length": 100, "avg_line_length": 28.916666666666668, "alnum_prop": 0.5280979827089337, "repo_name": "aspyatkin/themis-quals-frontend", "id": "2e711b196531dbb58421724bd79242780a7b28b0", "size": "12492", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/scripts/views/event/base.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5066" }, { "name": "HTML", "bytes": "119185" }, { "name": "JavaScript", "bytes": "192115" } ], "symlink_target": "" }
.code-highlight .highlight .hll { background-color: #ffffcc } .code-highlight .highlight .c { color: #008000 } /* Comment */ .code-highlight .highlight .err { border: 1px solid #FF0000 } /* Error */ .code-highlight .highlight .k { color: #0000ff } /* Keyword */ .code-highlight .highlight .cm { color: #008000 } /* Comment.Multiline */ .code-highlight .highlight .cp { color: #0000ff } /* Comment.Preproc */ .code-highlight .highlight .c1 { color: #008000 } /* Comment.Single */ .code-highlight .highlight .cs { color: #008000 } /* Comment.Special */ .code-highlight .highlight .ge { font-style: italic } /* Generic.Emph */ .code-highlight .highlight .gh { font-weight: bold } /* Generic.Heading */ .code-highlight .highlight .gp { font-weight: bold } /* Generic.Prompt */ .code-highlight .highlight .gs { font-weight: bold } /* Generic.Strong */ .code-highlight .highlight .gu { font-weight: bold } /* Generic.Subheading */ .code-highlight .highlight .kc { color: #0000ff } /* Keyword.Constant */ .code-highlight .highlight .kd { color: #0000ff } /* Keyword.Declaration */ .code-highlight .highlight .kn { color: #0000ff } /* Keyword.Namespace */ .code-highlight .highlight .kp { color: #0000ff } /* Keyword.Pseudo */ .code-highlight .highlight .kr { color: #0000ff } /* Keyword.Reserved */ .code-highlight .highlight .kt { color: #2b91af } /* Keyword.Type */ .code-highlight .highlight .s { color: #a31515 } /* Literal.String */ .code-highlight .highlight .nc { color: #2b91af } /* Name.Class */ .code-highlight .highlight .ow { color: #0000ff } /* Operator.Word */ .code-highlight .highlight .sb { color: #a31515 } /* Literal.String.Backtick */ .code-highlight .highlight .sc { color: #a31515 } /* Literal.String.Char */ .code-highlight .highlight .sd { color: #a31515 } /* Literal.String.Doc */ .code-highlight .highlight .s2 { color: #a31515 } /* Literal.String.Double */ .code-highlight .highlight .se { color: #a31515 } /* Literal.String.Escape */ .code-highlight .highlight .sh { color: #a31515 } /* Literal.String.Heredoc */ .code-highlight .highlight .si { color: #a31515 } /* Literal.String.Interpol */ .code-highlight .highlight .sx { color: #a31515 } /* Literal.String.Other */ .code-highlight .highlight .sr { color: #a31515 } /* Literal.String.Regex */ .code-highlight .highlight .s1 { color: #a31515 } /* Literal.String.Single */ .code-highlight .highlight .ss { color: #a31515 } /* Literal.String.Symbol */
{ "content_hash": "78515254171c91e27be346beacae3b38", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 79, "avg_line_length": 73.45454545454545, "alnum_prop": 0.6856435643564357, "repo_name": "Depado/MarkDownBlog", "id": "e7c35bb7f5bd91acfd7e1f234ade56c4194ac9f0", "size": "2424", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/static/css/syntax/vs.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "113779" }, { "name": "Dockerfile", "bytes": "359" }, { "name": "HTML", "bytes": "40180" }, { "name": "Mako", "bytes": "412" }, { "name": "Python", "bytes": "66380" } ], "symlink_target": "" }
require "spec_helper" feature "Account Creation" do scenario "allows guest to create account" do expect(page).to have_content I18n.t('devise.registrations.signed_up') end end
{ "content_hash": "f7a6e26e219ecb20aa4deb690f555198", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 73, "avg_line_length": 26.142857142857142, "alnum_prop": 0.7540983606557377, "repo_name": "themoonofendor/blog", "id": "010452e5b719c689050854886d949771e5f9561e", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/features/visitor_creates_account_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1698" }, { "name": "CoffeeScript", "bytes": "1055" }, { "name": "HTML", "bytes": "15263" }, { "name": "JavaScript", "bytes": "692" }, { "name": "Ruby", "bytes": "51748" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "bb77c5474ac1057eda17a3a6389beccc", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "480060ef3e55fdac4fe3bda0be5195f14c2ed476", "size": "178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Fragaria/Fragaria monophylla/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using namespace std; using namespace boost; // // Global state // CCriticalSection cs_setpwalletRegistered; set<CWallet*> setpwalletRegistered; CCriticalSection cs_main; CTxMemPool mempool; unsigned int nTransactionsUpdated = 0; map<uint256, CBlockIndex*> mapBlockIndex; uint256 hashGenesisBlock("0x34bbf350c1a09bd6fc6acce64cd4fb9c5204ebe31b16f6eff0be95339cd7ab17"); static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // starting difficulty is 1 / 2^12 CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; CBigNum bnBestChainWork = 0; CBigNum bnBestInvalidWork = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; int64 nTimeBestReceived = 0; CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> mapOrphanBlocksByPrev; map<uint256, CDataStream*> mapOrphanTransactions; map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = "barcoin Signed Message:\n"; double dHashesPerSec; int64 nHPSTimerStart; // Settings int64 nTransactionFee = 0; int64 nMinimumInputValue = CENT / 100; ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.erase(pwalletIn); } } // check whether the passed transaction is from us bool static IsFromMe(CTransaction& tx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) return true; return false; } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->Inventory(hash); } // ask wallets to resend their transactions void static ResendWalletTransactions() { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->ResendWalletTransactions(); } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CDataStream& vMsg) { CTransaction tx; CDataStream(vMsg) >> tx; uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; CDataStream* pvMsg = new CDataStream(vMsg); // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: if (pvMsg->size() > 5000) { printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str()); delete pvMsg; return false; } mapOrphanTransactions[hash] = pvMsg; BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg)); printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(), mapOrphanTransactions.size()); return true; } void static EraseOrphanTx(uint256 hash) { if (!mapOrphanTransactions.count(hash)) return; const CDataStream* pvMsg = mapOrphanTransactions[hash]; CTransaction tx; CDataStream(*pvMsg) >> tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) { mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash); if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty()) mapOrphanTransactionsByPrev.erase(txin.prevout.hash); } delete pvMsg; mapOrphanTransactions.erase(hash); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } ////////////////////////////////////////////////////////////////////////////// // // CTransaction and CTxIndex // bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(prevout.hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::IsStandard() const { if (nVersion > CTransaction::CURRENT_VERSION) return false; BOOST_FOREACH(const CTxIn& txin, vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) return false; if (!txin.scriptSig.IsPushOnly()) return false; } BOOST_FOREACH(const CTxOut& txout, vout) if (!::IsStandard(txout.scriptPubKey)) return false; return true; } // // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // expensive-to-check-upon-redemption script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 // bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const { if (IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prev = GetOutputFor(vin[i], mapInputs); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; int tmpExpected; tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int CTransaction::GetLegacySigOpCount() const { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { if (fClient) { if (hashBlock == 0) return 0; } else { CBlock blockTmp; if (pblock == NULL) { // Load the block this tx is in CTxIndex txindex; if (!CTxDB("r").ReadTxIndex(GetHash(), txindex)) return 0; if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) return 0; pblock = &blockTmp; } // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); } // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); // Size limits if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { if (txout.nValue < 0) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative")); if (txout.nValue > MAX_MONEY) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high")); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs, bool* pfMissingInputs) { if (pfMissingInputs) *pfMissingInputs = false; if (!tx.CheckTransaction()) return error("CTxMemPool::accept() : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx")); // To help v0.1.5 clients who would see it as a negative number if ((int64)tx.nLockTime > std::numeric_limits<int>::max()) return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet"); // Rather not work on nonstandard transactions (unless -testnet) if (!fTestNet && !tx.IsStandard()) return error("CTxMemPool::accept() : nonstandard transaction type"); // Do we already have it? uint256 hash = tx.GetHash(); { LOCK(cs); if (mapTx.count(hash)) return false; } if (fCheckInputs) if (txdb.ContainsTx(hash)) return false; // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = mapNextTx[outpoint].ptx; if (ptxOld->IsFinal()) return false; if (!tx.IsNewerThan(*ptxOld)) return false; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } if (fCheckInputs) { MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { if (fInvalid) return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str()); if (pfMissingInputs) *pfMissingInputs = true; return false; } // Check for non-standard pay-to-script-hash in inputs if (!tx.AreInputsStandard(mapInputs) && !fTestNet) return error("CTxMemPool::accept() : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Don't accept it if it can't get into a block if (nFees < tx.GetMinFee(1000, true, GMF_RELAY)) return error("CTxMemPool::accept() : not enough fees"); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make other's transactions take longer to confirm. if (nFees < MIN_RELAY_TX_FEE) { static CCriticalSection cs; static double dFreeCount; static int64 nLastTime; int64 nNow = GetTime(); { LOCK(cs); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx)) return error("CTxMemPool::accept() : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false)) { return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); } } // Store transaction in memory { LOCK(cs); if (ptxOld) { printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); remove(*ptxOld); } addUnchecked(hash, tx); } ///// are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); printf("CTxMemPool::accept() : accepted %s (poolsz %u)\n", hash.ToString().substr(0,10).c_str(), mapTx.size()); return true; } bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs) { return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs); } bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx) { // Add to memory pool without checking anything. Don't call this directly, // call CTxMemPool::accept to properly check the transaction first. { mapTx[hash] = tx; for (unsigned int i = 0; i < tx.vin.size(); i++) mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); nTransactionsUpdated++; } return true; } bool CTxMemPool::remove(CTransaction &tx) { // Remove transaction from memory pool { LOCK(cs); uint256 hash = tx.GetHash(); if (mapTx.count(hash)) { BOOST_FOREACH(const CTxIn& txin, tx.vin) mapNextTx.erase(txin.prevout); mapTx.erase(hash); nTransactionsUpdated++; } } return true; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetBlocksToMaturity() const { if (!IsCoinBase()) return 0; return max(0, (COINBASE_MATURITY+15) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs) { if (fClient) { if (!IsInMainChain() && !ClientConnectInputs()) return false; return CTransaction::AcceptToMemoryPool(txdb, false); } else { return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs); } } bool CMerkleTx::AcceptToMemoryPool() { CTxDB txdb("r"); return AcceptToMemoryPool(txdb); } bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs) { { LOCK(mempool.cs); // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!tx.IsCoinBase()) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && !txdb.ContainsTx(hash)) tx.AcceptToMemoryPool(txdb, fCheckInputs); } } return AcceptToMemoryPool(txdb, fCheckInputs); } return false; } bool CWalletTx::AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); } int CTxIndex::GetDepthInMainChain() const { // Read block header CBlock block; if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false)) return 0; // Find the block in the index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return 1 + nBestHeight - pindex->nHeight; } // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock) { { LOCK(cs_main); { LOCK(mempool.cs); if (mempool.exists(hash)) { tx = mempool.lookup(hash); return true; } } CTxDB txdb("r"); CTxIndex txindex; if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex)) { CBlock block; if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) hashBlock = block.GetHash(); return true; } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions) { if (!fReadTransactions) { *this = pindex->GetBlockHeader(); return true; } if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions)) return false; if (GetHash() != pindex->GetBlockHash()) return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlock* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } int64 static GetBlockValue(int nHeight, int64 nFees) { int64 nSubsidy = 1 * COIN; return nSubsidy + nFees; } static const int64 nTargetTimespan = 1 * 24 * 60 * 60; // barcoin: 1 days static const int64 nTargetSpacing = 120; // barcoin: 2 minute blocks static const int64 nInterval = nTargetTimespan / nTargetSpacing; // Thanks: Balthazar for suggesting the following fix // https://bitcointalk.org/index.php?topic=182430.msg1904506#msg1904506 static const int64 nReTargetHistoryFact = 4; // look at 4 times the retarget // interval into the block history // // minimum amount of work that could possibly be required nTime after // minimum work required was nBase // unsigned int ComputeMinWork(unsigned int nBase, int64 nTime) { // Testnet has min-difficulty blocks // after nTargetSpacing*2 time between blocks: if (fTestNet && nTime > nTargetSpacing*2) return bnProofOfWorkLimit.GetCompact(); CBigNum bnResult; bnResult.SetCompact(nBase); while (nTime > 0 && bnResult < bnProofOfWorkLimit) { // Maximum 400% adjustment... bnResult *= 4; // ... in best-case exactly 4-times-normal target time nTime -= nTargetTimespan*4; } if (bnResult > bnProofOfWorkLimit) bnResult = bnProofOfWorkLimit; return bnResult.GetCompact(); } unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock) { unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per interval if ((pindexLast->nHeight+1) % nInterval != 0) { // Special difficulty rule for testnet: if (fTestNet) { // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Litecoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = nInterval-1; if ((pindexLast->nHeight+1) != nInterval) blockstogoback = nInterval; if (pindexLast->nHeight > COINFIX1_BLOCK) { blockstogoback = nReTargetHistoryFact * nInterval; } // Go back by what we want to be nReTargetHistoryFact*nInterval blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); // Limit adjustment step int64 nActualTimespan = 0; if (pindexLast->nHeight > COINFIX1_BLOCK) // obtain average actual timespan nActualTimespan = (pindexLast->GetBlockTime() - pindexFirst->GetBlockTime())/nReTargetHistoryFact; else nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan); if (nActualTimespan < nTargetTimespan/4) nActualTimespan = nTargetTimespan/4; if (nActualTimespan > nTargetTimespan*4) nActualTimespan = nTargetTimespan*4; // Retarget CBigNum bnNew; bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= nTargetTimespan; if (bnNew > bnProofOfWorkLimit) bnNew = bnProofOfWorkLimit; /// debug print printf("GetNextWorkRequired RETARGET\n"); printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan); printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str()); printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str()); return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); } bool IsInitialBlockDownload() { if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate()) return true; static int64 nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 10 && pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->bnChainWork > bnBestInvalidWork) { bnBestInvalidWork = pindexNew->bnChainWork; CTxDB().WriteBestInvalidWork(bnBestInvalidWork); uiInterface.NotifyBlocksChanged(); } printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str()); printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n"); } void CBlock::UpdateTime(const CBlockIndex* pindexPrev) { nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); // Updating time can change work required on testnet: if (fTestNet) nBits = GetNextWorkRequired(pindexPrev, this); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) { // Get txindex from current proposed changes txindex = mapTestPool.find(prevout.hash)->second; } else { // Read txindex from txdb fFound = txdb.ReadTxIndex(prevout.hash, txindex); } if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); // Read txPrev CTransaction& txPrev = inputsRet[prevout.hash].second; if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory { LOCK(mempool.cs); if (!mempool.exists(prevout.hash)) return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); txPrev = mempool.lookup(prevout.hash); } if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else { // Get prev tx from disk if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); } } // Make sure all prevout.n's are valid: for (unsigned int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); } } return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64 nResult = 0; for (unsigned int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prevout = GetOutputFor(vin[i], inputs); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); } return nSigOps; } bool CTransaction::ConnectInputs(MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal barcoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64 nValueIn = 0; int64 nFees = 0; for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); // If prev is coinbase, check that it's matured if (txPrev.IsCoinBase()) for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev) if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str()); // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0)) { // only during transition phase for P2SH: do not invoke anti-DoS code for // potentially old clients relaying bad P2SH transactions if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0)) return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str()); return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) { mapTestPool[prevout.hash] = txindex; } } if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); // Tally transaction fees int64 nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); nFees += nTxFee; if (!MoneyRange(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } return true; } bool CTransaction::ClientConnectInputs() { if (IsCoinBase()) return false; // Take over previous transactions' spent pointers { LOCK(mempool.cs); int64 nValueIn = 0; for (unsigned int i = 0; i < vin.size(); i++) { // Get prev tx from single transactions in memory COutPoint prevout = vin[i].prevout; if (!mempool.exists(prevout.hash)) return false; CTransaction& txPrev = mempool.lookup(prevout.hash); if (prevout.n >= txPrev.vout.size()) return false; // Verify signature if (!VerifySignature(txPrev, *this, i, true, 0)) return error("ConnectInputs() : VerifySignature failed"); ///// this is redundant with the mempool.mapNextTx stuff, ///// not sure which I want to get rid of ///// this has to go away now that posNext is gone // // Check for conflicts // if (!txPrev.vout[prevout.n].posNext.IsNull()) // return error("ConnectInputs() : prev tx already used"); // // // Flag outpoints as used // txPrev.vout[prevout.n].posNext = posThisTx; nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return error("ClientConnectInputs() : txin values out of range"); } if (GetValueOut() > nValueIn) return false; } return true; } bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Disconnect in reverse order for (int i = vtx.size()-1; i >= 0; i--) if (!vtx[i].DisconnectInputs(txdb)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = 0; if (!txdb.WriteBlockIndex(blockindexPrev)) return error("DisconnectBlock() : WriteBlockIndex failed"); } return true; } bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Check it again in case a previous version let a bad block in if (!CheckBlock()) return false; // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction id's entirely. // This rule applies to all blocks whose timestamp is after October 1, 2012, 0:00 UTC. int64 nBIP30SwitchTime = 1349049600; bool fEnforceBIP30 = (pindex->nTime > nBIP30SwitchTime); // BIP16 didn't become active until October 1 2012 int64 nBIP16SwitchTime = 1349049600; bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime); //// issue here: it doesn't know the version unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size()); map<uint256, CTxIndex> mapQueuedChanges; int64 nFees = 0; unsigned int nSigOps = 0; BOOST_FOREACH(CTransaction& tx, vtx) { uint256 hashTx = tx.GetHash(); if (fEnforceBIP30) { CTxIndex txindexOld; if (txdb.ReadTxIndex(hashTx, txindexOld)) { BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent) if (pos.IsNull()) return false; } } nSigOps += tx.GetLegacySigOpCount(); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); MapPrevTx mapInputs; if (!tx.IsCoinBase()) { bool fInvalid; if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid)) return false; if (fStrictPayToScriptHash) { // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); } nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash)) return false; } mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size()); } // Write queued txindex changes for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi) { if (!txdb.UpdateTxIndex((*mi).first, (*mi).second)) return error("ConnectBlock() : UpdateTxIndex failed"); } if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = pindex->GetBlockHash(); if (!txdb.WriteBlockIndex(blockindexPrev)) return error("ConnectBlock() : WriteBlockIndex failed"); } // Watch for transactions paying to me BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, true); return true; } bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew) { printf("REORGANIZE\n"); // Find the fork CBlockIndex* pfork = pindexBest; CBlockIndex* plonger = pindexNew; while (pfork != plonger) { while (plonger->nHeight > pfork->nHeight) if (!(plonger = plonger->pprev)) return error("Reorganize() : plonger->pprev is null"); if (pfork == plonger) break; if (!(pfork = pfork->pprev)) return error("Reorganize() : pfork->pprev is null"); } // List of what to disconnect vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str()); printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str()); // Disconnect shorter branch vector<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for disconnect failed"); if (!block.DisconnectBlock(txdb, pindex)) return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); // Queue memory transactions to resurrect BOOST_FOREACH(const CTransaction& tx, block.vtx) if (!tx.IsCoinBase()) vResurrect.push_back(tx); } // Connect longer branch vector<CTransaction> vDelete; for (unsigned int i = 0; i < vConnect.size(); i++) { CBlockIndex* pindex = vConnect[i]; CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for connect failed"); if (!block.ConnectBlock(txdb, pindex)) { // Invalid block return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); } // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) return error("Reorganize() : WriteHashBestChain failed"); // Make sure it's successfully written to disk before changing memory structure if (!txdb.TxnCommit()) return error("Reorganize() : TxnCommit failed"); // Disconnect shorter branch BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) if (pindex->pprev) pindex->pprev->pnext = NULL; // Connect longer branch BOOST_FOREACH(CBlockIndex* pindex, vConnect) if (pindex->pprev) pindex->pprev->pnext = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) tx.AcceptToMemoryPool(txdb, false); // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) mempool.remove(tx); printf("REORGANIZE: done\n"); return true; } // Called from inside SetBestChain: attaches a block to the new best chain being built bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew) { uint256 hash = GetHash(); // Adding to current best branch if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return false; } if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); // Add to current best branch pindexNew->pprev->pnext = pindexNew; // Delete redundant memory transactions BOOST_FOREACH(CTransaction& tx, vtx) mempool.remove(tx); return true; } bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew) { uint256 hash = GetHash(); if (!txdb.TxnBegin()) return error("SetBestChain() : TxnBegin failed"); if (pindexGenesisBlock == NULL && hash == hashGenesisBlock) { txdb.WriteHashBestChain(hash); if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); pindexGenesisBlock = pindexNew; } else if (hashPrevBlock == hashBestChain) { if (!SetBestChainInner(txdb, pindexNew)) return error("SetBestChain() : SetBestChainInner failed"); } else { // the first block in the new chain that will cause it to become the new best chain CBlockIndex *pindexIntermediate = pindexNew; // list of blocks that need to be connected afterwards std::vector<CBlockIndex*> vpindexSecondary; // Reorganize is costly in terms of db load, as it works in a single db transaction. // Try to limit how much needs to be done inside while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork) { vpindexSecondary.push_back(pindexIntermediate); pindexIntermediate = pindexIntermediate->pprev; } if (!vpindexSecondary.empty()) printf("Postponing %i reconnects\n", vpindexSecondary.size()); // Switch to new best branch if (!Reorganize(txdb, pindexIntermediate)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : Reorganize failed"); } // Connect futher blocks BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary) { CBlock block; if (!block.ReadFromDisk(pindex)) { printf("SetBestChain() : ReadFromDisk failed\n"); break; } if (!txdb.TxnBegin()) { printf("SetBestChain() : TxnBegin 2 failed\n"); break; } // errors now are not fatal, we still did a reorganisation to a new chain in a valid way if (!block.SetBestChainInner(txdb, pindex)) break; } } // Update best block in wallet (so we can detect restored wallets) bool fIsInitialDownload = IsInitialBlockDownload(); if (!fIsInitialDownload) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = hash; pindexBest = pindexNew; nBestHeight = pindexBest->nHeight; bnBestChainWork = pindexNew->bnChainWork; nTimeBestReceived = GetTime(); nTransactionsUpdated++; printf("SetBestChain: new best=%s height=%d work=%s date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); // Check the version of the last 100 blocks to see if we need to upgrade: if (!fIsInitialDownload) { int nUpgraded = 0; const CBlockIndex* pindex = pindexBest; for (int i = 0; i < 100 && pindex != NULL; i++) { if (pindex->nVersion > CBlock::CURRENT_VERSION) ++nUpgraded; pindex = pindex->pprev; } if (nUpgraded > 0) printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION); // if (nUpgraded > 100/2) // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user: // strMiscWarning = _("Warning: this version is obsolete, upgrade required"); } std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos) { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str()); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this); if (!pindexNew) return error("AddToBlockIndex() : new CBlockIndex failed"); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork(); CTxDB txdb; if (!txdb.TxnBegin()) return false; txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew)); if (!txdb.TxnCommit()) return false; // New best if (pindexNew->bnChainWork > bnBestChainWork) if (!SetBestChain(txdb, pindexNew)) return false; txdb.Close(); if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 hashPrevBestCoinBase; UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = vtx[0].GetHash(); } uiInterface.NotifyBlocksChanged(); return true; } bool CBlock::CheckBlock() const { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CheckBlock() : size limits failed")); // Check proof of work matches claimed amount if (!CheckProofOfWork(GetPoWHash(), nBits)) return DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60) return error("CheckBlock() : block timestamp too far in the future"); // First transaction must be coinbase, the rest must not be if (vtx.empty() || !vtx[0].IsCoinBase()) return DoS(100, error("CheckBlock() : first tx is not coinbase")); for (unsigned int i = 1; i < vtx.size(); i++) if (vtx[i].IsCoinBase()) return DoS(100, error("CheckBlock() : more than one coinbase")); // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.CheckTransaction()) return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); // Check for duplicate txids. This is caught by ConnectInputs(), // but catching it earlier avoids a potential DoS attack: set<uint256> uniqueTx; BOOST_FOREACH(const CTransaction& tx, vtx) { uniqueTx.insert(tx.GetHash()); } if (uniqueTx.size() != vtx.size()) return DoS(100, error("CheckBlock() : duplicate transaction")); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); } if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkleroot if (hashMerkleRoot != BuildMerkleTree()) return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); return true; } bool CBlock::AcceptBlock() { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; // Check proof of work if (nBits != GetNextWorkRequired(pindexPrev, this)) return DoS(100, error("AcceptBlock() : incorrect proof of work")); // Check timestamp against prev if (GetBlockTime() <= pindexPrev->GetMedianTimePast()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!tx.IsFinal(nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckBlock(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight)); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); } return true; } bool ProcessBlock(CNode* pfrom, CBlock* pblock) { // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str()); if (mapOrphanBlocks.count(hash)) return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str()); // Preliminary checks if (!pblock->CheckBlock()) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; if (deltaTime < 0) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with timestamp before last checkpoint"); } CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime)); if (bnNewBlock > bnRequired) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with too little proof-of-work"); } } // If don't already have its previous block, shunt it off to holding area until we get it if (!mapBlockIndex.count(pblock->hashPrevBlock)) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str()); CBlock* pblock2 = new CBlock(*pblock); mapOrphanBlocks.insert(make_pair(hash, pblock2)); mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing if (pfrom) pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); return true; } // Store to disk if (!pblock->AcceptBlock()) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi) { CBlock* pblockOrphan = (*mi).second; if (pblockOrphan->AcceptBlock()) vWorkQueue.push_back(pblockOrphan->GetHash()); mapOrphanBlocks.erase(pblockOrphan->GetHash()); delete pblockOrphan; } mapOrphanBlocksByPrev.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); return true; } bool CheckDiskSpace(uint64 nAdditionalBytes) { uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) { fShutdown = true; string strMessage = _("Warning: Disk space is low"); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage, "barcoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); StartShutdown(); return false; } return true; } FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode) { if ((nFile < 1) || (nFile == (unsigned int) -1)) return NULL; FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode); if (!file) return NULL; if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w')) { if (fseek(file, nBlockPos, SEEK_SET) != 0) { fclose(file); return NULL; } } return file; } static unsigned int nCurrentBlockFile = 1; FILE* AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; loop { FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab"); if (!file) return NULL; if (fseek(file, 0, SEEK_END) != 0) return NULL; // FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (ftell(file) < 0x7F000000 - MAX_SIZE) { nFileRet = nCurrentBlockFile; return file; } fclose(file); nCurrentBlockFile++; } } bool LoadBlockIndex(bool fAllowNew) { if (fTestNet) { pchMessageStart[0] = 0xfb; pchMessageStart[1] = 0xc0; pchMessageStart[2] = 0xb8; pchMessageStart[3] = 0xdb; hashGenesisBlock = uint256("0xe28d5412d9a235f1ec2bcaf305ba967c3d5fd80272547998e34802ec19204221"); } // // Load block index // CTxDB txdb("cr"); if (!txdb.LoadBlockIndex()) return false; txdb.Close(); // // Init with genesis block // if (mapBlockIndex.empty()) { if (!fAllowNew) return false; // Genesis block const char* pszTimestamp = "Building a coin to show the world how..."; CTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 0; txNew.vout[0].scriptPubKey = CScript() << 0x0 << OP_CHECKSIG; // a privkey for that 'vanity' pubkey would be interesting ;) CBlock block; block.vtx.push_back(txNew); block.hashPrevBlock = 0; block.hashMerkleRoot = block.BuildMerkleTree(); block.nVersion = 1; block.nTime = 1392499236; //epochtime block.nBits = 0x1e0ffff0; block.nNonce = 1468222; if (fTestNet) { block.nTime = 1391984252; block.nNonce = 440824; } //// debug print printf("%s\n", block.GetHash().ToString().c_str()); printf("%s\n", hashGenesisBlock.ToString().c_str()); printf("%s\n", block.hashMerkleRoot.ToString().c_str()); assert(block.hashMerkleRoot == uint256("0x2fc1b7ef46270c053711fbae934cf7f83378efd4b3e158079451d9c6c90e4700")); // If genesis block hash does not match, then generate new genesis hash. if (false && block.GetHash() != hashGenesisBlock) { printf("Searching for genesis block...\n"); // This will figure out a valid hash and Nonce if you're // creating a different genesis block: uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256(); uint256 thash; char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; loop { scrypt_1024_1_1_256_sp(BEGIN(block.nVersion), BEGIN(thash), scratchpad); if (thash <= hashTarget) break; if ((block.nNonce & 0xFFF) == 0) { printf("nonce %08X: hash = %s (target = %s)\n", block.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str()); } ++block.nNonce; if (block.nNonce == 0) { printf("NONCE WRAPPED, incrementing time\n"); ++block.nTime; } } printf("block.nTime = %u \n", block.nTime); printf("block.nNonce = %u \n", block.nNonce); printf("block.GetHash = %s\n", block.GetHash().ToString().c_str()); } block.print(); assert(block.GetHash() == hashGenesisBlock); // Start new block file unsigned int nFile; unsigned int nBlockPos; if (!block.WriteToDisk(nFile, nBlockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!block.AddToBlockIndex(nFile, nBlockPos)) return error("LoadBlockIndex() : genesis block not accepted"); } return true; } void PrintBlockTree() { // precompute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; block.ReadFromDisk(pindex); printf("%d (%u,%u) %s %s tx %d", pindex->nHeight, pindex->nFile, pindex->nBlockPos, block.GetHash().ToString().substr(0,20).c_str(), DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(), block.vtx.size()); PrintWallets(block); // put the main timechain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (unsigned int i = 0; i < vNext.size(); i++) { if (vNext[i]->pnext) { swap(vNext[0], vNext[i]); break; } } // iterate children for (unsigned int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } bool LoadExternalBlockFile(FILE* fileIn) { int nLoaded = 0; { LOCK(cs_main); try { CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION); unsigned int nPos = 0; while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown) { unsigned char pchData[65536]; do { fseek(blkdat, nPos, SEEK_SET); int nRead = fread(pchData, 1, sizeof(pchData), blkdat); if (nRead <= 8) { nPos = (unsigned int)-1; break; } void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart)); if (nFind) { if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0) { nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart); break; } nPos += ((unsigned char*)nFind - pchData) + 1; } else nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1; } while(!fRequestShutdown); if (nPos == (unsigned int)-1) break; fseek(blkdat, nPos, SEEK_SET); unsigned int nSize; blkdat >> nSize; if (nSize > 0 && nSize <= MAX_BLOCK_SIZE) { CBlock block; blkdat >> block; if (ProcessBlock(NULL,&block)) { nLoaded++; nPos += 4 + nSize; } } } } catch (std::exception &e) { printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__); } } printf("Loaded %i blocks from external file\n", nLoaded); return nLoaded > 0; } ////////////////////////////////////////////////////////////////////////////// // // CAlert // map<uint256, CAlert> mapAlerts; CCriticalSection cs_mapAlerts; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // Longer invalid proof-of-work chain if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6) { nPriority = 2000; strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade."; } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } CAlert CAlert::getAlertByHash(const uint256 &hash) { CAlert retval; { LOCK(cs_mapAlerts); map<uint256, CAlert>::iterator mi = mapAlerts.find(hash); if(mi != mapAlerts.end()) retval = mi->second; } return retval; } bool CAlert::ProcessAlert() { if (!CheckSignature()) return false; if (!IsInEffect()) return false; { LOCK(cs_mapAlerts); // Cancel previous alerts for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();) { const CAlert& alert = (*mi).second; if (Cancels(alert)) { printf("cancelling alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else if (!alert.IsInEffect()) { printf("expiring alert %d\n", alert.nID); uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED); mapAlerts.erase(mi++); } else mi++; } // Check if this alert has been cancelled BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.Cancels(*this)) { printf("alert already cancelled by %d\n", alert.nID); return false; } } // Add to mapAlerts mapAlerts.insert(make_pair(GetHash(), *this)); // Notify UI if it applies to me if(AppliesToMe()) uiInterface.NotifyAlertChanged(GetHash(), CT_NEW); } printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe()); return true; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(CTxDB& txdb, const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; { LOCK(mempool.cs); txInMap = (mempool.exists(inv.hash)); } return txInMap || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ascii, not valid as UTF-8, and produce // a large 4-byte int at any alignment. unsigned char pchMessageStart[4] = { 0xfc, 0xd9, 0xb7, 0xdd }; bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { static map<CService, CPubKey> mapReuseKey; RandAddSeedPerfmon(); if (fDebug) printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size()); if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64 nTime; CAddress addrMe; CAddress addrFrom; uint64 nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PROTO_VERSION) { // Since February 20, 2012, the protocol is initiated at version 209, // and earlier versions are no longer supported printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; if (pfrom->fInbound && addrMe.IsRoutable()) { pfrom->addrLocal = addrMe; SeenLocal(addrMe); } // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr); if (addr.IsRoutable()) pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Ask the first connected node for block updates static int nAskedForBlocks = 0; if (!pfrom->fClient && !pfrom->fOneShot && (pfrom->nVersion < NOBLKS_VERSION_START || pfrom->nVersion >= NOBLKS_VERSION_END) && (nAskedForBlocks < 1 || vNodes.size() <= 1)) { nAskedForBlocks++; pfrom->PushGetBlocks(pindexBest, uint256(0)); } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } pfrom->fSuccessfullyConnected = true; printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str()); cPeerBlockCounts.input(pfrom->nStartingHeight); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %d", vAddr.size()); } // Store the new addresses vector<CAddress> vAddrOk; int64 nNow = GetAdjustedTime(); int64 nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { if (fShutdown) return true; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); bool fReachable = IsReachable(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint64 hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } // Do not store addresses outside our network if (fReachable) vAddrOk.push_back(addr); } addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; if (pfrom->fOneShot) pfrom->fDisconnect = true; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message inv size() = %d", vInv.size()); } // find last block in inv vector unsigned int nLastBlock = (unsigned int)(-1); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { nLastBlock = vInv.size() - 1 - nInv; break; } } CTxDB txdb("r"); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; if (fShutdown) return true; pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(txdb, inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) pfrom->AskFor(inv); else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); } else if (nInv == nLastBlock) { // In case we are on a very long side-chain, it is possible that we already have // the last block in an inv bundle sent in response to getblocks. Try to detect // this situation and push another getblocks to continue. std::vector<CInv> vGetData(1,inv); pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0)); if (fDebug) printf("force request: %s\n", inv.ToString().c_str()); } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > 50000) { pfrom->Misbehaving(20); return error("message getdata size() = %d", vInv.size()); } if (fDebugNet || (vInv.size() != 1)) printf("received getdata (%d invsz)\n", vInv.size()); BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; if (fDebugNet || (vInv.size() == 1)) printf("received getdata for: %s\n", inv.ToString().c_str()); if (inv.type == MSG_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; block.ReadFromDisk((*mi).second); pfrom->PushMessage("block", block); // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, hashBestChain)); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) pfrom->PushMessage(inv.GetCommand(), (*mi).second); } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->pnext; int nLimit = 500; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->pnext; } vector<CBlock> vHeaders; int nLimit = 2000; printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str()); for (; pindex; pindex = pindex->pnext) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CDataStream vMsg(vRecv); CTxDB txdb("r"); CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); bool fMissingInputs = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs)) { SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin(); mi != mapOrphanTransactionsByPrev[hashPrev].end(); ++mi) { const CDataStream& vMsg = *((*mi).second); CTransaction tx; CDataStream(vMsg) >> tx; CInv inv(MSG_TX, tx.GetHash()); bool fMissingInputs2 = false; if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2)) { printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); SyncWithWallets(tx, NULL, true); RelayMessage(inv, vMsg); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); } else if (!fMissingInputs2) { // invalid orphan vEraseQueue.push_back(inv.hash); printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str()); } } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(vMsg); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS); if (nEvicted > 0) printf("mapOrphan overflow, removed %u tx\n", nEvicted); } if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); } else if (strCommand == "block") { CBlock block; vRecv >> block; printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str()); // block.print(); CInv inv(MSG_BLOCK, block.GetHash()); pfrom->AddInventoryKnown(inv); if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); } else if (strCommand == "getaddr") { pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) pfrom->PushAddress(addr); } else if (strCommand == "checkorder") { uint256 hashReply; vRecv >> hashReply; if (!GetBoolArg("-allowreceivebyip")) { pfrom->PushMessage("reply", hashReply, (int)2, string("")); return true; } CWalletTx order; vRecv >> order; /// we have a chance to check the order here // Keep giving the same key to the same ip until they use it if (!mapReuseKey.count(pfrom->addr)) pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true); // Send back approval of order and pubkey to use CScript scriptPubKey; scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG; pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); } else if (strCommand == "reply") { uint256 hashReply; vRecv >> hashReply; CRequestTracker tracker; { LOCK(pfrom->cs_mapRequests); map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply); if (mi != pfrom->mapRequests.end()) { tracker = (*mi).second; pfrom->mapRequests.erase(mi); } } if (!tracker.IsNull()) tracker.fn(tracker.param1, vRecv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64 nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alert.GetHash()); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") AddressCurrentlyConnected(pfrom->addr); return true; } bool ProcessMessages(CNode* pfrom) { CDataStream& vRecv = pfrom->vRecv; if (vRecv.empty()) return true; //if (fDebug) // printf("ProcessMessages(%u bytes)\n", vRecv.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // loop { // Don't bother if send buffer is too full to respond anyway if (pfrom->vSend.size() >= SendBufferSize()) break; // Scan for message start CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart)); int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader()); if (vRecv.end() - pstart < nHeaderSize) { if ((int)vRecv.size() > nHeaderSize) { printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n"); vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize); } break; } if (pstart - vRecv.begin() > 0) printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin()); vRecv.erase(vRecv.begin(), pstart); // Read header vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize); CMessageHeader hdr; vRecv >> hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; if (nMessageSize > MAX_SIZE) { printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize); continue; } if (nMessageSize > vRecv.size()) { // Rewind and wait for rest of message vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end()); break; } // Checksum uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Copy message to its own buffer CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion); vRecv.ignore(nMessageSize); // Process message bool fRet = false; try { { LOCK(cs_main); fRet = ProcessMessage(pfrom, strCommand, vMsg); } if (fShutdown) return true; } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from underlength message on vRecv printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from overlong size printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } vRecv.Compact(); return true; } bool SendMessages(CNode* pto, bool fSendTrickle) { TRY_LOCK(cs_main, lockMain); if (lockMain) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping. We send a nonce of zero because we don't use it anywhere // right now. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) { uint64 nonce = 0; if (pto->nVersion > BIP0031_VERSION) pto->PushMessage("ping", nonce); else pto->PushMessage("ping"); } // Resend wallet transactions that haven't gotten in a block yet ResendWalletTransactions(); // Address refresh broadcast static int64 nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen) { CAddress addr = GetLocalAddress(&pnode->addr); if (addr.IsRoutable()) pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // // Message: addr // if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // // Message: getdata // vector<CInv> vGetData; int64 nNow = GetTime() * 1000000; CTxDB txdb("r"); while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(txdb, inv)) { if (fDebugNet) printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } mapAlreadyAskedFor[inv] = nNow; } pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; } ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // int static FormatHashBlocks(void* pbuffer, unsigned int len) { unsigned char* pdata = (unsigned char*)pbuffer; unsigned int blocks = 1 + ((len + 8) / 64); unsigned char* pend = pdata + 64 * blocks; memset(pdata + len, 0, 64 * blocks - len); pdata[len] = 0x80; unsigned int bits = len * 8; pend[-1] = (bits >> 0) & 0xff; pend[-2] = (bits >> 8) & 0xff; pend[-3] = (bits >> 16) & 0xff; pend[-4] = (bits >> 24) & 0xff; return blocks; } static const unsigned int pSHA256InitState[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; void SHA256Transform(void* pstate, void* pinput, const void* pinit) { SHA256_CTX ctx; unsigned char data[64]; SHA256_Init(&ctx); for (int i = 0; i < 16; i++) ((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]); for (int i = 0; i < 8; i++) ctx.h[i] = ((uint32_t*)pinit)[i]; SHA256_Update(&ctx, data, sizeof(data)); for (int i = 0; i < 8; i++) ((uint32_t*)pstate)[i] = ctx.h[i]; } // // ScanHash scans nonces looking for a hash with at least some zero bits. // It operates on big endian data. Caller does the byte reversing. // All input buffers are 16-byte aligned. nNonce is usually preserved // between calls, but periodically or if nNonce is 0xffff0000 or above, // the block is rebuilt and nNonce starts over at zero. // unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone) { unsigned int& nNonce = *(unsigned int*)(pdata + 12); for (;;) { // Crypto++ SHA-256 // Hash pdata using pmidstate as the starting state into // preformatted buffer phash1, then hash phash1 into phash nNonce++; SHA256Transform(phash1, pdata, pmidstate); SHA256Transform(phash, phash1, pSHA256InitState); // Return the nonce if the hash has at least some zero bits, // caller will check if it has enough to reach the target if (((unsigned short*)phash)[14] == 0) return nNonce; // If nothing found after trying for a while, return -1 if ((nNonce & 0xffff) == 0) { nHashesDone = 0xffff+1; return (unsigned int) -1; } } } // Some explaining would be appreciated class COrphan { public: CTransaction* ptx; set<uint256> setDependsOn; double dPriority; COrphan(CTransaction* ptxIn) { ptx = ptxIn; dPriority = 0; } void print() const { printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority); BOOST_FOREACH(uint256 hash, setDependsOn) printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str()); } }; uint64 nLastBlockTx = 0; uint64 nLastBlockSize = 0; CBlock* CreateNewBlock(CReserveKey& reservekey) { CBlockIndex* pindexPrev = pindexBest; // Create new block auto_ptr<CBlock> pblock(new CBlock()); if (!pblock.get()) return NULL; // Create coinbase tx CTransaction txNew; txNew.vin.resize(1); txNew.vin[0].prevout.SetNull(); txNew.vout.resize(1); txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG; // Add our coinbase tx as first transaction pblock->vtx.push_back(txNew); // Collect memory pool transactions into the block int64 nFees = 0; { LOCK2(cs_main, mempool.cs); CTxDB txdb("r"); // Priority order to process transactions list<COrphan> vOrphan; // list memory doesn't move map<uint256, vector<COrphan*> > mapDependers; multimap<double, CTransaction*> mapPriority; for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi) { CTransaction& tx = (*mi).second; if (tx.IsCoinBase() || !tx.IsFinal()) continue; COrphan* porphan = NULL; double dPriority = 0; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Read prev transaction CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) { // Has to wait for dependencies if (!porphan) { // Use list for automatic deletion vOrphan.push_back(COrphan(&tx)); porphan = &vOrphan.back(); } mapDependers[txin.prevout.hash].push_back(porphan); porphan->setDependsOn.insert(txin.prevout.hash); continue; } int64 nValueIn = txPrev.vout[txin.prevout.n].nValue; // Read block header int nConf = txindex.GetDepthInMainChain(); dPriority += (double)nValueIn * nConf; if (fDebug && GetBoolArg("-printpriority")) printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority); } // Priority is sum(valuein * age) / txsize dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (porphan) porphan->dPriority = dPriority; else mapPriority.insert(make_pair(-dPriority, &(*mi).second)); if (fDebug && GetBoolArg("-printpriority")) { printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str()); if (porphan) porphan->print(); printf("\n"); } } // Collect transactions into block map<uint256, CTxIndex> mapTestPool; uint64 nBlockSize = 1000; uint64 nBlockTx = 0; int nBlockSigOps = 100; while (!mapPriority.empty()) { // Take highest priority transaction off priority queue double dPriority = -(*mapPriority.begin()).first; CTransaction& tx = *(*mapPriority.begin()).second; mapPriority.erase(mapPriority.begin()); // Size limits unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN) continue; // Legacy limits on sigOps: unsigned int nTxSigOps = tx.GetLegacySigOpCount(); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; // Transaction fee required depends on block size // Litecoind: Reduce the exempted free transactions to 500 bytes (from Bitcoin's 3000 bytes) bool fAllowFree = (nBlockSize + nTxSize < 1500 || CTransaction::AllowFree(dPriority)); int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK); // Connecting shouldn't fail due to dependency on other memory pool transactions // because we're already processing them in order of dependency map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool); MapPrevTx mapInputs; bool fInvalid; if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid)) continue; int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); if (nTxFees < nMinFee) continue; nTxSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS) continue; if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true)) continue; mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size()); swap(mapTestPool, mapTestPoolTmp); // Added pblock->vtx.push_back(tx); nBlockSize += nTxSize; ++nBlockTx; nBlockSigOps += nTxSigOps; nFees += nTxFees; // Add transactions that depend on this one to the priority queue uint256 hash = tx.GetHash(); if (mapDependers.count(hash)) { BOOST_FOREACH(COrphan* porphan, mapDependers[hash]) { if (!porphan->setDependsOn.empty()) { porphan->setDependsOn.erase(hash); if (porphan->setDependsOn.empty()) mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx)); } } } } nLastBlockTx = nBlockTx; nLastBlockSize = nBlockSize; printf("CreateNewBlock(): total size %lu\n", nBlockSize); } pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); pblock->UpdateTime(pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get()); pblock->nNonce = 0; return pblock.release(); } void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS; assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100); pblock->hashMerkleRoot = pblock->BuildMerkleTree(); } void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1) { // // Prebuild hash buffers // struct { struct unnamed2 { int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; } block; unsigned char pchPadding0[64]; uint256 hash1; unsigned char pchPadding1[64]; } tmp; memset(&tmp, 0, sizeof(tmp)); tmp.block.nVersion = pblock->nVersion; tmp.block.hashPrevBlock = pblock->hashPrevBlock; tmp.block.hashMerkleRoot = pblock->hashMerkleRoot; tmp.block.nTime = pblock->nTime; tmp.block.nBits = pblock->nBits; tmp.block.nNonce = pblock->nNonce; FormatHashBlocks(&tmp.block, sizeof(tmp.block)); FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1)); // Byte swap all the input buffer for (unsigned int i = 0; i < sizeof(tmp)/4; i++) ((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]); // Precalc the first half of the first hash, which stays constant SHA256Transform(pmidstate, &tmp.block, pSHA256InitState); memcpy(pdata, &tmp.block, 128); memcpy(phash1, &tmp.hash1, 64); } bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey) { uint256 hash = pblock->GetPoWHash(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); if (hash > hashTarget) return false; //// debug print printf("BitcoinMiner:\n"); printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str()); pblock->print(); printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str()); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != hashBestChain) return error("BitcoinMiner : generated block is stale"); // Remove key from key pool reservekey.KeepKey(); // Track how many getdata requests this block gets { LOCK(wallet.cs_wallet); wallet.mapRequestCount[pblock->GetHash()] = 0; } // Process this block the same as if we had received it from another node if (!ProcessBlock(NULL, pblock)) return error("BitcoinMiner : ProcessBlock, block not accepted"); } return true; } void static ThreadBitcoinMiner(void* parg); static bool fGenerateBitcoins = false; static bool fLimitProcessors = false; static int nLimitProcessors = -1; void static BitcoinMiner(CWallet *pwallet) { printf("BitcoinMiner started\n"); SetThreadPriority(THREAD_PRIORITY_LOWEST); // Make this thread recognisable as the mining thread RenameThread("bitcoin-miner"); // Each thread has its own key and counter CReserveKey reservekey(pwallet); unsigned int nExtraNonce = 0; while (fGenerateBitcoins) { if (fShutdown) return; while (vNodes.empty() || IsInitialBlockDownload()) { Sleep(1000); if (fShutdown) return; if (!fGenerateBitcoins) return; } // // Create new block // unsigned int nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrev = pindexBest; auto_ptr<CBlock> pblock(CreateNewBlock(reservekey)); if (!pblock.get()) return; IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce); printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size()); // // Prebuild hash buffers // char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf); char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf); char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf); FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1); unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4); unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8); //unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12); // // Search // int64 nStart = GetTime(); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); loop { unsigned int nHashesDone = 0; //unsigned int nNonceFound; uint256 thash; char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; loop { scrypt_1024_1_1_256_sp(BEGIN(pblock->nVersion), BEGIN(thash), scratchpad); if (thash <= hashTarget) { // Found a solution SetThreadPriority(THREAD_PRIORITY_NORMAL); CheckWork(pblock.get(), *pwalletMain, reservekey); SetThreadPriority(THREAD_PRIORITY_LOWEST); break; } pblock->nNonce += 1; nHashesDone += 1; if ((pblock->nNonce & 0xFF) == 0) break; } // Meter hashes/sec static int64 nHashCounter; if (nHPSTimerStart == 0) { nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; } else nHashCounter += nHashesDone; if (GetTimeMillis() - nHPSTimerStart > 4000) { static CCriticalSection cs; { LOCK(cs); if (GetTimeMillis() - nHPSTimerStart > 4000) { dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart); nHPSTimerStart = GetTimeMillis(); nHashCounter = 0; string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0); static int64 nLogTime; if (GetTime() - nLogTime > 30 * 60) { nLogTime = GetTime(); printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str()); printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0); } } } } // Check for stop or if block needs to be rebuilt if (fShutdown) return; if (!fGenerateBitcoins) return; if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors) return; if (vNodes.empty()) break; if (pblock->nNonce >= 0xffff0000) break; if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; if (pindexPrev != pindexBest) break; // Update nTime every few seconds pblock->UpdateTime(pindexPrev); nBlockTime = ByteReverse(pblock->nTime); if (fTestNet) { // Changing pblock->nTime can change work required on testnet: nBlockBits = ByteReverse(pblock->nBits); hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); } } } } void static ThreadBitcoinMiner(void* parg) { CWallet* pwallet = (CWallet*)parg; try { vnThreadsRunning[THREAD_MINER]++; BitcoinMiner(pwallet); vnThreadsRunning[THREAD_MINER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_MINER]--; PrintException(&e, "ThreadBitcoinMiner()"); } catch (...) { vnThreadsRunning[THREAD_MINER]--; PrintException(NULL, "ThreadBitcoinMiner()"); } nHPSTimerStart = 0; if (vnThreadsRunning[THREAD_MINER] == 0) dHashesPerSec = 0; printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]); } void GenerateBitcoins(bool fGenerate, CWallet* pwallet) { fGenerateBitcoins = fGenerate; nLimitProcessors = GetArg("-genproclimit", -1); if (nLimitProcessors == 0) fGenerateBitcoins = false; fLimitProcessors = (nLimitProcessors != -1); if (fGenerate) { int nProcessors = boost::thread::hardware_concurrency(); printf("%d processors\n", nProcessors); if (nProcessors < 1) nProcessors = 1; if (fLimitProcessors && nProcessors > nLimitProcessors) nProcessors = nLimitProcessors; int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER]; printf("Starting %d BitcoinMiner threads\n", nAddThreads); for (int i = 0; i < nAddThreads; i++) { if (!CreateThread(ThreadBitcoinMiner, pwallet)) printf("Error: CreateThread(ThreadBitcoinMiner) failed\n"); Sleep(10); } } }
{ "content_hash": "9264fa4ee5f2f3aa5ec1194756bf5ee7", "timestamp": "", "source": "github", "line_count": 3814, "max_line_length": 280, "avg_line_length": 33.38384897745149, "alnum_prop": 0.5726324552722931, "repo_name": "esmadja/digitalcoin", "id": "6764c25822aaf70fb159633813911e1d2c9da06f", "size": "127832", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "78622" }, { "name": "C++", "bytes": "1371087" }, { "name": "IDL", "bytes": "10956" }, { "name": "Objective-C", "bytes": "2463" }, { "name": "Python", "bytes": "47538" }, { "name": "Shell", "bytes": "1402" }, { "name": "TypeScript", "bytes": "3810608" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GmailAuto")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("GmailAuto")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("57813386-bc38-4b7d-a9ec-cd0e2220a34e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "f763bbea1528ab5edb04c3e4ee30d539", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.138888888888886, "alnum_prop": 0.7473385379701917, "repo_name": "afrizyuk/gmail-auto", "id": "2996834a26c4d63c8187de29e3c773ae97bfc311", "size": "1412", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GmailAuto/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "25156" } ], "symlink_target": "" }
import poplib import email import time class MailHelper: def __init__(self, app): self.app = app def get_mail(self, username, password, subject): for i in range(10): pop = poplib.POP3(self.app.config['james']['host']) pop.user(username) pop.pass_(password) num = pop.stat()[0] if num > 0: for n in range(num): msglines = pop.retr(n+1)[1] msgtext = "\n".join(map(lambda x: x.decode('utf-8'), msglines)) msg = email.message_from_string(msgtext) if msg.get("Subject") == subject: pop.dele(n+1) pop.quit() return msg.get_payload() pop.quit() time.sleep(4) return None
{ "content_hash": "33dee81a746d39d4958fc3777ff766f6", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 83, "avg_line_length": 27.580645161290324, "alnum_prop": 0.45964912280701753, "repo_name": "AndreyBalabanov/python_training_mantisBT", "id": "3930eb50bf0062d4dca6f1de471a4626bc6206c6", "size": "855", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fixture/mail.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "163" }, { "name": "Python", "bytes": "15276" } ], "symlink_target": "" }
<?php namespace app\controllers; use Yii; use yii\rest\ActiveController; /** * Cron controller */ class CronController extends ActiveController { public $modelClass = 'app\models\Postinfo'; public function actions() { $actions = parent::actions(); // 注销系统自带的实现方法 unset($actions['index'],$actions['cron']); return $actions; } public function actionIndex() { echo "cron service runnning"; } public function actionCleanredis() { Yii::$app->cache->flush(); $themes = Yii::$app->db->createCommand('SELECT `order_id` as `id`, `pacname` as `packageName` ,`version`,`title`,`zip_source` as `downloadUrl`,`theme_url` as `previewImageUrl` FROM `postinfo` where `status`=1 ORDER BY `id` ASC' )->queryAll(); $themes_new = array(); if($themes != null){ foreach($themes as $theme){ $id = $theme['id']; // unset($theme['id']); Yii::$app->cache->set("theme".$id,json_encode($theme)); $themes_new[] = $theme; } // unset($themes['id']); Yii::$app->cache->set("themes",json_encode($themes_new)); } echo "reset redis data ok"; } }
{ "content_hash": "4fc524ac5fb057f472671f6b2a2e2f06", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 253, "avg_line_length": 28.27659574468085, "alnum_prop": 0.5191873589164786, "repo_name": "njkfei/yii2-basic", "id": "97ec80d0754dad0964396d3bd792546fac6819e9", "size": "1351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "controllers/CronController.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1030" }, { "name": "CSS", "bytes": "1364" }, { "name": "PHP", "bytes": "85939" } ], "symlink_target": "" }
var buttons = require('sdk/ui/button/action'); var tabs = require('sdk/tabs'); var button = buttons.ActionButton({ id:'facebook', label:'Visit FB', icon:{ "16":"./fb.png" }, onClick: handleClick }); var button1 = buttons.ActionButton({ id:'gmail', label:'Visit Gmail', icon:{ "16":"./gmail.png" }, onClick: handleClick1 }); function handleClick(state){ tabs.open("https://fb.com"); } function handleClick1(state){ tabs.open("https://gmail.com"); }
{ "content_hash": "3338e0c2d0d51478f32b1fc1f1bd376e", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 46, "avg_line_length": 17.612903225806452, "alnum_prop": 0.5604395604395604, "repo_name": "mohsalsaleem/FBGMail", "id": "a1965f2cb6fd17077432a090f6275b2d957686c2", "size": "546", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/main.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "1129" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="%PUBLIC_URL%/../favicon.ico"> <!-- Notice the use of %PUBLIC_URL% in the tag above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>React App</title> </head> <body> <div id="root"></div> <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start`. To create a production bundle, use `npm run build`. --> </body> </html>
{ "content_hash": "564422b49f6c030e9998249ffe8c0633", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 79, "avg_line_length": 36.774193548387096, "alnum_prop": 0.6473684210526316, "repo_name": "alexfigtree/CoreID", "id": "6233f6e288a657ef656537560ca60b3fd6a87530", "size": "1140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "105153" }, { "name": "HTML", "bytes": "46649" }, { "name": "JavaScript", "bytes": "61218" }, { "name": "Nginx", "bytes": "204" } ], "symlink_target": "" }
% PURPOSE: An example of using mess() on a small dataset % matrix exponential spatial specification % %--------------------------------------------------- % USAGE: mess_d %--------------------------------------------------- % load Anselin (1988) Columbus neighborhood crime data load anselin.dat; n = length(anselin); x = [ones(n,1) anselin(:,2:3)]; latt = anselin(:,4); long = anselin(:,5); vnames = strvcat('crime','constant','income','hvalue'); load wmat.dat; W = sparse(wmat(:,1),wmat(:,2),wmat(:,3));; % do Monte Carlo generation of an SAR model sige = 100; evec = randn(n,1)*sqrt(sige); beta = ones(3,1); rho = 0.6; lam = 0.25; A = eye(n) - rho*W; AI = inv(A); y = AI*x*beta + AI*evec; % generate some data % do MESS model using W as weight matrix option.D = W; res1 = mess(y,x,option); prt(res1,vnames); % do MESS model using latt, long and neighbors % to form a weight matrix option2.latt = latt; option2.long = long; option2.rho = 0.75; option2.neigh = 7; res2 = mess(y,x,option2); prt(res2,vnames); % do MESS model with spatially lagged x-variables option3.latt = latt; option3.long = long; option3.rho = 0.9; option3.neigh = 10; option3.xflag = 1; res3 = mess(y,x,option3); prt(res3,vnames);
{ "content_hash": "13ca8a92396d2160893ca0a498b2e6e7", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 56, "avg_line_length": 24.192307692307693, "alnum_prop": 0.5930047694753577, "repo_name": "pradlanka/malini", "id": "46ccc6088b7356ee95c72ea8abe3728bc5eea84b", "size": "1258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Codes/FC_EC_calculation code/DynamicFC/jplv7/spatial/mess_models/mess_d.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1556591" }, { "name": "C++", "bytes": "1112" }, { "name": "HTML", "bytes": "73524" }, { "name": "M", "bytes": "44313" }, { "name": "MATLAB", "bytes": "15262482" }, { "name": "Makefile", "bytes": "16489" }, { "name": "Mathematica", "bytes": "10015" }, { "name": "Mercury", "bytes": "855" }, { "name": "Objective-C", "bytes": "1987" }, { "name": "Rich Text Format", "bytes": "2705" }, { "name": "Roff", "bytes": "303696" }, { "name": "TeX", "bytes": "1048938" } ], "symlink_target": "" }
/******************************************************************************* * rc_balance.c * * Reference solution for balancing EduMiP *******************************************************************************/ #include "../../libraries/rc_usefulincludes.h" #include "../../libraries/roboticscape.h" #include "balance_config.h" /******************************************************************************* * drive_mode_t * * NOVICE: Drive rate and turn rate are limited to make driving easier. * ADVANCED: Faster drive and turn rate for more fun. *******************************************************************************/ typedef enum drive_mode_t{ NOVICE, ADVANCED }drive_mode_t; /******************************************************************************* * arm_state_t * * ARMED or DISARMED to indicate if the controller is running *******************************************************************************/ typedef enum arm_state_t{ ARMED, DISARMED }arm_state_t; /******************************************************************************* * setpoint_t * * Controller setpoint written to by setpoint_manager and read by the controller. *******************************************************************************/ typedef struct setpoint_t{ arm_state_t arm_state; // see arm_state_t declaration drive_mode_t drive_mode;// NOVICE or ADVANCED float theta; // body lean angle (rad) float phi; // wheel position (rad) float phi_dot; // rate at which phi reference updates (rad/s) float gamma; // body turn angle (rad) float gamma_dot; // rate at which gamma setpoint updates (rad/s) }setpoint_t; /******************************************************************************* * core_state_t * * This is the system state written to by the balance controller. *******************************************************************************/ typedef struct core_state_t{ float wheelAngleR; // wheel rotation relative to body float wheelAngleL; float theta; // body angle radians float phi; // average wheel angle in global frame float gamma; // body turn (yaw) angle radians float vBatt; // battery voltage float d1_u; // output of balance controller D1 to motors float d2_u; // output of position controller D2 (theta_ref) float d3_u; // output of steering controller D3 to motors float mot_drive; // u compensated for battery voltage } core_state_t; /******************************************************************************* * Local Function declarations *******************************************************************************/ // IMU interrupt routine void balance_controller(); // threads void* setpoint_manager(void* ptr); void* battery_checker(void* ptr); void* printf_loop(void* ptr); // regular functions int zero_out_controller(); int disarm_controller(); int arm_controller(); int wait_for_starting_condition(); void on_pause_press(); void on_mode_release(); int blink_green(); int blink_red(); /******************************************************************************* * Global Variables *******************************************************************************/ core_state_t cstate; setpoint_t setpoint; rc_filter_t D1, D2, D3; rc_imu_data_t imu_data; /******************************************************************************* * main() * * Initialize the filters, IMU, threads, & wait until shut down *******************************************************************************/ int main(){ // make sure everything initializes first if(rc_initialize()){ fprintf(stderr,"ERROR: failed to run rc_initialize(), are you root?\n"); return -1; } rc_set_led(RED,1); rc_set_led(GREEN,0); rc_set_state(UNINITIALIZED); // if gyro isn't calibrated, run the calibration routine if(!rc_is_gyro_calibrated()){ printf("Gyro not calibrated, automatically starting calibration routine\n"); printf("Let your MiP sit still on a firm surface\n"); rc_calibrate_gyro_routine(); } // make sure setpoint starts at normal values setpoint.arm_state = DISARMED; setpoint.drive_mode = NOVICE; D1=rc_empty_filter(); D2=rc_empty_filter(); D3=rc_empty_filter(); // set up D1 Theta controller float D1_num[] = D1_NUM; float D1_den[] = D1_DEN; if(rc_alloc_filter_from_arrays(&D1,D1_ORDER, DT, D1_num, D1_den)){ fprintf(stderr,"ERROR in rc_balance, failed to make filter D1\n"); return -1; } D1.gain = D1_GAIN; rc_enable_saturation(&D1, -1.0, 1.0); rc_enable_soft_start(&D1, SOFT_START_SEC); // set up D2 Phi controller float D2_num[] = D2_NUM; float D2_den[] = D2_DEN; if(rc_alloc_filter_from_arrays(&D2, D2_ORDER, DT, D2_num, D2_den)){ fprintf(stderr,"ERROR in rc_balance, failed to make filter D2\n"); return -1; } D2.gain = D2_GAIN; rc_enable_saturation(&D2, -THETA_REF_MAX, THETA_REF_MAX); rc_enable_soft_start(&D2, SOFT_START_SEC); printf("Inner Loop controller D1:\n"); rc_print_filter(D1); printf("\nOuter Loop controller D2:\n"); rc_print_filter(D2); // set up D3 gamma (steering) controller if(rc_pid_filter(&D3, D3_KP, D3_KI, D3_KD, 4*DT, DT)){ fprintf(stderr,"ERROR in rc_balance, failed to make steering controller\n"); return -1; } rc_enable_saturation(&D3, -STEERING_INPUT_MAX, STEERING_INPUT_MAX); // set up button handlers rc_set_pause_pressed_func(&on_pause_press); rc_set_mode_released_func(&on_mode_release); // start a thread to slowly sample battery pthread_t battery_thread; pthread_create(&battery_thread, NULL, battery_checker, (void*) NULL); // wait for the battery thread to make the first read while(cstate.vBatt==0 && rc_get_state()!=EXITING) rc_usleep(1000); // start printf_thread if running from a terminal // if it was started as a background process then don't bother if(isatty(fileno(stdout))){ pthread_t printf_thread; pthread_create(&printf_thread, NULL, printf_loop, (void*) NULL); } // set up IMU configuration rc_imu_config_t imu_config = rc_default_imu_config(); imu_config.dmp_sample_rate = SAMPLE_RATE_HZ; imu_config.orientation = ORIENTATION_Y_UP; // start imu if(rc_initialize_imu_dmp(&imu_data, imu_config)){ fprintf(stderr,"ERROR: can't talk to IMU, all hope is lost\n"); rc_blink_led(RED, 5, 5); return -1; } // start balance stack to control setpoints pthread_t setpoint_thread; pthread_create(&setpoint_thread, NULL, setpoint_manager, (void*) NULL); // this should be the last step in initialization // to make sure other setup functions don't interfere rc_set_imu_interrupt_func(&balance_controller); // start in the RUNNING state, pressing the pause button will swap to // the PAUSED state then back again. printf("\nHold your MIP upright to begin balancing\n"); rc_set_state(RUNNING); // start dsm listener rc_initialize_dsm(); // chill until something exits the program while(rc_get_state()!=EXITING){ rc_usleep(10000); } // cleanup rc_free_filter(&D1); rc_free_filter(&D2); rc_free_filter(&D3); rc_power_off_imu(); rc_cleanup(); return 0; } /******************************************************************************* * void* setpoint_manager(void* ptr) * * This thread is in charge of adjusting the controller setpoint based on user * inputs from dsm radio control. Also detects pickup to control arming the * controller. *******************************************************************************/ void* setpoint_manager(void* ptr){ float drive_stick, turn_stick; // dsm input sticks // wait for IMU to settle disarm_controller(); rc_usleep(2500000); rc_set_state(RUNNING); rc_set_led(RED,0); rc_set_led(GREEN,1); while(rc_get_state()!=EXITING){ // sleep at beginning of loop so we can use the 'continue' statement rc_usleep(1000000/SETPOINT_MANAGER_HZ); // nothing to do if paused, go back to beginning of loop if(rc_get_state() != RUNNING) continue; // if we got here the state is RUNNING, but controller is not // necessarily armed. If DISARMED, wait for the user to pick MIP up // which will we detected by wait_for_starting_condition() if(setpoint.arm_state == DISARMED){ if(wait_for_starting_condition()==0){ zero_out_controller(); arm_controller(); } else continue; } // if dsm is active, update the setpoint rates if(rc_is_new_dsm_data()){ // Read normalized (+-1) inputs from RC radio stick and multiply by // polarity setting so positive stick means positive setpoint turn_stick = rc_get_dsm_ch_normalized(DSM_TURN_CH) * DSM_TURN_POL; drive_stick = rc_get_dsm_ch_normalized(DSM_DRIVE_CH)* DSM_DRIVE_POL; // saturate the inputs to avoid possible erratic behavior rc_saturate_float(&drive_stick,-1,1); rc_saturate_float(&turn_stick,-1,1); // use a small deadzone to prevent slow drifts in position if(fabs(drive_stick)<DSM_DEAD_ZONE) drive_stick = 0.0; if(fabs(turn_stick)<DSM_DEAD_ZONE) turn_stick = 0.0; // translate normalized user input to real setpoint values switch(setpoint.drive_mode){ case NOVICE: setpoint.phi_dot = DRIVE_RATE_NOVICE * drive_stick; setpoint.gamma_dot = TURN_RATE_NOVICE * turn_stick; break; case ADVANCED: setpoint.phi_dot = DRIVE_RATE_ADVANCED * drive_stick; setpoint.gamma_dot = TURN_RATE_ADVANCED * turn_stick; break; default: break; } } // if dsm had timed out, put setpoint rates back to 0 else if(rc_is_dsm_active()==0){ setpoint.theta = 0; setpoint.phi_dot = 0; setpoint.gamma_dot = 0; continue; } } // if state becomes EXITING the above loop exists and we disarm here disarm_controller(); return NULL; } /******************************************************************************* * void balance_controller() * * discrete-time balance controller operated off IMU interrupt * Called at SAMPLE_RATE_HZ *******************************************************************************/ void balance_controller(){ static int inner_saturation_counter = 0; float dutyL, dutyR; /****************************************************************** * STATE_ESTIMATION * read sensors and compute the state when either ARMED or DISARMED ******************************************************************/ // angle theta is positive in the direction of forward tip around X axis cstate.theta = imu_data.dmp_TaitBryan[TB_PITCH_X] + CAPE_MOUNT_ANGLE; // collect encoder positions, right wheel is reversed cstate.wheelAngleR = (rc_get_encoder_pos(ENCODER_CHANNEL_R) * TWO_PI) \ /(ENCODER_POLARITY_R * GEARBOX * ENCODER_RES); cstate.wheelAngleL = (rc_get_encoder_pos(ENCODER_CHANNEL_L) * TWO_PI) \ /(ENCODER_POLARITY_L * GEARBOX * ENCODER_RES); // Phi is average wheel rotation also add theta body angle to get absolute // wheel position in global frame since encoders are attached to the body cstate.phi = ((cstate.wheelAngleL+cstate.wheelAngleR)/2) + cstate.theta; // steering angle gamma estimate cstate.gamma = (cstate.wheelAngleR-cstate.wheelAngleL) \ * (WHEEL_RADIUS_M/TRACK_WIDTH_M); /************************************************************* * check for various exit conditions AFTER state estimate ***************************************************************/ if(rc_get_state()==EXITING){ rc_disable_motors(); return; } // if controller is still ARMED while state is PAUSED, disarm it if(rc_get_state()!=RUNNING && setpoint.arm_state==ARMED){ disarm_controller(); return; } // exit if the controller is disarmed if(setpoint.arm_state==DISARMED){ return; } // check for a tipover if(fabs(cstate.theta) > TIP_ANGLE){ disarm_controller(); printf("tip detected \n"); return; } /************************************************************ * OUTER LOOP PHI controller D2 * Move the position setpoint based on phi_dot. * Input to the controller is phi error (setpoint-state). *************************************************************/ if(ENABLE_POSITION_HOLD){ if(setpoint.phi_dot != 0.0) setpoint.phi += setpoint.phi_dot*DT; cstate.d2_u = rc_march_filter(&D2,setpoint.phi-cstate.phi); setpoint.theta = cstate.d2_u; } else setpoint.theta = 0.0; /************************************************************ * INNER LOOP ANGLE Theta controller D1 * Input to D1 is theta error (setpoint-state). Then scale the * output u to compensate for changing battery voltage. *************************************************************/ D1.gain = D1_GAIN * V_NOMINAL/cstate.vBatt; cstate.d1_u = rc_march_filter(&D1,(setpoint.theta-cstate.theta)); /************************************************************* * Check if the inner loop saturated. If it saturates for over * a second disarm the controller to prevent stalling motors. *************************************************************/ if(fabs(cstate.d1_u)>0.95) inner_saturation_counter++; else inner_saturation_counter = 0; // if saturate for a second, disarm for safety if(inner_saturation_counter > (SAMPLE_RATE_HZ*D1_SATURATION_TIMEOUT)){ printf("inner loop controller saturated\n"); disarm_controller(); inner_saturation_counter = 0; return; } /********************************************************** * gama (steering) controller D3 * move the setpoint gamma based on user input like phi ***********************************************************/ if(fabs(setpoint.gamma_dot)>0.0001) setpoint.gamma += setpoint.gamma_dot * DT; cstate.d3_u = rc_march_filter(&D3,setpoint.gamma - cstate.gamma); /********************************************************** * Send signal to motors * add D1 balance control u and D3 steering control also * multiply by polarity to make sure direction is correct. ***********************************************************/ dutyL = cstate.d1_u - cstate.d3_u; dutyR = cstate.d1_u + cstate.d3_u; rc_set_motor(MOTOR_CHANNEL_L, MOTOR_POLARITY_L * dutyL); rc_set_motor(MOTOR_CHANNEL_R, MOTOR_POLARITY_R * dutyR); return; } /******************************************************************************* * zero_out_controller() * * Clear the controller's memory and zero out setpoints. *******************************************************************************/ int zero_out_controller(){ rc_reset_filter(&D1); rc_reset_filter(&D2); rc_reset_filter(&D3); setpoint.theta = 0.0f; setpoint.phi = 0.0f; setpoint.gamma = 0.0f; rc_set_motor_all(0.0f); return 0; } /******************************************************************************* * disarm_controller() * * disable motors & set the setpoint.core_mode to DISARMED *******************************************************************************/ int disarm_controller(){ rc_disable_motors(); setpoint.arm_state = DISARMED; return 0; } /******************************************************************************* * arm_controller() * * zero out the controller & encoders. Enable motors & arm the controller. *******************************************************************************/ int arm_controller(){ zero_out_controller(); rc_set_encoder_pos(ENCODER_CHANNEL_L,0); rc_set_encoder_pos(ENCODER_CHANNEL_R,0); // prefill_filter_inputs(&D1,cstate.theta); setpoint.arm_state = ARMED; rc_enable_motors(); return 0; } /******************************************************************************* * int wait_for_starting_condition() * * Wait for MiP to be held upright long enough to begin. * Returns 0 if successful. Returns -1 if the wait process was interrupted by * pause button or shutdown signal. *******************************************************************************/ int wait_for_starting_condition(){ int checks = 0; const int check_hz = 20; // check 20 times per second int checks_needed = round(START_DELAY*check_hz); int wait_us = 1000000/check_hz; // wait for MiP to be tipped back or forward first // exit if state becomes paused or exiting while(rc_get_state()==RUNNING){ // if within range, start counting if(fabs(cstate.theta) > START_ANGLE) checks++; // fell out of range, restart counter else checks = 0; // waited long enough, return if(checks >= checks_needed) break; rc_usleep(wait_us); } // now wait for MiP to be upright checks = 0; // exit if state becomes paused or exiting while(rc_get_state()==RUNNING){ // if within range, start counting if(fabs(cstate.theta) < START_ANGLE) checks++; // fell out of range, restart counter else checks = 0; // waited long enough, return if(checks >= checks_needed) return 0; rc_usleep(wait_us); } return -1; } /******************************************************************************* * battery_checker() * * Slow loop checking battery voltage. Also changes the D1 saturation limit * since that is dependent on the battery voltage. *******************************************************************************/ void* battery_checker(void* ptr){ float new_v; while(rc_get_state()!=EXITING){ new_v = rc_battery_voltage(); // if the value doesn't make sense, use nominal voltage if (new_v>9.0 || new_v<5.0) new_v = V_NOMINAL; cstate.vBatt = new_v; rc_usleep(1000000 / BATTERY_CHECK_HZ); } return NULL; } /******************************************************************************* * printf_loop() * * prints diagnostics to console * this only gets started if executing from terminal *******************************************************************************/ void* printf_loop(void* ptr){ rc_state_t last_rc_state, new_rc_state; // keep track of last state last_rc_state = rc_get_state(); while(rc_get_state()!=EXITING){ new_rc_state = rc_get_state(); // check if this is the first time since being paused if(new_rc_state==RUNNING && last_rc_state!=RUNNING){ printf("\nRUNNING: Hold upright to balance.\n"); printf(" θ |"); printf(" θ_ref |"); printf(" φ |"); printf(" φ_ref |"); printf(" γ |"); printf(" D1_u |"); printf(" D3_u |"); printf(" vBatt |"); printf("arm_state|"); printf("\n"); } else if(new_rc_state==PAUSED && last_rc_state!=PAUSED){ printf("\nPAUSED: press pause again to start.\n"); } last_rc_state = new_rc_state; // decide what to print or exit if(new_rc_state == RUNNING){ printf("\r"); printf("%7.3f |", cstate.theta); printf("%7.3f |", setpoint.theta); printf("%7.3f |", cstate.phi); printf("%7.3f |", setpoint.phi); printf("%7.3f |", cstate.gamma); printf("%7.3f |", cstate.d1_u); printf("%7.3f |", cstate.d3_u); printf("%7.3f |", cstate.vBatt); if(setpoint.arm_state == ARMED) printf(" ARMED |"); else printf("DISARMED |"); fflush(stdout); } rc_usleep(1000000 / PRINTF_HZ); } return NULL; } /******************************************************************************* * void on_pause_press() * * Disarm the controller and set system state to paused. * If the user holds the pause button for 2 seconds, exit cleanly *******************************************************************************/ void on_pause_press(){ int i=0; const int samples = 100; // check for release 100 times in this period const int us_wait = 2000000; // 2 seconds switch(rc_get_state()){ // pause if running case EXITING: return; case RUNNING: rc_set_state(PAUSED); disarm_controller(); rc_set_led(RED,1); rc_set_led(GREEN,0); break; case PAUSED: rc_set_state(RUNNING); disarm_controller(); rc_set_led(GREEN,1); rc_set_led(RED,0); break; default: break; } // now wait to see if the user want to shut down the program while(i<samples){ rc_usleep(us_wait/samples); if(rc_get_pause_button() == RELEASED){ return; //user let go before time-out } i++; } printf("long press detected, shutting down\n"); //user held the button down long enough, blink and exit cleanly rc_blink_led(RED,5,2); rc_set_state(EXITING); return; } /******************************************************************************* * void on_mode_release() * * toggle between position and angle modes if MiP is paused *******************************************************************************/ void on_mode_release(){ // toggle between position and angle modes if(setpoint.drive_mode == NOVICE){ setpoint.drive_mode = ADVANCED; printf("using drive_mode = ADVANCED\n"); } else { setpoint.drive_mode = NOVICE; printf("using drive_mode = NOVICE\n"); } rc_blink_led(GREEN,5,1); return; }
{ "content_hash": "a3d719a726da5100a74e8f2f5fd02995", "timestamp": "", "source": "github", "line_count": 617, "max_line_length": 80, "avg_line_length": 33.246353322528364, "alnum_prop": 0.5613025886023497, "repo_name": "Andrewiski/Robotics_Cape_Installer", "id": "419b9df0d06499abb99d44fb7583f44d8694d4e4", "size": "20518", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/rc_balance/rc_balance.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "13346" }, { "name": "Batchfile", "bytes": "3505" }, { "name": "C", "bytes": "648776" }, { "name": "C++", "bytes": "2237" }, { "name": "Makefile", "bytes": "12427" }, { "name": "Shell", "bytes": "12447" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.14"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Variant: source/toolkit/number Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Variant </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.14 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_b2f33c71d4aa5e7af42a1ca61ff5af1b.html">source</a></li><li class="navelem"><a class="el" href="dir_89ef54b1a8322798cfdb03be7b54efa8.html">toolkit</a></li><li class="navelem"><a class="el" href="dir_3fa6eb2cd29569ca063708d3ce12eec8.html">number</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">number Directory Reference</div> </div> </div><!--header--> <div class="contents"> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.14 </small></address> </body> </html>
{ "content_hash": "747f7115c98fab44288c017d0c20a9b1", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 302, "avg_line_length": 40.175, "alnum_prop": 0.6907280647168638, "repo_name": "will-iam/Variant", "id": "2cff9bcc886add53e71cdbb9a80f3317841b136b", "size": "3214", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/html/dir_3fa6eb2cd29569ca063708d3ce12eec8.html", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "269808" }, { "name": "Python", "bytes": "386768" }, { "name": "Shell", "bytes": "848" } ], "symlink_target": "" }
'use strict'; let angular = require('angular'); module.exports = angular.module('spinnaker.core.serverGroup.configure.common.service', [ require('exports?"restangular"!imports?_=lodash!restangular'), require('../../../cache/deckCacheFactory.js'), require('../../../cloudProvider/serviceDelegate.service.js'), require('../../../config/settings.js') ]) .factory('serverGroupCommandBuilder', function (settings, Restangular, serviceDelegate) { function getServerGroup(application, account, region, serverGroupName) { return Restangular.one('applications', application).all('serverGroups').all(account).all(region).one(serverGroupName).get(); } function getDelegate(provider) { return serviceDelegate.getDelegate(provider, 'serverGroup.commandBuilder'); } function buildNewServerGroupCommand(application, provider, options) { return getDelegate(provider).buildNewServerGroupCommand(application, options); } function buildServerGroupCommandFromExisting(application, serverGroup, mode) { return getDelegate(serverGroup.type).buildServerGroupCommandFromExisting(application, serverGroup, mode); } function buildNewServerGroupCommandForPipeline(provider) { return getDelegate(provider).buildNewServerGroupCommandForPipeline(); } function buildServerGroupCommandFromPipeline(application, cluster) { return getDelegate(cluster.provider).buildServerGroupCommandFromPipeline(application, cluster); } return { getServerGroup: getServerGroup, buildNewServerGroupCommand: buildNewServerGroupCommand, buildServerGroupCommandFromExisting: buildServerGroupCommandFromExisting, buildNewServerGroupCommandForPipeline: buildNewServerGroupCommandForPipeline, buildServerGroupCommandFromPipeline: buildServerGroupCommandFromPipeline, }; }).name;
{ "content_hash": "48301d792b5cb2dff43da0a5fe5835c2", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 130, "avg_line_length": 41.44444444444444, "alnum_prop": 0.767828418230563, "repo_name": "zanthrash/deck-old", "id": "eb6232bc2dc47510b07a52b928c43eaed37909fa", "size": "1865", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/scripts/modules/core/serverGroup/configure/common/serverGroupCommandBuilder.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "24139" }, { "name": "CSS", "bytes": "99587" }, { "name": "HTML", "bytes": "787246" }, { "name": "JavaScript", "bytes": "1836403" } ], "symlink_target": "" }
<table> <tr> <td>Package</td><td>react-responsive</td> </tr> <tr> <td>Description</td> <td>Media queries in react for responsive design</td> </tr> <tr> <td>Browser Version</td> <td>>= IE6*</td> </tr> </tr> <tr> <td colspan="2"><a href="http://contra.io/react-responsive/">Demo</a></td> </tr> </table> The best supported, easiest to use react media query module. This module is pretty straightforward: You specify a set of requirements, and the children will be rendered if they are met. Also handles changes so if you resize or flip or whatever it all just works. ## Install ```console $ npm install react-responsive --save ``` ## Usage A MediaQuery element functions like any other React component, which means you can nest them and do all the normal jazz. ### Using CSS Media Queries ```jsx var MediaQuery = require('react-responsive'); var A = React.createClass({ render: function(){ return ( <div> <div>Device Test!</div> <MediaQuery query='(min-device-width: 1224px)'> <div>You are a desktop or laptop</div> <MediaQuery query='(min-device-width: 1824px)'> <div>You also have a huge screen</div> </MediaQuery> <MediaQuery query='(max-width: 1224px)'> <div>You are sized like a tablet or mobile phone though</div> </MediaQuery> </MediaQuery> <MediaQuery query='(max-device-width: 1224px)'> <div>You are a tablet or mobile phone</div> </MediaQuery> <MediaQuery query='(orientation: portrait)'> <div>You are portrait</div> </MediaQuery> <MediaQuery query='(orientation: landscape)'> <div>You are landscape</div> </MediaQuery> <MediaQuery query='(min-resolution: 2dppx)'> <div>You are retina</div> </MediaQuery> </div> ); } }); ``` ### Using Properties To make things more idiomatic to react, you can use camelcased shorthands to construct media queries. For a list of all possible shorthands and value types see https://github.com/wearefractal/react-responsive/blob/master/src/mediaQuery.js#L9 Any numbers given as a shorthand will be expanded to px (`1234` will become `'1234px'`) ```jsx var MediaQuery = require('react-responsive'); var A = React.createClass({ render: function(){ return ( <div> <div>Device Test!</div> <MediaQuery minDeviceWidth={1224}> <div>You are a desktop or laptop</div> <MediaQuery minDeviceWidth={1824}> <div>You also have a huge screen</div> </MediaQuery> <MediaQuery maxWidth={1224}> <div>You are sized like a tablet or mobile phone though</div> </MediaQuery> </MediaQuery> <MediaQuery maxDeviceWidth={1224}> <div>You are a tablet or mobile phone</div> </MediaQuery> <MediaQuery orientation='portrait'> <div>You are portrait</div> </MediaQuery> <MediaQuery orientation='landscape'> <div>You are landscape</div> </MediaQuery> <MediaQuery minResolution='2dppx'> <div>You are retina</div> </MediaQuery> </div> ); } }); ``` ### Rendering with a child function You may also specify a function for the child of the MediaQuery component. When the component renders, it is passed whether or not the given media query matches. This function must return a single element or `null`. ```jsx <MediaQuery minDeviceWidth={700}> {(matches) => { if (matches) { return <div>Media query matches!</div>; } else { return <div>Media query does not match!</div>; } }} </MediaQuery> ``` ### Component Property You may specify an optional `component` property on the `MediaQuery` that indicates what component to wrap children with. Any additional props defined on the `MediaQuery` will be passed through to this "wrapper" component. If the `component` property is not defined and the `MediaQuery` has more than 1 child, a `div` will be used as the "wrapper" component by default. However, if the `component` prop is not defined and there is only 1 child, that child will be rendered alone without a component wrapping it. **Specifying Wrapper Component** ```jsx <MediaQuery minDeviceWidth={700} component="ul"> <li>Item 1</li> <li>Item 2</li> </MediaQuery> // renders the following when the media query condition is met <ul> <li>Item 1</li> <li>Item 2</li> </ul> ``` **Unwrapped Component** ```jsx <MediaQuery minDeviceWidth={700}> <div>Unwrapped component</div> </MediaQuery> // renders the following when the media query condition is met <div>Unwrapped component</div> ``` **Default div Wrapper Component** ```jsx <MediaQuery minDeviceWidth={1200} className="some-class"> <div>Wrapped</div> <div>Content</div> </MediaQuery> // renders the following when the media query condition is met <div className="some-class"> <div>Wrapped</div> <div>Content</div> </div> ``` ### Server rendering Server rendering can be done by passing static values through the `values` property. The values property can contain `orientation`, `scan`, `aspectRatio`, `deviceAspectRatio`, `height`, `deviceHeight`, `width`, `deviceWidth`, `color`, `colorIndex`, `monochrome`, `resolution` and `type` to be matched against the media query. `type` can be one of: `all`, `grid`, `aural`, `braille`, `handheld`, `print`, `projection`, `screen`, `tty`, `tv` or `embossed`. ```jsx var MediaQuery = require('react-responsive'); var A = React.createClass({ render: function(){ return ( <div> <div>Device Test!</div> <MediaQuery minDeviceWidth={1224} values={{deviceWidth: 1600}}> <div>You are a desktop or laptop</div> <MediaQuery minDeviceWidth={1824}> <div>You also have a huge screen</div> </MediaQuery> <MediaQuery maxWidth={1224}> <div>You are sized like a tablet or mobile phone though</div> </MediaQuery> </MediaQuery> <MediaQuery maxDeviceWidth={1224}> <div>You are a tablet or mobile phone</div> </MediaQuery> <MediaQuery orientation='portrait'> <div>You are portrait</div> </MediaQuery> <MediaQuery orientation='landscape'> <div>You are landscape</div> </MediaQuery> <MediaQuery minResolution='2dppx'> <div>You are retina</div> </MediaQuery> </div> ); } }); ``` ## Browser Support ### Out of the box <table> <tr> <td>Chrome</td> <td>9</td> </tr> <tr> <td>Firefox (Gecko)</td> <td>6</td> </tr> <tr> <td>MS Edge</td> <td>All</td> </tr> <tr> <td>Internet Explorer</td> <td>10</td> </tr> <tr> <td>Opera</td> <td>12.1</td> </tr> <tr> <td>Safari</td> <td>5.1</td> </tr> </table> ### With Polyfills Pretty much everything. Check out these polyfills: - [matchMedia.js by Paul Irish](https://github.com/paulirish/matchMedia.js/) - [media-match (faster, but larger and lacking some features)](https://github.com/weblinc/media-match) [gittip-url]: https://www.gittip.com/WeAreFractal/ [gittip-image]: http://img.shields.io/gittip/WeAreFractal.svg [downloads-image]: http://img.shields.io/npm/dm/react-responsive.svg [npm-url]: https://npmjs.org/package/react-responsive [npm-image]: http://img.shields.io/npm/v/react-responsive.svg
{ "content_hash": "73d86e1011c945f41df8cf7940148e2d", "timestamp": "", "source": "github", "line_count": 270, "max_line_length": 511, "avg_line_length": 27.32962962962963, "alnum_prop": 0.6480552920449926, "repo_name": "geng890518/editor-ui", "id": "8861555e01b0d94d527105bcb5746212205c8885", "size": "7536", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/react-responsive/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "127022" }, { "name": "JavaScript", "bytes": "260497" } ], "symlink_target": "" }
#ifndef _DISK_H_ #define _DISK_H_ #include <unistd.h> #define DISK_BLOCKS 8192 /* number of blocks on the disk */ #define BLOCK_SIZE 4096 /* block size on "disk" */ #define MAX_FILE_COUNT 64 /** * @brief The file control block struct */ struct fcb { char file_name[20]; unsigned char is_opened; unsigned int size; unsigned int first_block; unsigned int last_block; unsigned int last_block_used; // n-bytes used from last block } __attribute__((packed)); /** * @brief The volume control block struct */ struct vcb { int free_block_count; unsigned char free_fcb[MAX_FILE_COUNT]; } __attribute__((packed)); struct metadata { int disk_blocks; // for validation struct vcb vcb; struct fcb fcb_list[MAX_FILE_COUNT]; } __attribute__((packed)); int make_disk(char *name); /* create an empty, virtual disk file */ int open_disk(char *name); /* open a virtual disk (file) */ int close_disk(); /* close a previously opened disk (file) */ int block_write(int block, char *buf); /* write a block of size BLOCK_SIZE to disk */ int block_read(int block, char *buf); /* read a block of size BLOCK_SIZE from disk */ int make_fs(char *disk_name); int mount_fs(char *disk_name); int umount_fs(char *disk_name); /** * @brief rewrite metadata in disk * Assumes the disk is mounted * @return -1 in case of error, 0 in case of success */ int metadata_rewrite(); #endif
{ "content_hash": "a370fd95e89e1d28b910aa2ecd7aca01", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 90, "avg_line_length": 27.925925925925927, "alnum_prop": 0.626657824933687, "repo_name": "moreka/os-prj3", "id": "84c9c06b48bab49358626aac0548012e90528c28", "size": "1508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "disk.h", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "3427" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Linq; namespace Yaclops.Parsing.Configuration { internal class ParserConfiguration { private readonly List<ParserCommand> _commands = new List<ParserCommand>(); private readonly List<ParserNamedParameter> _namedParameters = new List<ParserNamedParameter>(); public ParserCommand AddCommand(string commandText) { if (_commands.Any(x => x.Text == commandText)) { throw new ParserConfigurationException("Cannot add duplicate command '{0}'.", commandText); } var command = new ParserCommand(commandText); _commands.Add(command); return command; } public ParserCommand DefaultCommand { get; set; } public IEnumerable<ParserCommand> Commands { get { return _commands; } } public IEnumerable<ParserNamedParameter> GlobalNamedParameters { get { return _namedParameters; } } public ParserNamedParameter AddNamedParameter(string key, bool isBool = false) { var param = new ParserNamedParameter(key, isBool); // TODO - check for duplicates _namedParameters.Add(param); return param; } } }
{ "content_hash": "202ced6bb831d34d26f13d774fa9bb1c", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 107, "avg_line_length": 29.651162790697676, "alnum_prop": 0.6345098039215686, "repo_name": "dswisher/yaclops", "id": "741c45c18b8ef6b38d5502374819b6d54a14c353", "size": "1277", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Old/YaclopsOld/Parsing/Configuration/ParserConfiguration.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "279" }, { "name": "C#", "bytes": "279341" } ], "symlink_target": "" }
import grpc from . import ( engine_pb2 as google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2, ) from . import ( quantum_pb2 as google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2, ) from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 class QuantumEngineServiceStub(object): """- - """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.CreateQuantumProgram = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumProgram', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.CreateQuantumProgramRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumProgram.FromString, ) self.GetQuantumProgram = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProgram', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumProgramRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumProgram.FromString, ) self.ListQuantumPrograms = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumPrograms', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumProgramsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumProgramsResponse.FromString, ) self.DeleteQuantumProgram = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumProgram', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.DeleteQuantumProgramRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.UpdateQuantumProgram = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumProgram', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.UpdateQuantumProgramRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumProgram.FromString, ) self.CreateQuantumJob = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumJob', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.CreateQuantumJobRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumJob.FromString, ) self.GetQuantumJob = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumJob', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumJobRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumJob.FromString, ) self.ListQuantumJobs = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumJobs', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumJobsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumJobsResponse.FromString, ) self.DeleteQuantumJob = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumJob', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.DeleteQuantumJobRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.UpdateQuantumJob = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumJob', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.UpdateQuantumJobRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumJob.FromString, ) self.CancelQuantumJob = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CancelQuantumJob', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.CancelQuantumJobRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.ListQuantumJobEvents = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumJobEvents', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumJobEventsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumJobEventsResponse.FromString, ) self.GetQuantumResult = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumResult', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumResultRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumResult.FromString, ) self.ListQuantumProcessors = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumProcessors', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumProcessorsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumProcessorsResponse.FromString, ) self.GetQuantumProcessor = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumProcessor', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumProcessorRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumProcessor.FromString, ) self.ListQuantumCalibrations = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumCalibrations', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumCalibrationsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumCalibrationsResponse.FromString, ) self.GetQuantumCalibration = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumCalibration', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumCalibrationRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumCalibration.FromString, ) self.CreateQuantumReservation = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CreateQuantumReservation', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.CreateQuantumReservationRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumReservation.FromString, ) self.CancelQuantumReservation = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/CancelQuantumReservation', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.CancelQuantumReservationRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumReservation.FromString, ) self.DeleteQuantumReservation = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/DeleteQuantumReservation', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.DeleteQuantumReservationRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.GetQuantumReservation = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/GetQuantumReservation', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumReservationRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumReservation.FromString, ) self.ListQuantumReservations = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservations', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationsResponse.FromString, ) self.UpdateQuantumReservation = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/UpdateQuantumReservation', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.UpdateQuantumReservationRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumReservation.FromString, ) self.QuantumRunStream = channel.stream_stream( '/google.cloud.quantum.v1alpha1.QuantumEngineService/QuantumRunStream', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.QuantumRunStreamRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.QuantumRunStreamResponse.FromString, ) self.ListQuantumReservationGrants = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservationGrants', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationGrantsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationGrantsResponse.FromString, ) self.ReallocateQuantumReservationGrant = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ReallocateQuantumReservationGrant', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ReallocateQuantumReservationGrantRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumReservationGrant.FromString, ) self.ListQuantumReservationBudgets = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumReservationBudgets', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationBudgetsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationBudgetsResponse.FromString, ) self.ListQuantumTimeSlots = channel.unary_unary( '/google.cloud.quantum.v1alpha1.QuantumEngineService/ListQuantumTimeSlots', request_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumTimeSlotsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumTimeSlotsResponse.FromString, ) class QuantumEngineServiceServicer(object): """- - """ def CreateQuantumProgram(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetQuantumProgram(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListQuantumPrograms(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DeleteQuantumProgram(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def UpdateQuantumProgram(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def CreateQuantumJob(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetQuantumJob(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListQuantumJobs(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DeleteQuantumJob(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def UpdateQuantumJob(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def CancelQuantumJob(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListQuantumJobEvents(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetQuantumResult(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListQuantumProcessors(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetQuantumProcessor(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListQuantumCalibrations(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetQuantumCalibration(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def CreateQuantumReservation(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def CancelQuantumReservation(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def DeleteQuantumReservation(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetQuantumReservation(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListQuantumReservations(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def UpdateQuantumReservation(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def QuantumRunStream(self, request_iterator, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListQuantumReservationGrants(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ReallocateQuantumReservationGrant(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListQuantumReservationBudgets(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def ListQuantumTimeSlots(self, request, context): """-""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_QuantumEngineServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'CreateQuantumProgram': grpc.unary_unary_rpc_method_handler( servicer.CreateQuantumProgram, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.CreateQuantumProgramRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumProgram.SerializeToString, ), 'GetQuantumProgram': grpc.unary_unary_rpc_method_handler( servicer.GetQuantumProgram, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumProgramRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumProgram.SerializeToString, ), 'ListQuantumPrograms': grpc.unary_unary_rpc_method_handler( servicer.ListQuantumPrograms, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumProgramsRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumProgramsResponse.SerializeToString, ), 'DeleteQuantumProgram': grpc.unary_unary_rpc_method_handler( servicer.DeleteQuantumProgram, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.DeleteQuantumProgramRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'UpdateQuantumProgram': grpc.unary_unary_rpc_method_handler( servicer.UpdateQuantumProgram, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.UpdateQuantumProgramRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumProgram.SerializeToString, ), 'CreateQuantumJob': grpc.unary_unary_rpc_method_handler( servicer.CreateQuantumJob, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.CreateQuantumJobRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumJob.SerializeToString, ), 'GetQuantumJob': grpc.unary_unary_rpc_method_handler( servicer.GetQuantumJob, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumJobRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumJob.SerializeToString, ), 'ListQuantumJobs': grpc.unary_unary_rpc_method_handler( servicer.ListQuantumJobs, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumJobsRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumJobsResponse.SerializeToString, ), 'DeleteQuantumJob': grpc.unary_unary_rpc_method_handler( servicer.DeleteQuantumJob, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.DeleteQuantumJobRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'UpdateQuantumJob': grpc.unary_unary_rpc_method_handler( servicer.UpdateQuantumJob, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.UpdateQuantumJobRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumJob.SerializeToString, ), 'CancelQuantumJob': grpc.unary_unary_rpc_method_handler( servicer.CancelQuantumJob, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.CancelQuantumJobRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'ListQuantumJobEvents': grpc.unary_unary_rpc_method_handler( servicer.ListQuantumJobEvents, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumJobEventsRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumJobEventsResponse.SerializeToString, ), 'GetQuantumResult': grpc.unary_unary_rpc_method_handler( servicer.GetQuantumResult, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumResultRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumResult.SerializeToString, ), 'ListQuantumProcessors': grpc.unary_unary_rpc_method_handler( servicer.ListQuantumProcessors, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumProcessorsRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumProcessorsResponse.SerializeToString, ), 'GetQuantumProcessor': grpc.unary_unary_rpc_method_handler( servicer.GetQuantumProcessor, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumProcessorRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumProcessor.SerializeToString, ), 'ListQuantumCalibrations': grpc.unary_unary_rpc_method_handler( servicer.ListQuantumCalibrations, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumCalibrationsRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumCalibrationsResponse.SerializeToString, ), 'GetQuantumCalibration': grpc.unary_unary_rpc_method_handler( servicer.GetQuantumCalibration, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumCalibrationRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumCalibration.SerializeToString, ), 'CreateQuantumReservation': grpc.unary_unary_rpc_method_handler( servicer.CreateQuantumReservation, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.CreateQuantumReservationRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumReservation.SerializeToString, ), 'CancelQuantumReservation': grpc.unary_unary_rpc_method_handler( servicer.CancelQuantumReservation, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.CancelQuantumReservationRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumReservation.SerializeToString, ), 'DeleteQuantumReservation': grpc.unary_unary_rpc_method_handler( servicer.DeleteQuantumReservation, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.DeleteQuantumReservationRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), 'GetQuantumReservation': grpc.unary_unary_rpc_method_handler( servicer.GetQuantumReservation, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.GetQuantumReservationRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumReservation.SerializeToString, ), 'ListQuantumReservations': grpc.unary_unary_rpc_method_handler( servicer.ListQuantumReservations, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationsRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationsResponse.SerializeToString, ), 'UpdateQuantumReservation': grpc.unary_unary_rpc_method_handler( servicer.UpdateQuantumReservation, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.UpdateQuantumReservationRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumReservation.SerializeToString, ), 'QuantumRunStream': grpc.stream_stream_rpc_method_handler( servicer.QuantumRunStream, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.QuantumRunStreamRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.QuantumRunStreamResponse.SerializeToString, ), 'ListQuantumReservationGrants': grpc.unary_unary_rpc_method_handler( servicer.ListQuantumReservationGrants, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationGrantsRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationGrantsResponse.SerializeToString, ), 'ReallocateQuantumReservationGrant': grpc.unary_unary_rpc_method_handler( servicer.ReallocateQuantumReservationGrant, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ReallocateQuantumReservationGrantRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_quantum__pb2.QuantumReservationGrant.SerializeToString, ), 'ListQuantumReservationBudgets': grpc.unary_unary_rpc_method_handler( servicer.ListQuantumReservationBudgets, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationBudgetsRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumReservationBudgetsResponse.SerializeToString, ), 'ListQuantumTimeSlots': grpc.unary_unary_rpc_method_handler( servicer.ListQuantumTimeSlots, request_deserializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumTimeSlotsRequest.FromString, response_serializer=google_dot_cloud_dot_quantum__v1alpha1_dot_proto_dot_engine__pb2.ListQuantumTimeSlotsResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'google.cloud.quantum.v1alpha1.QuantumEngineService', rpc_method_handlers ) server.add_generic_rpc_handlers((generic_handler,))
{ "content_hash": "e306d2bfdca526a757c05ac19c38a3d8", "timestamp": "", "source": "github", "line_count": 487, "max_line_length": 155, "avg_line_length": 62.997946611909654, "alnum_prop": 0.7247392438070405, "repo_name": "balopat/Cirq", "id": "902292f9ca20d353ec8a00c972ec3a95dd0474eb", "size": "30750", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cirq-google/cirq_google/engine/client/quantum_v1alpha1/proto/engine_pb2_grpc.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "5923" }, { "name": "HTML", "bytes": "262" }, { "name": "Jupyter Notebook", "bytes": "23905" }, { "name": "Makefile", "bytes": "634" }, { "name": "Python", "bytes": "6256825" }, { "name": "Shell", "bytes": "50383" }, { "name": "Starlark", "bytes": "5979" } ], "symlink_target": "" }
<?php namespace TwigJs; interface TestCompilerInterface { function getName(); function compile(JsCompiler $compiler, \Twig_Node_Expression_Test $node); }
{ "content_hash": "55bf57eb9e12065420003375bac98a67", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 77, "avg_line_length": 15, "alnum_prop": 0.7393939393939394, "repo_name": "hostnet/twig.js", "id": "f8a01edabfa0b1dce6ea795d1cc61d99a794a79c", "size": "786", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/TwigJs/TestCompilerInterface.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "21527" }, { "name": "JavaScript", "bytes": "87974" }, { "name": "Makefile", "bytes": "365" }, { "name": "PHP", "bytes": "180253" } ], "symlink_target": "" }
FOUNDATION_EXPORT double Pods_Konex_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_Konex_ExampleVersionString[];
{ "content_hash": "c55c48f2a7df3d687d73c7e1312dbddd", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 72, "avg_line_length": 44, "alnum_prop": 0.8560606060606061, "repo_name": "fmo91/Konex", "id": "308d2202fe5a1e11c8a81d9cf29622a19ae1578c", "size": "181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/Pods/Target Support Files/Pods-Konex_Example/Pods-Konex_Example-umbrella.h", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "143" }, { "name": "Swift", "bytes": "362074" } ], "symlink_target": "" }
namespace ash { FakeUserImageFileSelector::FakeUserImageFileSelector(content::WebUI* web_ui) : UserImageFileSelector(web_ui) {} FakeUserImageFileSelector::~FakeUserImageFileSelector() {} void FakeUserImageFileSelector::SelectFile( base::OnceCallback<void(const base::FilePath&)> selected_cb, base::OnceCallback<void(void)> canceled_cb) { std::move(selected_cb).Run(file_path_); } void FakeUserImageFileSelector::SetFilePath(const base::FilePath& file_path) { file_path_ = file_path; } } // namespace ash
{ "content_hash": "751b5bcb4e3ef9c6cbbe9d8939e9a742", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 78, "avg_line_length": 29.22222222222222, "alnum_prop": 0.752851711026616, "repo_name": "scheib/chromium", "id": "fa37d8d69544486cc4c18cbe082edaeabce863e8", "size": "774", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "chrome/browser/ash/login/users/avatar/fake_user_image_file_selector.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
@interface LocationCell : WLCustomCell @property (weak, nonatomic) IBOutlet UILabel *addressLab; @property (weak, nonatomic) IBOutlet UILabel *locLab; @property (weak, nonatomic) IBOutlet UILabel *timeLab; @end
{ "content_hash": "d689263641234166f58e2c22493e50eb", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 57, "avg_line_length": 23.88888888888889, "alnum_prop": 0.7767441860465116, "repo_name": "SummerHenry/Tool_General", "id": "c85252f9c6d0e22c5e31c9273f343a926cd24ca8", "size": "374", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "yqDemo/yqDemo/Main/View/LocationCell.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "54687" }, { "name": "Objective-C", "bytes": "477731" }, { "name": "Objective-C++", "bytes": "124423" } ], "symlink_target": "" }
type: post121 title: Querying the Space categories: XAP121NET, PRM parent: none weight: 600 --- This section explains the various mechanisms offered by GigaSpaces XAP to query the space for data, as well as related topics, such as how to use indexing to boost query performance and how the space can be iterated to fetch entries more efficiently. <br> {{%fpanel%}} [Id Queries](./query-by-id.html){{<wbr>}} Id Based query - Primary Key based object retrieval from space. [Query by template](./query-template-matching.html){{<wbr>}} Template matching (a.k.a. Match by example) is a simple way to query the space. [Prepared template](./query-prepared-template.html){{<wbr>}} Querying the space using a Prepared Template. [SQL Query](./query-sql.html){{<wbr>}} The SQLQuery class is used to query the space using SQL-like syntax. [Free text search](./query-free-text-search.html){{<wbr>}} Search for records that include one or more words within a free text field. [Nested property queries](./query-nested-properties.html){{<wbr>}} Query nested properties, maps and collections using SQL queries. [Partial results - Projection](./query-partial-results.html){{<wbr>}} Obtaining partial results when querying the space to improve application performance and reduce memory footprint. [Paging support](./query-paging-support.html){{<wbr>}} Reading large number of objects using multiple queries in one call in a continuous manner. [LINQ](./query-linq.html){{<wbr>}} Querying the space using LINQ {{%/fpanel%}}
{ "content_hash": "3081e01db4154047eb1f024b3bdbdcc7", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 250, "avg_line_length": 33.08695652173913, "alnum_prop": 0.7496714848883048, "repo_name": "croffler/documentation", "id": "a8347f222ff8f3262bcc59b91646d8fb766a541a", "size": "1526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sites/xap-docs/content/xap121net/querying-the-space.markdown", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2013 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. --> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.kitware.android.glass.sample.line" android:versionCode="2" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="15" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <application android:allowBackup="true" android:label="@string/app_name" android:icon="@drawable/ic_line" > <uses-library android:name="com.google.android.glass" android:required="true" /> <activity android:name="com.kitware.android.glass.sample.line.LineMenuActivity" android:theme="@style/MenuTheme" /> </application> </manifest>
{ "content_hash": "de041e3d61342bf7efc0474838de17ed", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 81, "avg_line_length": 33.86046511627907, "alnum_prop": 0.6758241758241759, "repo_name": "luisibanez/gdk-line-sample", "id": "f89db0abd5814dd5e5051f81643d654e947f5aba", "size": "1456", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "60365" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.demo</groupId> <artifactId>spring-aspectj</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <version.server.bom>19.0.0.Final</version.server.bom> <spring.version>5.1.17.RELEASE</spring.version> <maven.compiler.source>1.6</maven.compiler.source> <maven.compiler.target>1.6</maven.compiler.target> <aspectj.version>1.6.8</aspectj.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.wildfly.bom</groupId> <artifactId>wildfly-jakartaee8-with-tools</artifactId> <version>${version.server.bom}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>jakarta.enterprise</groupId> <artifactId>jakarta.enterprise.cdi-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.spec.javax.servlet</groupId> <artifactId>jboss-servlet-api_4.0_spec</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- AOP --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>org.wildfly.plugins</groupId> <artifactId>wildfly-maven-plugin</artifactId> <version>2.0.0.Final</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "36aa26c14398ee784fae725f71b0634e", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 108, "avg_line_length": 35.83157894736842, "alnum_prop": 0.5769682726204466, "repo_name": "fmarchioni/mastertheboss", "id": "6dee9f26efe32afcd15b35107ef2d5fee0eba204", "size": "3404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring/spring-aspectj/pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "11870" }, { "name": "CSS", "bytes": "35387" }, { "name": "Dockerfile", "bytes": "99" }, { "name": "HTML", "bytes": "1315278" }, { "name": "Java", "bytes": "762286" }, { "name": "JavaScript", "bytes": "2723393" }, { "name": "Kotlin", "bytes": "1314" }, { "name": "Shell", "bytes": "27623" } ], "symlink_target": "" }
@interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @end
{ "content_hash": "6a94114268219561fec9205a9a9264c0", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 281, "avg_line_length": 53.48571428571429, "alnum_prop": 0.7863247863247863, "repo_name": "i36lib/DBGuestureLock", "id": "cc2be3b6aa6b21222ff211b058f8e752068ffb38", "size": "2132", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Demo/Demo/AppDelegate.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "35845" }, { "name": "Ruby", "bytes": "706" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_03) on Mon Nov 19 21:41:16 CET 2007 --> <TITLE> Uses of Interface org.springframework.beans.factory.support.AutowireCandidateResolver (Spring Framework API 2.5) </TITLE> <META NAME="date" CONTENT="2007-11-19"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.springframework.beans.factory.support.AutowireCandidateResolver (Spring Framework API 2.5)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <a href="http://www.springframework.org/" target="_top">The Spring Framework</a></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/springframework/beans/factory/support/\class-useAutowireCandidateResolver.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="AutowireCandidateResolver.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Interface<br>org.springframework.beans.factory.support.AutowireCandidateResolver</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support">AutowireCandidateResolver</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.springframework.beans.factory.annotation"><B>org.springframework.beans.factory.annotation</B></A></TD> <TD>Support package for annotation-driven bean configuration.&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.springframework.beans.factory.support"><B>org.springframework.beans.factory.support</B></A></TD> <TD>Classes supporting the <code>org.springframework.beans.factory</code> package.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.springframework.beans.factory.annotation"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support">AutowireCandidateResolver</A> in <A HREF="../../../../../../org/springframework/beans/factory/annotation/package-summary.html">org.springframework.beans.factory.annotation</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../../org/springframework/beans/factory/annotation/package-summary.html">org.springframework.beans.factory.annotation</A> that implement <A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support">AutowireCandidateResolver</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.html" title="class in org.springframework.beans.factory.annotation">QualifierAnnotationAutowireCandidateResolver</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support"><CODE>AutowireCandidateResolver</CODE></A> implementation that matches bean definition qualifiers against qualifier annotations on the field or parameter to be autowired.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.springframework.beans.factory.support"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support">AutowireCandidateResolver</A> in <A HREF="../../../../../../org/springframework/beans/factory/support/package-summary.html">org.springframework.beans.factory.support</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../../org/springframework/beans/factory/support/package-summary.html">org.springframework.beans.factory.support</A> that implement <A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support">AutowireCandidateResolver</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../org/springframework/beans/factory/support/SimpleAutowireCandidateResolver.html" title="class in org.springframework.beans.factory.support">SimpleAutowireCandidateResolver</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support"><CODE>AutowireCandidateResolver</CODE></A> implementation to use when Java version is less than 1.5 and therefore no annotation support is available.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/springframework/beans/factory/support/package-summary.html">org.springframework.beans.factory.support</A> that return <A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support">AutowireCandidateResolver</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support">AutowireCandidateResolver</A></CODE></FONT></TD> <TD><CODE><B>DefaultListableBeanFactory.</B><B><A HREF="../../../../../../org/springframework/beans/factory/support/DefaultListableBeanFactory.html#getAutowireCandidateResolver()">getAutowireCandidateResolver</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Return the autowire candidate resolver for this BeanFactory (never <code>null</code>).</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/springframework/beans/factory/support/package-summary.html">org.springframework.beans.factory.support</A> with parameters of type <A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support">AutowireCandidateResolver</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>DefaultListableBeanFactory.</B><B><A HREF="../../../../../../org/springframework/beans/factory/support/DefaultListableBeanFactory.html#setAutowireCandidateResolver(org.springframework.beans.factory.support.AutowireCandidateResolver)">setAutowireCandidateResolver</A></B>(<A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support">AutowireCandidateResolver</A>&nbsp;autowireCandidateResolver)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Set a custom autowire candidate resolver for this BeanFactory to use when deciding whether a bean definition should be considered as a candidate for autowiring.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/springframework/beans/factory/support/AutowireCandidateResolver.html" title="interface in org.springframework.beans.factory.support"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <a href="http://www.springframework.org/" target="_top">The Spring Framework</a></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/springframework/beans/factory/support/\class-useAutowireCandidateResolver.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="AutowireCandidateResolver.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &copy; 2002-2007 <a href=http://www.springframework.org/ target=_top>The Spring Framework</a>.</i> </BODY> </HTML>
{ "content_hash": "1f90fe63b71a4dc7c66b9795a522e541", "timestamp": "", "source": "github", "line_count": 245, "max_line_length": 516, "avg_line_length": 57.412244897959184, "alnum_prop": 0.6829233612967439, "repo_name": "mattxia/spring-2.5-analysis", "id": "bd9576be0c466020df94766a1192388c3e5dd26c", "size": "14066", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/org/springframework/beans/factory/support/class-use/AutowireCandidateResolver.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "18516" }, { "name": "CSS", "bytes": "20368" }, { "name": "Groovy", "bytes": "2361" }, { "name": "Java", "bytes": "16366293" }, { "name": "Ruby", "bytes": "623" }, { "name": "Shell", "bytes": "684" }, { "name": "XSLT", "bytes": "2674" } ], "symlink_target": "" }
--- description: Enabling AppArmor in Docker keywords: AppArmor, security, docker, documentation title: AppArmor security profiles for Docker --- AppArmor (Application Armor) is a Linux security module that protects an operating system and its applications from security threats. To use it, a system administrator associates an AppArmor security profile with each program. Docker expects to find an AppArmor policy loaded and enforced. Docker automatically generates and loads a default profile for containers named `docker-default`. On Docker versions `1.13.0` and later, the Docker binary generates this profile in `tmpfs` and then loads it into the kernel. On Docker versions earlier than `1.13.0`, this profile is generated in `/etc/apparmor.d/docker` instead. > **Note:** This profile is used on containers, _not_ on the Docker Daemon. A profile for the Docker Engine daemon exists but it is not currently installed with the `deb` packages. If you are interested in the source for the daemon profile, it is located in [contrib/apparmor](https://github.com/docker/docker/tree/master/contrib/apparmor) in the Docker Engine source repository. ## Understand the policies The `docker-default` profile is the default for running containers. It is moderately protective while providing wide application compatibility. The profile is generated from the following [template](https://github.com/docker/docker/blob/master/profiles/apparmor/template.go). When you run a container, it uses the `docker-default` policy unless you override it with the `security-opt` option. For example, the following explicitly specifies the default policy: ```bash $ docker run --rm -it --security-opt apparmor=docker-default hello-world ``` ## Load and unload profiles To load a new profile into AppArmor for use with containers: ```bash $ apparmor_parser -r -W /path/to/your_profile ``` Then, run the custom profile with `--security-opt` like so: ```bash $ docker run --rm -it --security-opt apparmor=your_profile hello-world ``` To unload a profile from AppArmor: ```bash # stop apparmor $ /etc/init.d/apparmor stop # unload the profile $ apparmor_parser -R /path/to/profile # start apparmor $ /etc/init.d/apparmor start ``` ### Resources for writing profiles The syntax for file globbing in AppArmor is a bit different than some other globbing implementations. It is highly suggested you take a look at some of the below resources with regard to AppArmor profile syntax. - [Quick Profile Language](http://wiki.apparmor.net/index.php/QuickProfileLanguage) - [Globbing Syntax](http://wiki.apparmor.net/index.php/AppArmor_Core_Policy_Reference#AppArmor_globbing_syntax) ## Nginx example profile In this example, you create a custom AppArmor profile for Nginx. Below is the custom profile. ``` #include <tunables/global> profile docker-nginx flags=(attach_disconnected,mediate_deleted) { #include <abstractions/base> network inet tcp, network inet udp, network inet icmp, deny network raw, deny network packet, file, umount, deny /bin/** wl, deny /boot/** wl, deny /dev/** wl, deny /etc/** wl, deny /home/** wl, deny /lib/** wl, deny /lib64/** wl, deny /media/** wl, deny /mnt/** wl, deny /opt/** wl, deny /proc/** wl, deny /root/** wl, deny /sbin/** wl, deny /srv/** wl, deny /tmp/** wl, deny /sys/** wl, deny /usr/** wl, audit /** w, /var/run/nginx.pid w, /usr/sbin/nginx ix, deny /bin/dash mrwklx, deny /bin/sh mrwklx, deny /usr/bin/top mrwklx, capability chown, capability dac_override, capability setuid, capability setgid, capability net_bind_service, deny @{PROC}/* w, # deny write for all files directly in /proc (not in a subdir) # deny write to files not in /proc/<number>/** or /proc/sys/** deny @{PROC}/{[^1-9],[^1-9][^0-9],[^1-9s][^0-9y][^0-9s],[^1-9][^0-9][^0-9][^0-9]*}/** w, deny @{PROC}/sys/[^k]** w, # deny /proc/sys except /proc/sys/k* (effectively /proc/sys/kernel) deny @{PROC}/sys/kernel/{?,??,[^s][^h][^m]**} w, # deny everything except shm* in /proc/sys/kernel/ deny @{PROC}/sysrq-trigger rwklx, deny @{PROC}/mem rwklx, deny @{PROC}/kmem rwklx, deny @{PROC}/kcore rwklx, deny mount, deny /sys/[^f]*/** wklx, deny /sys/f[^s]*/** wklx, deny /sys/fs/[^c]*/** wklx, deny /sys/fs/c[^g]*/** wklx, deny /sys/fs/cg[^r]*/** wklx, deny /sys/firmware/** rwklx, deny /sys/kernel/security/** rwklx, } ``` 1. Save the custom profile to disk in the `/etc/apparmor.d/containers/docker-nginx` file. The file path in this example is not a requirement. In production, you could use another. 2. Load the profile. ```bash $ sudo apparmor_parser -r -W /etc/apparmor.d/containers/docker-nginx ``` 3. Run a container with the profile. To run nginx in detached mode: ```bash $ docker run --security-opt "apparmor=docker-nginx" \ -p 80:80 -d --name apparmor-nginx nginx ``` 4. Exec into the running container ```bash $ docker exec -it apparmor-nginx bash ``` 5. Try some operations to test the profile. ```bash root@6da5a2a930b9:~# ping 8.8.8.8 ping: Lacking privilege for raw socket. root@6da5a2a930b9:/# top bash: /usr/bin/top: Permission denied root@6da5a2a930b9:~# touch ~/thing touch: cannot touch 'thing': Permission denied root@6da5a2a930b9:/# sh bash: /bin/sh: Permission denied root@6da5a2a930b9:/# dash bash: /bin/dash: Permission denied ``` Congrats! You just deployed a container secured with a custom apparmor profile! ## Debug AppArmor You can use `dmesg` to debug problems and `aa-status` check the loaded profiles. ### Use dmesg Here are some helpful tips for debugging any problems you might be facing with regard to AppArmor. AppArmor sends quite verbose messaging to `dmesg`. Usually an AppArmor line looks like the following: ``` [ 5442.864673] audit: type=1400 audit(1453830992.845:37): apparmor="ALLOWED" operation="open" profile="/usr/bin/docker" name="/home/jessie/docker/man/man1/docker-attach.1" pid=10923 comm="docker" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0 ``` In the above example, you can see `profile=/usr/bin/docker`. This means the user has the `docker-engine` (Docker Engine Daemon) profile loaded. > **Note:** On version of Ubuntu > 14.04 this is all fine and well, but Trusty > users might run into some issues when trying to `docker exec`. Look at another log line: ``` [ 3256.689120] type=1400 audit(1405454041.341:73): apparmor="DENIED" operation="ptrace" profile="docker-default" pid=17651 comm="docker" requested_mask="receive" denied_mask="receive" ``` This time the profile is `docker-default`, which is run on containers by default unless in `privileged` mode. This line shows that apparmor has denied `ptrace` in the container. This is exactly as expected. ### Use aa-status If you need to check which profiles are loaded, you can use `aa-status`. The output looks like: ```bash $ sudo aa-status apparmor module is loaded. 14 profiles are loaded. 1 profiles are in enforce mode. docker-default 13 profiles are in complain mode. /usr/bin/docker /usr/bin/docker///bin/cat /usr/bin/docker///bin/ps /usr/bin/docker///sbin/apparmor_parser /usr/bin/docker///sbin/auplink /usr/bin/docker///sbin/blkid /usr/bin/docker///sbin/iptables /usr/bin/docker///sbin/mke2fs /usr/bin/docker///sbin/modprobe /usr/bin/docker///sbin/tune2fs /usr/bin/docker///sbin/xtables-multi /usr/bin/docker///sbin/zfs /usr/bin/docker///usr/bin/xz 38 processes have profiles defined. 37 processes are in enforce mode. docker-default (6044) ... docker-default (31899) 1 processes are in complain mode. /usr/bin/docker (29756) 0 processes are unconfined but have a profile defined. ``` The above output shows that the `docker-default` profile running on various container PIDs is in `enforce` mode. This means AppArmor is actively blocking and auditing in `dmesg` anything outside the bounds of the `docker-default` profile. The output above also shows the `/usr/bin/docker` (Docker Engine daemon) profile is running in `complain` mode. This means AppArmor _only_ logs to `dmesg` activity outside the bounds of the profile. (Except in the case of Ubuntu Trusty, where some interesting behaviors are enforced.) ## Contribute Docker's AppArmor code Advanced users and package managers can find a profile for `/usr/bin/docker` (Docker Engine Daemon) underneath [contrib/apparmor](https://github.com/docker/docker/tree/master/contrib/apparmor) in the Docker Engine source repository. The `docker-default` profile for containers lives in [profiles/apparmor](https://github.com/docker/docker/tree/master/profiles/apparmor).
{ "content_hash": "15d9236afa32497d38096596b000941f", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 248, "avg_line_length": 30.19655172413793, "alnum_prop": 0.7174831563320772, "repo_name": "sanscontext/docker.github.io", "id": "202a7702ca26601fbecb87292aead8393025d55b", "size": "8757", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "engine/security/apparmor.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1402651" }, { "name": "Go", "bytes": "8433" }, { "name": "HTML", "bytes": "1336934" }, { "name": "JavaScript", "bytes": "2820366" }, { "name": "Makefile", "bytes": "5057" }, { "name": "Ruby", "bytes": "4702" }, { "name": "Shell", "bytes": "6530" } ], "symlink_target": "" }
/*jshint node:true*/ /* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var app = new EmberApp(defaults, { fingerprint: { prepend: 'https://totally-sick-cdn.example.com/', assetMapPath: 'totally-customized-asset-map.json' } }); return app.toTree(); };
{ "content_hash": "37b115a129524eae3d3aec4525f7bb3d", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 59, "avg_line_length": 25.428571428571427, "alnum_prop": 0.6601123595505618, "repo_name": "GetBlimp/ember-cli-fastboot", "id": "2a9d796910edb025627dd24243b3e678907ade96", "size": "356", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/fixtures/customized-fingerprinting/ember-cli-build.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "960" }, { "name": "JavaScript", "bytes": "28871" } ], "symlink_target": "" }
`npm install -d` ## Lancer un serveur de dev : `npm run dev`
{ "content_hash": "9cd20a14b919ea088bbf928baf2fe29b", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 29, "avg_line_length": 12.6, "alnum_prop": 0.6349206349206349, "repo_name": "bastienfaulconnier/drunkgame", "id": "8ed759a7d64b8c48da70107be4ad8538fe84f4ad", "size": "130", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2243" }, { "name": "HTML", "bytes": "3724" }, { "name": "JavaScript", "bytes": "3554" } ], "symlink_target": "" }
This is a site where you can practice chess openings. You select an opening from the list and then attempt to play it on the board. You are supposed to always respond with the most commonly played continuation. If you do not the move will be taken back and you try again. See the site here: http://cabanachess.com/ ## Prep First download the latest version of KingBase in PGN ZIP format here: http://www.kingbase-chess.net/ Unzip the file and rename the folder as KingBase/ in the project directory. Then run `prep/treeify_games.py`. If successful it should generate a games/ directory. Next download the opening name PGN file from here: http://www.chessfiles.com/download-openings.html Copy the file ecoe.pgn to the project directory and run `prep/build_openings.py`. If successful it should generate an openings.json file. Finally, run `prep/logo.py` to create the logo and favicon. ## Running Install node modules: `npm install` Install forever: `npm install -g forever` Then run: `forever start app.js` By default the site will be accessible at http://localhost:3000/
{ "content_hash": "a28d22a5ad98373069f045f632a7b60f", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 314, "avg_line_length": 47.08695652173913, "alnum_prop": 0.7746999076638966, "repo_name": "philleski/cabana", "id": "0e163f5b7fc41ca393d7d16268eb04f070703ee0", "size": "1093", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1034" }, { "name": "HTML", "bytes": "15990" }, { "name": "JavaScript", "bytes": "51087" }, { "name": "Python", "bytes": "7208" } ], "symlink_target": "" }