text
stringlengths
2
1.04M
meta
dict
@interface SampleRootTableViewController : UITableViewController @end
{ "content_hash": "b3b9f41749871cedf52210a752c93c74", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 64, "avg_line_length": 23.666666666666668, "alnum_prop": 0.8732394366197183, "repo_name": "alexclp/STAControls", "id": "b6dbae42f2d4be6951a436003935aa18410b120d", "size": "256", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "STAControls/Sample/SampleRootTableViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "578" }, { "name": "Objective-C", "bytes": "370744" }, { "name": "Ruby", "bytes": "145" }, { "name": "Shell", "bytes": "4098" } ], "symlink_target": "" }
<?xml version="1.0"?> <!-- ~ Copyright 2016 Red Hat, Inc. and/or its affiliates ~ and other contributors as indicated by the @author tags. ~ ~ 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. --> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.keycloak.testsuite</groupId> <artifactId>integration-arquillian-tests-adapters-jboss</artifactId> <version>3.2.0.CR1-SNAPSHOT</version> </parent> <artifactId>integration-arquillian-tests-adapters-as7</artifactId> <name>Adapter Tests - JBoss - JBossAS 7</name> <properties> <app.server>as7</app.server> <app.server.management.protocol>remote</app.server.management.protocol> <app.server.management.port>${app.server.management.port.jmx}</app.server.management.port> <app.server.java.home>${java7.home}</app.server.java.home> <app.server.memory.settings>-Xms64m -Xmx512m -XX:MaxPermSize=256m</app.server.memory.settings> </properties> <build> <plugins> <plugin> <artifactId>maven-enforcer-plugin</artifactId> <executions> <execution> <goals> <goal>enforce</goal> </goals> <configuration> <rules> <requireProperty> <property>java7.home</property> </requireProperty> </rules> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "df3de6812e944948371ea817713a8336", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 149, "avg_line_length": 37.24242424242424, "alnum_prop": 0.5866558177379984, "repo_name": "almighty/keycloak", "id": "6d9c2344b7e7dc021b394f3172b4e8c83f41582c", "size": "2458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "testsuite/integration-arquillian/tests/other/adapters/jboss/as7/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "6208" }, { "name": "Batchfile", "bytes": "5139" }, { "name": "CSS", "bytes": "347760" }, { "name": "FreeMarker", "bytes": "84082" }, { "name": "HTML", "bytes": "692981" }, { "name": "Java", "bytes": "16629185" }, { "name": "JavaScript", "bytes": "2024159" }, { "name": "Shell", "bytes": "9502" }, { "name": "XSLT", "bytes": "72941" } ], "symlink_target": "" }
package com.ignite.webview_communicator; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import android.os.Handler; import android.util.Log; import android.webkit.JavascriptInterface; import android.webkit.WebView; /** * @version 0.1 * * Class for communicating with WebView */ public class WebViewCommunicator { /** * registeredObjects stores the mapping between the registered object and * the tags used to recognize them */ private HashMap<String, Communicator> registeredObjects; /** * webViewInstance is a reference to the webview in which the Javascript * objects we need to communicate with reside */ private WebView webViewInstance; /** * Handler is used to execute Javascript code in webview instance */ private Handler uiHandler; /** * The global Javascript object, which is used for communication between * the webview and the Java object. */ private final static String JSOBJECT = "WebViewCommunicator"; /** * In order to use WebViewCommunicator, an activity needs to initialize it * using an instance of the WebView and a Handler * * @param webView the webView instance with which the activity needs to * communicate make sure that you have executed the javascript * side of WebViewCommunicator in the webview * @param uiHandler a Handler bound to the thread on which the webView is running * This is needed to execute Javascript on WebView's thread * @see <a href="http://developer.android.com/reference/android/os/Handler.html">Handler</a> */ public WebViewCommunicator(WebView webView, Handler uiHandler) { this.webViewInstance = webView; this.uiHandler = uiHandler; this.registeredObjects = new HashMap<String, Communicator>(); webView.addJavascriptInterface(this, "_WebViewCommunicator"); } /** * Helper method to get the Javascript code to be executed in the webview * * @param tag tag of the object on which the method is to be invoked * @param method the method to invoke on object * @param args the arguments to be based when invoking the method * * @return the javascript code that will need to be executed in the * webview in the form of a string */ private String getJSCode(String tag, String method, String args) { return (JSOBJECT + ".raiseEvent('" + tag + "', '" + method + "', '" + args + "')"); } /** * Invokes method on the javascript object. * * @param tag the tag of the javascript object on which the method needs to be invoked * @param method the method to be invoked * @param args the parameters with which the method is to be invoked */ private void raiseJSEvent(String tag, String method, String args) { final String code = getJSCode(tag, method, args); uiHandler.post(new Runnable() { @Override public void run() { webViewInstance.loadUrl("javascript:" + code); } }); } /** * This method can be used by the app to invoke methods on the javascript object * the arguments should be in the form of a JSONArray. It accepts the following * parameters * * @param tag the tag of the javascript object which we wish to invoke * @param method the method to invoke * @param args the arguments to be passed to the method */ public void callJS(String tag, String method, JSONArray args) { try { String arguments = URLEncoder.encode(args.toString(), "UTF-8"); tag = URLEncoder.encode(tag, "UTF-8"); method = URLEncoder.encode(method, "UTF-8"); raiseJSEvent(tag, method, arguments); } catch (UnsupportedEncodingException e) { Log.w("URL encoding failed: ", "Check encoding"); e.printStackTrace(); } } /** * Convenient method for invoking javascript object methods without arguments * Same as calling {@link #callJS(String, String, JSONArray) callJS} with an * empty JSONArray * * @param tag the tag of the javascript object which we wish to invoke * @param method the method to invoke */ public void callJS(String tag, String method) { try { tag = URLEncoder.encode(tag, "UTF-8"); method = URLEncoder.encode(method, "UTF-8"); raiseJSEvent(tag, method, null); } catch (UnsupportedEncodingException e) { Log.w("URL encoding failed: ", "Check encoding"); e.printStackTrace(); } } /** * Allows the activity to register objects for receiving messages * from Javascript. * * The receiving object should implement the Communicator interface. * * @param tag the tag with which the receiving object will be invoked * @param client an object implementing the communicator interface * @see Communicator * * @return true if the object was successfully registered else false * is the tag is already being used */ public boolean register(String tag, Communicator client) { if(registeredObjects.containsKey(tag)) { Log.e("Duplicate tag", "An object is already registered with the given tag"); return false; } else { registeredObjects.put(tag, client); return true; } } /** * Method exposed to the javascript for invoking native java methods * It accepts the following parameters * * @param tag the tag of the object on which to invoke the method * @param method the method to invoke * @param args the arguments to be passed to the method * * @return returns false if the object is not found else it returns true */ @JavascriptInterface public boolean nativeCall(String tag, String method, String args) { // Check if the an object is registered with given tag, if we have such object // invoke its 'router' method else simply log an error message and raise return // false if(registeredObjects.containsKey(tag)) { final String TAG = tag, METHOD = method, ARGS = args; Thread mThread = new Thread(new Runnable() { @Override public void run() { try { registeredObjects.get(TAG).router(METHOD, new JSONArray(ARGS)); } catch (JSONException e) { Log.w("nativeCall","JSON Parsing failed"); e.printStackTrace(); } } }); uiHandler.post(mThread); return true; } else { String errorMsg = "Error: No object with tag '" + tag + "' registered on application"; callJS("__self", "log", new JSONArray().put(errorMsg)); return false; } } }
{ "content_hash": "79913fae98a27ecbb3fb660681d325af", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 98, "avg_line_length": 34.525510204081634, "alnum_prop": 0.6633663366336634, "repo_name": "ignitesol/androidsockets", "id": "3d7c6daadb37d143327d15f04e57d658c94eb461", "size": "6767", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/com/ignite/webview_communicator/WebViewCommunicator.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "35588" }, { "name": "JavaScript", "bytes": "7135" } ], "symlink_target": "" }
// Copyright (C) 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html #ifndef __PKG_IMP_H__ #define __PKG_IMP_H__ #include "unicode/utypes.h" #include "unicode/udata.h" /* * Read an ICU data item with any platform type, * return the pointer to the UDataInfo in its header, * and set the lengths of the UDataInfo and of the whole header. * All data remains in its platform type. */ U_CFUNC const UDataInfo * getDataInfo(const uint8_t *data, int32_t length, int32_t &infoLength, int32_t &headerLength, UErrorCode *pErrorCode); #endif
{ "content_hash": "c1c097bf2e5ae64e280c587e9f070cf9", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 64, "avg_line_length": 28.181818181818183, "alnum_prop": 0.6919354838709677, "repo_name": "hkernbach/arangodb", "id": "c9fe81bd73a20aeb479ba956911171e8cba2c398", "size": "1133", "binary": false, "copies": "6", "ref": "refs/heads/devel", "path": "3rdParty/V8/v5.7.492.77/third_party/icu/source/tools/toolutil/pkg_imp.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89079" }, { "name": "Assembly", "bytes": "391227" }, { "name": "Awk", "bytes": "7502" }, { "name": "Batchfile", "bytes": "62496" }, { "name": "C", "bytes": "9184899" }, { "name": "C#", "bytes": "96431" }, { "name": "C++", "bytes": "278343201" }, { "name": "CMake", "bytes": "664691" }, { "name": "CSS", "bytes": "650173" }, { "name": "CWeb", "bytes": "174166" }, { "name": "Cuda", "bytes": "52444" }, { "name": "DIGITAL Command Language", "bytes": "259402" }, { "name": "Emacs Lisp", "bytes": "14637" }, { "name": "Fortran", "bytes": "1856" }, { "name": "Groovy", "bytes": "51836" }, { "name": "HTML", "bytes": "2415724" }, { "name": "Java", "bytes": "1048556" }, { "name": "JavaScript", "bytes": "54219725" }, { "name": "LLVM", "bytes": "24019" }, { "name": "Lex", "bytes": "1231" }, { "name": "Lua", "bytes": "17899" }, { "name": "M4", "bytes": "658700" }, { "name": "Makefile", "bytes": "522586" }, { "name": "Max", "bytes": "36857" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "NSIS", "bytes": "42998" }, { "name": "Objective-C", "bytes": "98866" }, { "name": "Objective-C++", "bytes": "2503" }, { "name": "PHP", "bytes": "118092" }, { "name": "Pascal", "bytes": "150599" }, { "name": "Perl", "bytes": "906737" }, { "name": "Perl 6", "bytes": "25883" }, { "name": "PowerShell", "bytes": "20434" }, { "name": "Python", "bytes": "4557865" }, { "name": "QMake", "bytes": "16692" }, { "name": "R", "bytes": "5123" }, { "name": "Rebol", "bytes": "354" }, { "name": "Roff", "bytes": "1089418" }, { "name": "Ruby", "bytes": "1141022" }, { "name": "SAS", "bytes": "1847" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "508528" }, { "name": "Swift", "bytes": "116" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "32117" }, { "name": "Visual Basic", "bytes": "11568" }, { "name": "XSLT", "bytes": "567028" }, { "name": "Yacc", "bytes": "53063" } ], "symlink_target": "" }
Learning SWIFT Title: Json Request Description: A json request in Swift [Source: Developing iOS Apps Using Swift Tutorial Part 2](http://goo.gl/TzMnWe)
{ "content_hash": "b0cdcbe94b57187c3530c79478b172f1", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 79, "avg_line_length": 15.8, "alnum_prop": 0.759493670886076, "repo_name": "nguyenantinhbk77/practice-swift", "id": "b0b4a5f3b91d35b0a187605dc01e018a40b9820b", "size": "158", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Tutorials/Developing_iOS_Apps_With_Swift/lesson3/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1683" }, { "name": "Objective-C", "bytes": "263103" }, { "name": "Ruby", "bytes": "784" }, { "name": "Shell", "bytes": "4447" }, { "name": "Swift", "bytes": "1508062" } ], "symlink_target": "" }
<?php namespace Point\Framework\Http\Controllers\Master\Account; use Illuminate\Http\Request; use Point\Core\Traits\ValidationTrait; use Point\Framework\Http\Controllers\Controller; use Point\Framework\Models\AccountDepreciation; use Point\Framework\Models\Master\Coa; class AccountDepreciationController extends Controller { use ValidationTrait; /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { if (!$this->validateCSRF()) { return response()->json($this->restrictionAccessMessage()); } $response_error = array('status' => 'failed'); $response_success = array('status' => 'success'); $account_fixed_asset_id = \Input::get('fixed_asset_id'); $account_depreciation_id = \Input::get('depreciation_id'); $account_depreciation = AccountDepreciation::where('account_depreciation_id', $account_depreciation_id)->first(); if ($account_depreciation) { return response()->json($response_error); } $account_depreciation_fixed_asset = AccountDepreciation::where('account_fixed_asset_id', $account_fixed_asset_id)->first(); if (!$account_depreciation_fixed_asset) { $account_depreciation = new AccountDepreciation; $account_depreciation->account_fixed_asset_id = $account_fixed_asset_id; $account_depreciation->account_depreciation_id = $account_depreciation_id; $account_depreciation->save(); return response()->json($response_success); } $account_depreciation_fixed_asset->account_depreciation_id = $account_depreciation_id == 0 ? null : $account_depreciation_id; $account_depreciation_fixed_asset->save(); return response()->json($response_success); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show() { $view = view('framework::app.master.coa.depreciation._show'); $view->list_account_fixed_assets = Coa::joinCategory()->where('coa_category.name', 'Fixed Assets') ->where('subledger_type', 'Point\Framework\Models\FixedAsset') ->selectOriginal() ->get(); $view->list_account_depreciations = Coa::joinCategory()->where('coa_category.name', 'Fixed Assets') ->where('coa.has_subledger', 0) ->selectOriginal() ->get(); return $view; } }
{ "content_hash": "d8a09231ef1e8106b3efbe53a8c330ea", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 133, "avg_line_length": 35.06666666666667, "alnum_prop": 0.6342205323193917, "repo_name": "pringgojs/point-app-test", "id": "a7a0b36166138f719967433befc0b2f272272690", "size": "2630", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/point/point-framework/src/Http/Controllers/Master/Account/AccountDepreciationController.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "412" }, { "name": "CSS", "bytes": "917733" }, { "name": "HTML", "bytes": "6373428" }, { "name": "JavaScript", "bytes": "787585" }, { "name": "PHP", "bytes": "3421396" } ], "symlink_target": "" }
local T = {} --[[ Q.mink() alias wrapper Q.mink() : returns minimum k values of input vector 2 usages of mink(): 1)Q.mink(x, y): which returns two vectors with minimum k values from first input vector and corresponding y values from second input vector -- Input arguments: x and y are of type 'lVector' -- Returns : 2 vectors -- i) min k values from x -- ii) corresponding k values from y 2)Q.mink(x): which returns one vector with minimum k values from input vector -- Input arguments: x is of type 'lVector' -- Returns : 1 vector -- i)minimum k values from x -- ]] local function mink(x, y, optargs) local expander local op = "mink" assert(type(x) == "lVector", "val must be a lVector") if type(x) == "lVector" and type(y) == "lVector" then expander = require 'Q/OPERATORS/GETK/lua/expander_getk_reducer' elseif type(x) == "lVector" then expander = require 'Q/OPERATORS/GETK/lua/expander_getk' else assert(nil, "Invalid arguments") end local status, ret_1, ret_2 = pcall(expander, op, x, y, optargs) if ( not status ) then print(ret_1) end --print(status) assert(status, "Could not execute mink") return ret_1, ret_1 end T.mink = mink require('Q/q_export').export('mink', mink)
{ "content_hash": "c311cdbba246be695195d4439e57bdc7", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 78, "avg_line_length": 32.38095238095238, "alnum_prop": 0.6169117647058824, "repo_name": "NerdWalletOSS/Q", "id": "80922385666ecaf47a7eedbd46dc60e9e6524bfd", "size": "1360", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ALIAS/lua/mink.lua", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1528854" }, { "name": "C++", "bytes": "11900" }, { "name": "CMake", "bytes": "414" }, { "name": "CSS", "bytes": "651" }, { "name": "Cuda", "bytes": "4192" }, { "name": "HTML", "bytes": "184009" }, { "name": "JavaScript", "bytes": "12282" }, { "name": "Jupyter Notebook", "bytes": "60539" }, { "name": "Lex", "bytes": "5777" }, { "name": "Logos", "bytes": "18046" }, { "name": "Lua", "bytes": "2273456" }, { "name": "Makefile", "bytes": "72536" }, { "name": "Perl", "bytes": "3421" }, { "name": "Python", "bytes": "121910" }, { "name": "R", "bytes": "1071" }, { "name": "RPC", "bytes": "5973" }, { "name": "Shell", "bytes": "128156" }, { "name": "TeX", "bytes": "819194" }, { "name": "Terra", "bytes": "3360" }, { "name": "Vim script", "bytes": "5911" }, { "name": "Yacc", "bytes": "52645" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TSRP.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TSRP.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
{ "content_hash": "47d6e617e61ffac9396a0d07ba3cb6dc", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 170, "avg_line_length": 43.98412698412698, "alnum_prop": 0.6113316492241068, "repo_name": "TheCreatorJames/TSRP", "id": "64aa013cd21eefe7a842938c4e2aea8dfea1dc96", "size": "2773", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TSRP/Properties/Resources.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "200442" }, { "name": "Smalltalk", "bytes": "3" } ], "symlink_target": "" }
layout: page title: "Eric White" comments: true description: "blanks" keywords: "Eric White,CU,Boulder" --- <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script> <!-- <script src="../assets/js/highcharts.js"></script> --> <style type="text/css">@font-face { font-family: "Bebas Neue"; src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype"); } h1.Bebas { font-family: "Bebas Neue", Verdana, Tahoma; } </style> </head> #### TEACHING INFORMATION **College**: College of Arts and Sciences **Classes taught**: COML 5610, ENGL 2010, ENGL 2112, ENGL 3116, ENGL 4038, ENGL 4039, ENGL 4224, ENGL 5019, ENGL 5529, ENGL 5559, ENGL 7489 #### COML 5610: Introduction to Literary Theory **Terms taught**: Fall 2011 **Instructor rating**: 5.38 **Standard deviation in instructor rating**: 0.0 **Average grade** (4.0 scale): 3.98 **Standard deviation in grades** (4.0 scale): 0.0 **Average workload** (raw): 2.83 **Standard deviation in workload** (raw): 0.0 #### ENGL 2010: Introduction to Literary Theory **Terms taught**: Fall 2006, Fall 2010 **Instructor rating**: 5.31 **Standard deviation in instructor rating**: 0.06 **Average grade** (4.0 scale): 3.51 **Standard deviation in grades** (4.0 scale): 0.01 **Average workload** (raw): 2.26 **Standard deviation in workload** (raw): 0.05 #### ENGL 2112: Introduction to Literary Theory **Terms taught**: Spring 2015, Spring 2017 **Instructor rating**: 5.23 **Standard deviation in instructor rating**: 0.15 **Average grade** (4.0 scale): 3.78 **Standard deviation in grades** (4.0 scale): 0.09 **Average workload** (raw): 2.0 **Standard deviation in workload** (raw): 0.0 #### ENGL 3116: Topics in Advanced Theory **Terms taught**: Fall 2007, Spring 2010, Spring 2011, Spring 2012, Spring 2013, Spring 2017 **Instructor rating**: 5.46 **Standard deviation in instructor rating**: 0.42 **Average grade** (4.0 scale): 3.73 **Standard deviation in grades** (4.0 scale): 0.18 **Average workload** (raw): 2.75 **Standard deviation in workload** (raw): 0.25 #### ENGL 4038: Critical Thinking in English Studies **Terms taught**: Fall 2006, Spring 2008, Fall 2008, Spring 2009, Spring 2013 **Instructor rating**: 5.47 **Standard deviation in instructor rating**: 0.1 **Average grade** (4.0 scale): 3.69 **Standard deviation in grades** (4.0 scale): 0.12 **Average workload** (raw): 2.7 **Standard deviation in workload** (raw): 0.23 #### ENGL 4039: Critical Thinking in English Studies **Terms taught**: Fall 2013, Spring 2014, Spring 2015, Fall 2015, Spring 2016, Fall 2016 **Instructor rating**: 5.52 **Standard deviation in instructor rating**: 0.14 **Average grade** (4.0 scale): 3.83 **Standard deviation in grades** (4.0 scale): 0.08 **Average workload** (raw): 2.64 **Standard deviation in workload** (raw): 0.28 #### ENGL 4224: Modern British and Irish Novel **Terms taught**: Spring 2007, Fall 2007, Spring 2008, Fall 2008, Spring 2011, Fall 2013 **Instructor rating**: 5.44 **Standard deviation in instructor rating**: 0.17 **Average grade** (4.0 scale): 3.72 **Standard deviation in grades** (4.0 scale): 0.06 **Average workload** (raw): 2.78 **Standard deviation in workload** (raw): 0.13 #### ENGL 5019: Survey of Contemporary Literary and Cultural Theory **Terms taught**: Fall 2009, Fall 2011, Fall 2015 **Instructor rating**: 5.5 **Standard deviation in instructor rating**: 0.5 **Average grade** (4.0 scale): 3.96 **Standard deviation in grades** (4.0 scale): 0.06 **Average workload** (raw): 3.4 **Standard deviation in workload** (raw): 0.15 #### ENGL 5529: Studies in Special Topics **Terms taught**: Spring 2010, Spring 2012 **Instructor rating**: 5.59 **Standard deviation in instructor rating**: 0.01 **Average grade** (4.0 scale): 3.93 **Standard deviation in grades** (4.0 scale): 0.07 **Average workload** (raw): 3.87 **Standard deviation in workload** (raw): 0.27 #### ENGL 5559: TPC-PHANTAS/PSYCHIC LIFE **Terms taught**: Spring 2007 **Instructor rating**: 5.0 **Standard deviation in instructor rating**: 0.0 **Average grade** (4.0 scale): 4.0 **Standard deviation in grades** (4.0 scale): 0.0 **Average workload** (raw): 3.08 **Standard deviation in workload** (raw): 0.0 #### ENGL 7489: Advanced Special Topics **Terms taught**: Spring 2014, Fall 2016 **Instructor rating**: 5.85 **Standard deviation in instructor rating**: 0.15 **Average grade** (4.0 scale): 3.97 **Standard deviation in grades** (4.0 scale): 0.03 **Average workload** (raw): 3.86 **Standard deviation in workload** (raw): 0.26
{ "content_hash": "7f1bb8d38797ea4f1d45d797b817c4ba", "timestamp": "", "source": "github", "line_count": 202, "max_line_length": 139, "avg_line_length": 23.485148514851485, "alnum_prop": 0.6854974704890388, "repo_name": "nikhilrajaram/nikhilrajaram.github.io", "id": "5a1a58515462ca9fe039ab7b94f14676c7b2a40a", "size": "4748", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "instructors/Eric_White.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15727" }, { "name": "HTML", "bytes": "48339721" }, { "name": "Python", "bytes": "9692" }, { "name": "Ruby", "bytes": "5940" } ], "symlink_target": "" }
All about my delphi Project
{ "content_hash": "d4d01d76c7d5a9d78f5712ef483ff3f7", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 27, "avg_line_length": 28, "alnum_prop": 0.8214285714285714, "repo_name": "dhiasajanwar/delphiproject", "id": "03105b2893c8fe8a89e5cfda588e69e81516756d", "size": "44", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; if (access("/Applications/WinterBoard.app/WinterBoard.dylib", (R_OK|X_OK)) == 0) dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL); // Create folders if (![[NSFileManager defaultManager] fileExistsAtPath:kIcyCachePath] || ![[NSFileManager defaultManager] fileExistsAtPath:kIcyIndexesPath]) { NSDictionary* attrs = [NSDictionary dictionaryWithObjectsAndKeys:@"mobile", NSFileOwnerAccountName, @"mobile", NSFileGroupOwnerAccountName, nil]; [[NSFileManager defaultManager] createDirectoryAtPath:kIcyCachePath withIntermediateDirectories:YES attributes:attrs error:nil]; [[NSFileManager defaultManager] createDirectoryAtPath:kIcyIndexesPath withIntermediateDirectories:YES attributes:attrs error:nil]; } // build schema //sqlite3_enable_shared_cache(1); [[[SchemaBuilder alloc] init] release]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; }
{ "content_hash": "7fa38e963ce055f441ba4ab4e21497b9", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 147, "avg_line_length": 45.69565217391305, "alnum_prop": 0.7611798287345385, "repo_name": "slavikus/Icy", "id": "b4da1b9efb72d72dff925343de9bf719c9a92973", "size": "1260", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Sources/Misc/main.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "10859" }, { "name": "Objective-C", "bytes": "268359" } ], "symlink_target": "" }
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): Phil Schwartau <pschwartau@meer.net> * Bob Clary <bob@bclary.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var gTestfile = 'regress-167328.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 167328; var summary = 'Normal error reporting code should fill Error object properties'; var actual = ''; var expect = ''; printBugNumber(BUGNUMBER); printStatus (summary); expect = 'TypeError:53'; try { var obj = {toString: function() {return new Object();}}; var result = String(obj); actual = 'no error'; } catch(e) { actual = e.name + ':' + e.lineNumber; } reportCompare(expect, actual, summary);
{ "content_hash": "6cbd3890b406825736af92b6628ebd40", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 80, "avg_line_length": 40.166666666666664, "alnum_prop": 0.6871369294605809, "repo_name": "jubos/meguro", "id": "5e96bbcb2249bd9c712b1353050e1094efc1ed48", "size": "2410", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "deps/spidermonkey/tests/js1_5/Regress/regress-167328.js", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "4039" }, { "name": "C", "bytes": "9744445" }, { "name": "C++", "bytes": "6605756" }, { "name": "D", "bytes": "3439" }, { "name": "JavaScript", "bytes": "24155571" }, { "name": "Objective-C", "bytes": "2071" }, { "name": "Perl", "bytes": "291508" }, { "name": "Python", "bytes": "597422" }, { "name": "Shell", "bytes": "119472" } ], "symlink_target": "" }
package org.assertj.core.error; import static org.assertj.core.error.ShouldContainValue.shouldContainValue; import java.util.Set; /** * Creates an error message indicating that an assertion that verifies a map contains a values. * * @author Alexander Bischof */ public class ShouldContainValues extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldContainValues}</code>. * * @param <V> value type * @param actual the actual value in the failed assertion. * @param values the expected values. * @return the created {@code ErrorMessageFactory}. */ public static <V> ErrorMessageFactory shouldContainValues(Object actual, Set<V> values) { if (values.size() == 1) return shouldContainValue(actual, values.iterator().next()); return new ShouldContainValues(actual, values); } private <V> ShouldContainValues(Object actual, Set<V> values) { super("%nExpecting:%n <%s>%nto contain values:%n <%s>", actual, values); } }
{ "content_hash": "2c6fcf3ab3198357bdbdaf1bb36cf03e", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 95, "avg_line_length": 31.612903225806452, "alnum_prop": 0.7234693877551021, "repo_name": "ChrisA89/assertj-core", "id": "ec287b3e7bbaa104fb9c7169805d69ea2047182e", "size": "1587", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/org/assertj/core/error/ShouldContainValues.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "9353819" }, { "name": "Shell", "bytes": "40820" } ], "symlink_target": "" }
layout: page title: Archive Mountain International Award Ceremony date: 2016-05-24 author: Joan Watkins tags: weekly links, java status: published summary: Fusce sit amet semper sem. Cras nibh quam, hendrerit a. banner: images/banner/leisure-04.jpg booking: startDate: 07/14/2017 endDate: 07/16/2017 ctyhocn: AVPSCHX groupCode: AMIAC published: true --- Maecenas ac odio at dui maximus ultrices at eu leo. Duis luctus metus et dolor posuere elementum. Mauris eget vulputate justo, non ultricies diam. Maecenas vel ante erat. Integer consectetur ipsum in lorem dictum interdum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed sit amet dolor sed odio iaculis luctus sit amet nec nibh. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis vitae velit id eros rhoncus porttitor vitae vitae augue. Fusce a turpis eget risus congue ullamcorper sed vitae risus. Nulla risus urna, semper et ipsum at, interdum congue quam. Praesent eu efficitur orci, eget vulputate felis. Aenean egestas sem non ante pretium, a tincidunt lacus tincidunt. Cras suscipit ac felis sit amet laoreet. * Nam condimentum neque nec sagittis eleifend * Vivamus dictum dui vitae condimentum pretium. Integer aliquam nisl vitae risus fermentum varius. Sed in pellentesque risus. Maecenas ullamcorper feugiat pellentesque. Vestibulum et dignissim odio. Vivamus nec ante nunc. Curabitur sit amet auctor justo. Sed eget dolor sed neque pellentesque dictum. Nulla ut pharetra magna, non pellentesque ligula. In hac habitasse platea dictumst. Sed vel auctor urna, sit amet eleifend ex. Ut justo lacus, vestibulum id nibh a, scelerisque interdum justo. Aenean vehicula euismod nibh eu molestie.
{ "content_hash": "0fae076f5e3fe27d5e5724b036f2a36c", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 770, "avg_line_length": 81.76190476190476, "alnum_prop": 0.8072218986604542, "repo_name": "KlishGroup/prose-pogs", "id": "3a0c5e9a2d959e0d45524bfd31fcbcf914fb23a4", "size": "1721", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "pogs/A/AVPSCHX/AMIAC/index.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
module SolidusKlarnaPayments module AmountCalculators module Uk class ShipmentCalculator def adjust_with(shipment) yield().merge( total_tax_amount: tax_amount(shipment), tax_rate: tax_rate(shipment), unit_price: unit_price(shipment) ) end private def tax_amount(shipment) (shipment.included_tax_total * 100).to_i end def tax_rate(shipment) if shipment.included_tax_total == 0 0 elsif shipment.adjustments.tax.count == 1 (shipment.adjustments.tax.first.source.amount * 10_000).to_i else (((shipment.amount / shipment.pre_tax_amount) - 1) * 10_000).to_i end end def unit_price(shipment) shipment.display_amount.cents end end end end end
{ "content_hash": "4c3f9bcf764178a2b7d12481bdc29267", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 77, "avg_line_length": 25.34285714285714, "alnum_prop": 0.5569334836527621, "repo_name": "bitspire/solidus_klarna_payments", "id": "bf2954b5a926eb39b99fc1380a09fb2793221007", "size": "918", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/solidus_klarna_payments/amount_calculators/uk/shipment_calculator.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "15041" }, { "name": "Ruby", "bytes": "179422" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectInspectionProfilesVisibleTreeState"> <entry key="Project Default"> <profile-state> <expanded-state> <State> <id /> </State> <State> <id>Android</id> </State> <State> <id>Android Lint</id> </State> </expanded-state> <selected-state> <State> <id>Abstraction issues</id> </State> </selected-state> </profile-state> </entry> </component> <component name="ProjectLevelVcsManager" settingsEditedManually="false"> <OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Checkout" /> <OptionsSetting value="true" id="Update" /> <OptionsSetting value="true" id="Status" /> <OptionsSetting value="true" id="Edit" /> <ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Remove" /> </component> <component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" assert-keyword="true" jdk-15="true" project-jdk-name="1.8" project-jdk-type="JavaSDK"> <output url="file://$PROJECT_DIR$/build/classes" /> </component> <component name="ProjectType"> <option name="id" value="Android" /> </component> <component name="masterDetails"> <states> <state key="ProjectJDKs.UI"> <settings> <last-edited>1.8</last-edited> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> <state key="ScopeChooserConfigurable.UI"> <settings> <splitter-proportions> <option name="proportions"> <list> <option value="0.2" /> </list> </option> </splitter-proportions> </settings> </state> </states> </component> </project>
{ "content_hash": "090859761d516cc97cfc5c2e64ce067a", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 161, "avg_line_length": 31.470588235294116, "alnum_prop": 0.5509345794392523, "repo_name": "SmileLikeYe/Cornerstone", "id": "a00097441a9ed03d9f49db3645208a33500dd0ca", "size": "2140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/misc.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "52383" } ], "symlink_target": "" }
app.controller('DealersCtrl', [ '$scope', '$rootScope', 'dealerFactory', function($scope, $rootScope, dealerFactory) { $scope.dealers = dealerFactory.dealers $scope.openModal = $rootScope.openModal $scope.modalData = { form: { validated: false, fields: {} } } }])
{ "content_hash": "bae3a6fc2ac84f36949274e4b2d63132", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 45, "avg_line_length": 20.8, "alnum_prop": 0.6025641025641025, "repo_name": "jblossomweb/redcap-test", "id": "e6134df31e81fc40c35602953f90bbba084d8094", "size": "312", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/js/controllers/dealers.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "693" }, { "name": "HTML", "bytes": "8267" }, { "name": "JavaScript", "bytes": "23060" } ], "symlink_target": "" }
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2005-2011. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTERPROCESS_MAP_INDEX_HPP #define BOOST_INTERPROCESS_MAP_INDEX_HPP #include <boost/interprocess/detail/config_begin.hpp> #include <boost/interprocess/detail/workaround.hpp> #include <functional> #include <utility> #include <boost/interprocess/containers/map.hpp> #include <boost/interprocess/allocators/private_adaptive_pool.hpp> //!\file //!Describes index adaptor of boost::map container, to use it //!as name/shared memory index namespace boost { namespace interprocess { namespace ipcdetail{ //!Helper class to define typedefs from IndexTraits template <class MapConfig> struct map_index_aux { typedef typename MapConfig::key_type key_type; typedef typename MapConfig::mapped_type mapped_type; typedef std::less<key_type> key_less; typedef std::pair<const key_type, mapped_type> value_type; typedef private_adaptive_pool <value_type, typename MapConfig:: segment_manager_base> allocator_type; typedef boost::interprocess::map <key_type, mapped_type, key_less, allocator_type> index_t; }; } //namespace ipcdetail { //!Index type based in boost::interprocess::map. Just derives from boost::interprocess::map //!and defines the interface needed by managed memory segments template <class MapConfig> class map_index //Derive class from map specialization : public ipcdetail::map_index_aux<MapConfig>::index_t { /// @cond typedef ipcdetail::map_index_aux<MapConfig> index_aux; typedef typename index_aux::index_t base_type; typedef typename MapConfig:: segment_manager_base segment_manager_base; /// @endcond public: //!Constructor. Takes a pointer to the //!segment manager. Can throw map_index(segment_manager_base *segment_mngr) : base_type(typename index_aux::key_less(), segment_mngr){} //!This reserves memory to optimize the insertion of n //!elements in the index void reserve(typename segment_manager_base::size_type) { /*Does nothing, map has not reserve or rehash*/ } //!This tries to free previously allocate //!unused memory. void shrink_to_fit() { base_type::get_stored_allocator().deallocate_free_blocks(); } }; /// @cond //!Trait class to detect if an index is a node //!index. This allows more efficient operations //!when deallocating named objects. template<class MapConfig> struct is_node_index <boost::interprocess::map_index<MapConfig> > { static const bool value = true; }; /// @endcond }} //namespace boost { namespace interprocess { #include <boost/interprocess/detail/config_end.hpp> #endif //#ifndef BOOST_INTERPROCESS_MAP_INDEX_HPP
{ "content_hash": "0e0ef37ac533897e4ed605db1f851c20", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 91, "avg_line_length": 31.85, "alnum_prop": 0.6590266875981162, "repo_name": "djsedulous/namecoind", "id": "1bfc7ce31052afac78d7c001eb4aefa90fe08dbc", "size": "3185", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "libs/boost_1_50_0/boost/interprocess/indexes/map_index.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "843598" }, { "name": "Awk", "bytes": "90447" }, { "name": "C", "bytes": "19896147" }, { "name": "C#", "bytes": "121901" }, { "name": "C++", "bytes": "132199970" }, { "name": "CSS", "bytes": "336528" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "IDL", "bytes": "11976" }, { "name": "Java", "bytes": "3955488" }, { "name": "JavaScript", "bytes": "22346" }, { "name": "Max", "bytes": "36857" }, { "name": "Objective-C", "bytes": "23505" }, { "name": "Objective-C++", "bytes": "2450" }, { "name": "PHP", "bytes": "55712" }, { "name": "Perl", "bytes": "4194947" }, { "name": "Python", "bytes": "761429" }, { "name": "R", "bytes": "4009" }, { "name": "Rebol", "bytes": "354" }, { "name": "Scheme", "bytes": "6073" }, { "name": "Shell", "bytes": "550004" }, { "name": "Tcl", "bytes": "2268735" }, { "name": "TeX", "bytes": "13404" }, { "name": "TypeScript", "bytes": "5318296" }, { "name": "XSLT", "bytes": "757548" }, { "name": "eC", "bytes": "5079" } ], "symlink_target": "" }
/** * Functions to create and operate on complete systems. * * @module System/System */ import * as CPU from './CPU'; import * as RAM from './RAM'; import * as Printer from './Printer'; /** * A system in a virgin state. * * @typedef {Object} System * @property {CPU} cpu - CPU device * @property {RAM} ram - RAM device * @property {Printer} printer - Printer device * @property {Number} cycle - Current cycle number */ /** * A generic device. * * @typedef {Object} Device */ /** * Specification for a system bus. * * This bus specifies the order of creation and execution of devices in the * system, and which lines will be synchronized between devices after each * device has cycled. * * @typedef {Array} Bus * @property {String} Bus[].id - ID of device in the bus * @property {Module} Bus[].device - Module of device to instantiate * @property {Array} Bus[].lines - Synchronization lines to other devices */ export const Bus = [{ id: 'cpu', device: CPU, lines: { ram: ['read', 'write', 'ar', 'dr'], printer: ['output', 'or'], }, }, { id: 'ram', device: RAM, lines: { cpu: ['dr'], }, }, { id: 'printer', device: Printer, lines: {}, }]; /** * Create a system in a virgin state. * * @method create * @returns {System} */ export function create() { const system = { cycle: 0, }; for (const {id, device} of Bus) { system[id] = device.create(); } return system; } /** * Executes one system cycle by cycling devices, and returning the * new state. * * @param {System} state * @returns {System} */ export function cycle(state) { state = { ...state, cycle: state.cycle + 1, }; for (const {id, device, lines} of Bus) { state[id] = device.cycle(state[id]); for (const [target, mapping] of Object.entries(lines)) { for (const line of mapping) { state[target][line] = state[id][line]; } } } return state; } /** * Returns an overview of the state of a System as text. * * @param {System} state * @returns {String} */ export function toString(state) { return `${state.cycle}${Bus.map( ({id, device}) => `\t\t${device.toString(state[id])}\n` )}`; }
{ "content_hash": "90b13c9d868933f17929d9e5d8b08bcb", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 77, "avg_line_length": 19.693693693693692, "alnum_prop": 0.6093321134492223, "repo_name": "zenoamaro/chip3", "id": "c4ab0abd5573a482ea735a116586e89bef07c3fb", "size": "2186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/System/System.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2644" }, { "name": "JavaScript", "bytes": "50360" }, { "name": "Makefile", "bytes": "1386" } ], "symlink_target": "" }
package com.intellij.codeInspection.dataFlow.value; import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiType; import org.jetbrains.annotations.NotNull; /** * Used in DFA-aware completion only */ public class DfaInstanceofValue extends DfaValue { private final @NotNull PsiExpression myExpression; private final @NotNull PsiType myCastType; private final @NotNull DfaCondition myRelation; public DfaInstanceofValue(@NotNull DfaValueFactory factory, @NotNull PsiExpression expression, @NotNull PsiType castType, @NotNull DfaCondition relation) { super(factory); myExpression = expression; myCastType = castType; myRelation = relation; } @NotNull public DfaCondition getRelation() { return myRelation; } @NotNull public PsiExpression getExpression() { return myExpression; } @NotNull public PsiType getCastType() { return myCastType; } }
{ "content_hash": "565769697a63c070403ea2ba7f30d32b", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 62, "avg_line_length": 24.975, "alnum_prop": 0.6926926926926927, "repo_name": "leafclick/intellij-community", "id": "ba6c45fcfb435f4c475852ae1a074ff5da593149", "size": "1599", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaInstanceofValue.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package br.usp.poli.magnodb.model.dao; import br.usp.poli.magnodb.model.Produto; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; public abstract class DBConnector { private DataSource dataSource; private Connection connection; public void create(DataSource dataSource) throws NamingException { this.dataSource = dataSource; } protected void connect() throws SQLException { connection = dataSource.getConnection(); } protected DataSource getDataSource() { return dataSource; } protected Connection getConnection() { return connection; } }
{ "content_hash": "f33b387e1c6a955010a441b17932a163", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 70, "avg_line_length": 21.12121212121212, "alnum_prop": 0.7187948350071736, "repo_name": "gustavotorresm/PCS-3623", "id": "4ad283689d94811d5390f14862939db4e41e3697", "size": "697", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/br/usp/poli/magnodb/model/dao/DBConnector.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "224" }, { "name": "Java", "bytes": "91131" } ], "symlink_target": "" }
ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
{ "content_hash": "bd8f133ca2aeaf1b27ecc3300a73af7e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 23, "avg_line_length": 9.076923076923077, "alnum_prop": 0.6779661016949152, "repo_name": "mdoering/backbone", "id": "bb68a8599e9681ec6f9d5a1785195e73e768a71e", "size": "179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Teucrium/Teucrium leucocladum/Teucrium leucocladum leucocladum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.wikipedia.feed.random; import android.support.annotation.NonNull; import org.wikipedia.Site; import org.wikipedia.feed.model.Card; public class RandomCard extends Card { @NonNull private Site site; public RandomCard(@NonNull Site site) { this.site = site; } @Override @NonNull public String title() { return ""; } public Site site() { return site; } }
{ "content_hash": "c7911cdfa422d346b50b2598b478b61e", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 43, "avg_line_length": 17.916666666666668, "alnum_prop": 0.6465116279069767, "repo_name": "Duct-and-rice/KrswtkhrWiki4Android", "id": "0c7d4a933ae1792313ecdf8d5725c197d56ed203", "size": "430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/org/wikipedia/feed/random/RandomCard.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "64439" }, { "name": "HTML", "bytes": "2719" }, { "name": "Java", "bytes": "1864273" }, { "name": "JavaScript", "bytes": "128269" }, { "name": "Python", "bytes": "22963" }, { "name": "Shell", "bytes": "3434" } ], "symlink_target": "" }
""" #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# This file is part of the Smart Developer Hub Project: http://www.smartdeveloperhub.org Center for Open Middleware http://www.centeropenmiddleware.com/ #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# Copyright (C) 2015 Center for Open Middleware. #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=# """ import pkg_resources try: pkg_resources.declare_namespace(__name__) except ImportError: import pkgutil __path__ = pkgutil.extend_path(__path__, __name__)
{ "content_hash": "681b744e1504bbb22b4e8355d5e78198", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 76, "avg_line_length": 39.0625, "alnum_prop": 0.5504, "repo_name": "fserena/agora-stoa", "id": "d71f6eb331207dfd73ad38852a6539904bc22a2d", "size": "1250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "agora/stoa/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "121135" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.3/phpunit.xsd" backupGlobals="false" colors="true" bootstrap="tests/bootstrap.php" > <testsuites> <testsuite name="Hypixel-PHP Test"> <directory>./tests/</directory> </testsuite> </testsuites> </phpunit>
{ "content_hash": "d86ee4ddee1a7e4346b325314c5a098a", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 80, "avg_line_length": 27.625, "alnum_prop": 0.6131221719457014, "repo_name": "Plancke/hypixel-php", "id": "c79352173aa1720ffd0c0a8c3af24594bef78bb6", "size": "442", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "phpunit.xml", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "397072" } ], "symlink_target": "" }
<!DOCTYPE html> <html class="minimal"> <title>Canvas test: 2d.composite.transparent.xor</title> <script src="../tests.js"></script> <link rel="stylesheet" href="../tests.css"> <link rel="prev" href="minimal.2d.composite.transparent.destination-atop.html" title="2d.composite.transparent.destination-atop"> <link rel="next" href="minimal.2d.composite.transparent.copy.html" title="2d.composite.transparent.copy"> <body> <p id="passtext">Pass</p> <p id="failtext">Fail</p> <!-- TODO: handle "script did not run" case --> <p class="output">These images should be identical:</p> <canvas id="c" class="output" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas> <p class="output expectedtext">Expected output:<p><img src="2d.composite.transparent.xor.png" class="output expected" id="expected" alt=""> <ul id="d"></ul> <script> _addTest(function(canvas, ctx) { ctx.fillStyle = 'rgba(0, 255, 0, 0.5)'; ctx.fillRect(0, 0, 100, 50); ctx.globalCompositeOperation = 'xor'; ctx.fillStyle = 'rgba(0, 0, 255, 0.75)'; ctx.fillRect(0, 0, 100, 50); _assertPixelApprox(canvas, 50,25, 0,63,191,127, "50,25", "0,63,191,127", 5); }); </script>
{ "content_hash": "da95a445ecb7027759b27de2ea8edcd2", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 139, "avg_line_length": 38.6, "alnum_prop": 0.694300518134715, "repo_name": "SunboX/SVG-to-GLSL-Converter", "id": "ae79519ef5d9137dd965dfc0ab55b9dddcbada5e", "size": "1158", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "lib/webgl-2d/test/philip.html5.org/tests/minimal.2d.composite.transparent.xor.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "124980" } ], "symlink_target": "" }
//---------------------------------------------------------------------------- /** @file GoSearch.h Class GoSearch extends SgSearch */ //---------------------------------------------------------------------------- #ifndef GO_SEARCH_H #define GO_SEARCH_H #include "../smartgame/SgSearch.h" class GoBoard; //---------------------------------------------------------------------------- /** Go search. Defines EndOfGame to return true after two passes. */ class GoSearch : public SgSearch { public: GoSearch(GoBoard& board, SgSearchHashTable* hash); GoBoard& Board(); const GoBoard& Board() const; /** Return false, because some Go searches require it. @todo Remove. Implement it in the subclasses, because it depends on the move generation there. */ bool CheckDepthLimitReached() const; bool EndOfGame() const; /** Default implementation of SgSearch::Execute() for Go searches. Executes the move is legal. */ bool Execute(SgMove move, int* delta, int depth); /** Default implementation of SgSearch::GetHashCode() for Go searches. @return Board().GetHashCodeInclToPlay(). */ SgHashCode GetHashCode() const; /** Default implementation of SgSearch::ToPlay() for Go searches. @return Board().ToPlay(). */ SgBlackWhite GetToPlay() const; void SetToPlay(SgBlackWhite toPlay); std::string MoveString(SgMove move) const; /** Default implementation of SgSearch::TakeBack() for Go searches. Takes back the move on the board. */ void TakeBack(); private: GoBoard& m_board; }; inline GoBoard& GoSearch::Board() { return m_board; } inline const GoBoard& GoSearch::Board() const { return m_board; } //---------------------------------------------------------------------------- #endif // GO_SEARCH_H
{ "content_hash": "4e314310ae96f9d36846e4b618b3aaf3", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 78, "avg_line_length": 26.271428571428572, "alnum_prop": 0.5562805872756933, "repo_name": "cbordeman/gameofgo", "id": "89352e45bfcb32fddff915905209afed332e1e48", "size": "1839", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FuegoUniversalComponent/fuego/go/GoSearch.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1561" }, { "name": "C", "bytes": "185564" }, { "name": "C#", "bytes": "571008" }, { "name": "C++", "bytes": "114101755" }, { "name": "M4", "bytes": "9738" }, { "name": "Perl", "bytes": "6080" }, { "name": "Shell", "bytes": "728" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>全国资源城市分类</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="favicon.ico" href="favicon.ico" type="image/x-icon"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--引入EXT API和关键CSS,其中custom.css是自定义CSS-----> <script type="text/javascript" src="../lib/ext/ext-all.js"></script> <link rel="stylesheet" href="../lib/ext/resources/css/custom.css"/> <link rel="stylesheet" href="../lib/leaflet/leaflet.css"/> <!--[if lte IE 8]> <link rel="stylesheet" href="../lib/leaflet/leaflet.ie.css"/><![endif]--> <link rel="stylesheet" href="../lib/leaflet/plugin/MarkerCluster/MarkerCluster.css"/> <link rel="stylesheet" href="../lib/leaflet/plugin/MarkerCluster/MarkerCluster.Default.css"/> <!--[if lte IE 8]> <link rel="stylesheet" href="../dist/MarkerCluster.Default.ie.css"/><![endif]--> <link rel="stylesheet" href="../lib/leaflet/plugin/esri/demo.css"/> <!--引入leaflet的API-----> <script src="../lib/leaflet/leaflet-0.6.2-src.js"></script> <script src="../lib/leaflet/plugin/MarkerCluster/leaflet.markercluster-src.js"></script> <script type="text/javascript" src="../lib/heatmap/QuadTree.js"></script> <script type="text/javascript" src="../lib/heatmap/heatmap.js"></script> <script type="text/javascript" src="../lib/heatmap/heatmap-leaflet.js"></script> <script src="../lib/leaflet/plugin/awesome/leaflet.awesome-markers.min.js"></script> <link rel="stylesheet" href="../lib/leaflet/plugin/awesome/leaflet.awesome-markers.css"/> <link rel="stylesheet" href="../lib/leaflet/plugin/awesome/css/font-awesome.min.css"/> <script src="../data/resourcecity.geojson"></script> <style> body { margin: 0; padding: 0; } #map { position: absolute; top: 0; left: 0; right: 0; bottom: 0; height: 100%; } </style> </head> <body> <div id='map'></div> <script> map = L.map('map').setView([30.0, 110.0], 4); var markers = L.markerClusterGroup({ spiderfyOnMaxZoom: false, disableClusteringAtZoom: 12, polygonOptions: { color: "#2d84c8", weight: 4, opacity: 1, fillOpacity: 0.5 }, //设置不同层级圆环的样式,它是根据数字位数来确定css的 iconCreateFunction: function (cluster) { // get the number of items in the cluster var count = cluster.getChildCount(); var digits = (count + "").length; return new L.DivIcon({ html: count, className: "cluster digits-" + digits, iconSize: null }); } }); // Add a CloudMade tile layer with style #999 var herenormalchn = L.tileLayer('http://1.maps.nlp.nokia.com.cn/maptile/2.1/maptile/933ee1206a/normal.day/{z}/{x}/{y}/256/png8?lg=CHI&app_id=90oGXsXHT8IRMSt5D79X&token=JY0BReev8ax1gIrHZZoqIg&xnlp=CL_JSMv2.5.3.2', { attribution: 'Map &copy; Certain data &copy; <a href="http://openstreetmap.org">HERE</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>' }); herenormalchn.addTo(map); var respText = rescourcecity; var heatmapLayer = L.TileLayer.heatMap({ radius: 6, // radius could be absolute or relative // absolute: radius in meters, relative: radius in pixels //radius: { value: 15000, absolute: true }, opacity: 0.8, gradient: { 0.35: "rgb(255,0,255)", 0.45: "rgb(0,0,255)", 0.55: "rgb(0,255,255)", 0.65: "rgb(0,255,0)", 0.95: "yellow", 1.0: "rgb(255,0,0)" } }); // 点聚类 var ms = []; var heatms = [] var colors = ['red', 'blue', 'green', 'purple', 'orange', 'darkred', 'darkblue', 'darkgreen', 'cadetblue', 'darkpurple']; var awesomeIcons = ['font', 'cloud-download', 'medkit', 'github-alt', 'coffee', 'food', 'bell-alt', 'question-sign', 'star']; for (var i = 0; i < respText.features.length; i++) { var a = respText.features[i]; var color = colors[a['properties']['type']]; var awesomeIcon = awesomeIcons[a['properties']['type']]; var m = new L.Marker(new L.LatLng(a['geometry']['coordinates'][1], a['geometry']['coordinates'][0]), { value: 1, title: 'ss', icon: L.AwesomeMarkers.icon({ icon: awesomeIcon, color: color }) }); var popupText = "<div>城市名称:" + a['properties']['city'] + "<br>类型:" + a['properties']['type'] + "</div>"; m.bindPopup(popupText); ms.push(m); var hm = {'lat': a['geometry']['coordinates'][1], 'lng': a['geometry']['coordinates'][0], value: 1} heatms.push(hm); } markers.addLayers(ms); heatmapLayer.addData(heatms); heatmapLayer.addTo(map); map.addLayer(markers); </script> </body> </html>
{ "content_hash": "b31718d39d357f8a2abc5a6173f946ca", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 218, "avg_line_length": 40.1640625, "alnum_prop": 0.574596382026843, "repo_name": "ludwiyk/ludwiyk.github.io", "id": "0a3559d871267273cb157dfe8c29329cb019de78", "size": "5253", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webcontent/CityResource.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "42112" }, { "name": "JavaScript", "bytes": "6784945" } ], "symlink_target": "" }
[![Build Status](https://travis-ci.org/ontop/ontop.png?branch=develop)](https://travis-ci.org/ontop/ontop) [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/ontop/ontop/trend.png)](https://bitdeli.com/free "Bitdeli Badge") Ontop ================== Ontop is a framework for ontology based data access (OBDA). It supports SPARQL over virtual RDF graphs defined through mappings to RDBMS. Licensing terms -------------------- The -ontop- framework is available under the Apache License, Version 2.0 All documentation is licensed under the [Creative Commons](http://creativecommons.org/licenses/by/4.0/) (attribute) license. Compiling, packing, testing, etc. -------------------- The project is a [Maven](http://maven.apache.org/) project. Compiling, running the unit tests, building the release binaries all can be done using maven. To make it more practical we created several .sh scripts that you can run on any unix environment that has maven installed. The scripts are located in the folder 'scripts', look at that folder for more information. Currently we use Maven 3 and Java 7 to build the project. Code organization -------------------- The code is organized in several submodules as follows: // TODO - extend this section of the readme Links -------------------- official website and documentations: http://ontop.inf.unibz.it/ Google Group: https://groups.google.com/forum/#!forum/ontop4obda Blog: http://ontop-obda.blogspot.it/ Source Code: https://github.com/ontop/ontop Issue Tracker: https://github.com/ontop/ontop/issues Wiki: https://github.com/ontop/ontop/wiki
{ "content_hash": "a18f7abf24340dcee7d893c36e0a9a06", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 368, "avg_line_length": 33.416666666666664, "alnum_prop": 0.7219451371571073, "repo_name": "clarkparsia/ontop", "id": "57bbb644b1eaef6a56e76c1aad2c6d561885affa", "size": "1604", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2676" }, { "name": "GAP", "bytes": "65836" }, { "name": "Java", "bytes": "4772137" }, { "name": "Ruby", "bytes": "52622" }, { "name": "Shell", "bytes": "16320" }, { "name": "TeX", "bytes": "10376" } ], "symlink_target": "" }
(function() { require(['codemirror', 'codemirrorxml', 'codemirrorjavascript', 'codemirrorcss', 'codemirrorcs', 'codemirrorclike', 'codemirrorfolding'], function(CodeMirror) { return CodeMirror; }); }).call(this);
{ "content_hash": "aa7dceaf484428dcbc2fa8194d2e0f29", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 162, "avg_line_length": 31.857142857142858, "alnum_prop": 0.7040358744394619, "repo_name": "ToJans/Big", "id": "9685a9bb15ff1cdf51c9cf9b9019a0f1a2349b41", "size": "223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Editor/scripts/utils/codeMirrorWrapper.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "13040" }, { "name": "Erlang", "bytes": "7216" }, { "name": "JavaScript", "bytes": "6731" }, { "name": "Shell", "bytes": "107" } ], "symlink_target": "" }
const $ = require('jquery'); const jQuery = $; const PIXI = require('pixi.js'); const p2 = require('p2'); const marked = require('marked'); const video = require('video.js'); const howler = require('howler'); require('./game'); require('./jquery.fullpage'); require('./sketch'); $(document).ready(function () { $("#pong-game-canvas").PongGame(); $(".markdown").each(function () { $(this).html(marked($(this).text())); }); $(".canvas-view").each(function(id) { let $elem = $(this); let idS = `drawing_${id}`; let container = document.createElement("div"); $(container).addClass("w3-row"); $.each(['#f00', '#ff0', '#0f0', '#0ff', '#00f', '#f0f', '#000', '#fff'], function() { let link = document.createElement("a"); link.href = `#${idS}`; link.setAttribute('data-color', this); $(link).addClass("w3-col s1"); let color = document.createElement("div"); color.style = `width: 100%; height: 100%; background: ${this}`; $(color).addClass("w3-border w3-hover-opacity"); $(link).append(color); $(container).append(link); }); $(container).append("<div class='w3-rest'></div>"); ['brush', 'eraser'].map(elem => { let link = document.createElement("a"); link.href = `#${idS}`; link.setAttribute('data-tool', elem); link.style = "width: 45px"; $(link).addClass("w3-col w3-right"); $(link).append(`<img class='w3-image w3-opacity w3-hover-opacity-off' src='./img/rendered/${elem}.png'>`); $(container).append(link); }); { let link = document.createElement("a"); link.href = `#${idS}`; link.setAttribute('data-download', 'pngp'); link.style = "width: 45px"; $(link).addClass("w3-col w3-right"); $(link).append(`<img class='w3-image w3-opacity w3-hover-opacity-off' src='./img/rendered/save.png'>`) $(container).append(link); } $elem.append(container); let canvas = document.createElement("canvas"); $(canvas).addClass("w3-border"); $(canvas).attr('id', idS); $elem.append(canvas); $(`#drawing_${id}`).sketch(); }); $("#main-container").fullpage({ verticalCentered: true, loopBottom : false, sectionSelector : ".fp-section", navigation : true, paddingBottom : "100px", fixedElements : "#background", afterLoad : onLoad, onLeave : onLeave }); $("#buttonNext").click(() => { $.fn.fullpage.moveSectionDown(); }); $("#buttonPrev").click(() => { $.fn.fullpage.moveSectionUp(); }); $("#buttonStart").click(function () { $.fn.fullpage.moveTo(1); }); let active = true; let sounds = {}; $("#buttonSound").click(function () { active = $(this).data("active"); this.src = "img/rendered/" + (active ? "sound.png" : "sound_off.png"); $(this).data("active", !active); howler.Howler.mute(!active); }); ['challenge', 'game', 'text', 'draw'].map(elem => { sounds[elem] = new howler.Howl({ src : [`audio/${elem}.mp3`], loop : true, onfade: function () { if (this.volume() === 0) this.pause(); } }); }); function onLoad() { let type = $(this).data('type'); if (!active || !type) return; console.log("Entering:", type); sounds[type].play(); sounds[type].fade(0, 1, 500); } function onLeave() { let type = $(this).data('type'); if (!active || !type) return; console.log("Leaving:", type); sounds[type].fade(1, 0, 500); } });
{ "content_hash": "452240808e38040e43872b8512c16adb", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 118, "avg_line_length": 30.66417910447761, "alnum_prop": 0.4779751764419567, "repo_name": "jmigual/5book", "id": "c2387b7ce155a617bc5ad03e45859168bdeca87d", "size": "4109", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/pigs_book/js/pigs_book.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "135306" }, { "name": "HTML", "bytes": "18604" }, { "name": "JavaScript", "bytes": "223841" } ], "symlink_target": "" }
sendMessage = function(message){ validateMessage(message); //Check if message is for a room if(message.room && !message.receiver){ message.type = "ROOM_MESSAGE"; var usersInRoom = RoomUsers.find({"room": message.room}).fetch(); var peerIds = []; _.each(usersInRoom, function(userInRoom){ if(userInRoom !== Meteor.user().username){ var user = Meteor.users.findOne({"username": userInRoom.username}); if(user){ var peerId = user.peerId; if(peerId) peerIds.push(peerId); } } }); _.each(peerIds, function(peerId){ var conn = peer.connect(peerId); conn.on('open', function() { // Send messages conn.send(EJSON.stringify(message)); console.log("Sent message to peerId: "+peerId); }); }); } //Check if private message else if(!message.room && message.receiver){ message.type = "PRIVATE_MESSAGE"; var user = Meteor.users.findOne({"username": message.receiver}); var peerId; if(user) peerId = user.peerId; if(peerId){ var conn = peer.connect(peerId); conn.on('open', function() { // Send messages conn.send(EJSON.stringify(message)); console.log("Sent message to peerId: "+peerId); }); } } Messages.insert(message); } //Message receiver initPeerMessageListener = function(){ peer.on('connection', Meteor.bindEnvironment(function(conn) { console.log("Received entering connection"); // Receive messages conn.on('data', function(data) { console.log("Received entering data: "+data); data = EJSON.parse(data); if(data.type == "PRIVATE_MESSAGE" || data.type == "ROOM_MESSAGE"){ var message = data; validateMessage(message); message.isRead = false; Messages.insert(message); alertNewMessage(message); } }); })); } var alertNewMessage = function(message){ //Check if private message if(message.type == "PRIVATE_MESSAGE"){ Notifications.insert({type: message.type, username: message.user, message: message.content}); } //Check if message is for a room else if(message.type == "ROOM_MESSAGE"){ Notifications.insert({type: message.type, username: message.user, room: message.room, message: message.content}); } }
{ "content_hash": "6650c5c8625dcd237d9ea5f7d087bcd8", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 115, "avg_line_length": 27.743589743589745, "alnum_prop": 0.6682070240295749, "repo_name": "sorensenlars0128/MeteorChatApp", "id": "0647f1121e1c649c60e2d2e739a7d777f54d07f5", "size": "2164", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "client/MessageManager.js", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1841" }, { "name": "HTML", "bytes": "9066" }, { "name": "JavaScript", "bytes": "24830" } ], "symlink_target": "" }
package org.onosproject.net.flow.criteria; import org.onosproject.net.PortNumber; import java.util.Objects; /** * Implementation of input port criterion. */ public final class PortCriterion implements Criterion { private final PortNumber port; private final Type type; /** * Constructor. * * @param port the input port number to match * @param type the match type. Should be either Type.IN_PORT or * Type.IN_PHY_PORT */ PortCriterion(PortNumber port, Type type) { this.port = port; this.type = type; } @Override public Type type() { return this.type; } /** * Gets the input port number to match. * * @return the input port number to match */ public PortNumber port() { return this.port; } @Override public String toString() { return type().toString() + SEPARATOR + port; } @Override public int hashCode() { return Objects.hash(type().ordinal(), port); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof PortCriterion) { PortCriterion that = (PortCriterion) obj; return Objects.equals(port, that.port) && Objects.equals(this.type(), that.type()); } return false; } }
{ "content_hash": "f929297e8d5ebf21d130b36235301223", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 67, "avg_line_length": 22.253968253968253, "alnum_prop": 0.5813124108416547, "repo_name": "oplinkoms/onos", "id": "af0673b7ffe03acc36a3b81fbc3b156846e4cfb1", "size": "2019", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "core/api/src/main/java/org/onosproject/net/flow/criteria/PortCriterion.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "364443" }, { "name": "Dockerfile", "bytes": "2443" }, { "name": "HTML", "bytes": "319812" }, { "name": "Java", "bytes": "46767333" }, { "name": "JavaScript", "bytes": "4022973" }, { "name": "Makefile", "bytes": "1658" }, { "name": "P4", "bytes": "171319" }, { "name": "Python", "bytes": "977954" }, { "name": "Ruby", "bytes": "8615" }, { "name": "Shell", "bytes": "336303" }, { "name": "TypeScript", "bytes": "894995" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_listen_socket_51b.c Label Definition File: CWE680_Integer_Overflow_to_Buffer_Overflow__malloc.label.xml Template File: sources-sink-51b.tmpl.c */ /* * @description * CWE: 680 Integer Overflow to Buffer Overflow * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Small number greater than zero that will not cause an integer overflow in the sink * Sink: * BadSink : Attempt to allocate array using length value from source * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files * * */ #include "std_testcase.h" #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define LISTEN_BACKLOG 5 #define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) /* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ #ifndef OMITBAD void CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_listen_socket_51b_badSink(int data) { { size_t i; int *intPointer; /* POTENTIAL FLAW: if data * sizeof(int) > SIZE_MAX, overflows to a small value * so that the for loop doing the initialization causes a buffer overflow */ intPointer = (int*)malloc(data * sizeof(int)); for (i = 0; i < (size_t)data; i++) { intPointer[i] = 0; /* Potentially writes beyond the boundary of intPointer */ } printIntLine(intPointer[0]); free(intPointer); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_listen_socket_51b_goodG2BSink(int data) { { size_t i; int *intPointer; /* POTENTIAL FLAW: if data * sizeof(int) > SIZE_MAX, overflows to a small value * so that the for loop doing the initialization causes a buffer overflow */ intPointer = (int*)malloc(data * sizeof(int)); for (i = 0; i < (size_t)data; i++) { intPointer[i] = 0; /* Potentially writes beyond the boundary of intPointer */ } printIntLine(intPointer[0]); free(intPointer); } } #endif /* OMITGOOD */
{ "content_hash": "0c095e438476200f311d1cb42b6b6288", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 112, "avg_line_length": 32.42857142857143, "alnum_prop": 0.6552863436123348, "repo_name": "maurer/tiamat", "id": "1b3580b405ba760bc83e6aa6fc6b3df1f386df30", "size": "2724", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/Juliet/testcases/CWE680_Integer_Overflow_to_Buffer_Overflow/CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_listen_socket_51b.c", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php declare(strict_types = 1); namespace SlevomatCodingStandard\Sniffs\Functions; use SlevomatCodingStandard\Sniffs\TestCase; class DisallowTrailingCommaInClosureUseSniffTest extends TestCase { public function testNoErrors(): void { $report = self::checkFile(__DIR__ . '/data/disallowTrailingCommaInClosureUseNoErrors.php', [ 'onlySingleLine' => false, ]); self::assertNoSniffErrorInFile($report); } public function testErrors(): void { $report = self::checkFile(__DIR__ . '/data/disallowTrailingCommaInClosureUseErrors.php', [ 'onlySingleLine' => false, ]); self::assertSame(2, $report->getErrorCount()); self::assertSniffError($report, 5, DisallowTrailingCommaInClosureUseSniff::CODE_DISALLOWED_TRAILING_COMMA); self::assertSniffError($report, 10, DisallowTrailingCommaInClosureUseSniff::CODE_DISALLOWED_TRAILING_COMMA); self::assertAllFixedInFile($report); } public function testErrorsWithOnlySingleLineEnabled(): void { $report = self::checkFile(__DIR__ . '/data/disallowTrailingCommaInClosureUseWithOnlySingleLineEnabledErrors.php', [ 'onlySingleLine' => true, ]); self::assertSame(1, $report->getErrorCount()); self::assertSniffError($report, 10, DisallowTrailingCommaInClosureUseSniff::CODE_DISALLOWED_TRAILING_COMMA); self::assertAllFixedInFile($report); } }
{ "content_hash": "e6c42d831c50cb057d1defa85e5d43ad", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 117, "avg_line_length": 29.511111111111113, "alnum_prop": 0.7582831325301205, "repo_name": "slevomat/coding-standard", "id": "6681a696d30a0bb00fc6dc67bbacf0f6d1ebac0e", "size": "1328", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Sniffs/Functions/DisallowTrailingCommaInClosureUseSniffTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "2196122" } ], "symlink_target": "" }
package mqtt import ( "os" "testing" "time" "github.com/brocaar/chirpstack-api/go/v3/gw" "github.com/gofrs/uuid" paho "github.com/eclipse/paho.mqtt.golang" log "github.com/sirupsen/logrus" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/brocaar/chirpstack-gateway-bridge/internal/config" "github.com/brocaar/lorawan" ) type MQTTBackendTestSuite struct { suite.Suite mqttClient paho.Client backend *Backend gatewayID lorawan.EUI64 } func (ts *MQTTBackendTestSuite) SetupSuite() { assert := require.New(ts.T()) log.SetLevel(log.ErrorLevel) server := "tcp://127.0.0.1:1883/1" var username string var password string if v := os.Getenv("TEST_MQTT_SERVER"); v != "" { server = v } if v := os.Getenv("TEST_MQTT_USERNAME"); v != "" { username = v } if v := os.Getenv("TEST_MQTT_PASSWORD"); v != "" { password = v } opts := paho.NewClientOptions().AddBroker(server).SetUsername(username).SetPassword(password) ts.mqttClient = paho.NewClient(opts) token := ts.mqttClient.Connect() token.Wait() assert.NoError(token.Error()) ts.gatewayID = lorawan.EUI64{8, 7, 6, 5, 4, 3, 2, 1} var conf config.Config conf.Integration.Marshaler = "json" conf.Integration.MQTT.EventTopicTemplate = "gateway/{{ .GatewayID }}/event/{{ .EventType }}" conf.Integration.MQTT.CommandTopicTemplate = "gateway/{{ .GatewayID }}/command/#" conf.Integration.MQTT.Auth.Type = "generic" conf.Integration.MQTT.Auth.Generic.Servers = []string{server} conf.Integration.MQTT.Auth.Generic.Username = username conf.Integration.MQTT.Auth.Generic.Password = password conf.Integration.MQTT.Auth.Generic.CleanSession = true var err error ts.backend, err = NewBackend(conf) assert.NoError(err) assert.NoError(ts.backend.Start()) assert.NoError(ts.backend.SetGatewaySubscription(true, ts.gatewayID)) time.Sleep(100 * time.Millisecond) } func (ts *MQTTBackendTestSuite) TearDownSuite() { ts.mqttClient.Disconnect(0) ts.backend.Stop() } func (ts *MQTTBackendTestSuite) TestSubscribeGateway() { assert := require.New(ts.T()) gatewayID := lorawan.EUI64{1, 2, 3, 4, 5, 6, 7, 8} assert.NoError(ts.backend.SetGatewaySubscription(true, gatewayID)) _, ok := ts.backend.gateways[gatewayID] assert.True(ok) ts.T().Run("Unsubscribe", func(t *testing.T) { assert := require.New(t) assert.NoError(ts.backend.SetGatewaySubscription(false, gatewayID)) _, ok := ts.backend.gateways[gatewayID] assert.False(ok) }) } func (ts *MQTTBackendTestSuite) TestPublishUplinkFrame() { assert := require.New(ts.T()) id, err := uuid.NewV4() assert.NoError(err) uplink := gw.UplinkFrame{ PhyPayload: []byte{1, 2, 3, 4}, RxInfo: &gw.UplinkRXInfo{ UplinkId: id[:], }, } uplinkFrameChan := make(chan gw.UplinkFrame) token := ts.mqttClient.Subscribe("gateway/+/event/up", 0, func(c paho.Client, msg paho.Message) { var pl gw.UplinkFrame assert.NoError(ts.backend.unmarshal(msg.Payload(), &pl)) uplinkFrameChan <- pl }) token.Wait() assert.NoError(token.Error()) assert.NoError(ts.backend.PublishEvent(ts.gatewayID, "up", id, &uplink)) uplinkReceived := <-uplinkFrameChan assert.Equal(uplink, uplinkReceived) } func (ts *MQTTBackendTestSuite) TestGatewayStats() { assert := require.New(ts.T()) id, err := uuid.NewV4() assert.NoError(err) stats := gw.GatewayStats{ GatewayId: ts.gatewayID[:], StatsId: id[:], } statsChan := make(chan gw.GatewayStats) token := ts.mqttClient.Subscribe("gateway/+/event/stats", 0, func(c paho.Client, msg paho.Message) { var pl gw.GatewayStats assert.NoError(ts.backend.unmarshal(msg.Payload(), &pl)) statsChan <- stats }) token.Wait() assert.NoError(token.Error()) assert.NoError(ts.backend.PublishEvent(ts.gatewayID, "stats", id, &stats)) statsReceived := <-statsChan assert.Equal(stats, statsReceived) } func (ts *MQTTBackendTestSuite) TestPublishDownlinkTXAck() { assert := require.New(ts.T()) id, err := uuid.NewV4() assert.NoError(err) txAck := gw.DownlinkTXAck{ GatewayId: ts.gatewayID[:], Token: 1234, DownlinkId: id[:], Items: []*gw.DownlinkTXAckItem{ { Status: gw.TxAckStatus_OK, }, }, } txAckChan := make(chan gw.DownlinkTXAck) token := ts.mqttClient.Subscribe("gateway/+/event/ack", 0, func(c paho.Client, msg paho.Message) { var pl gw.DownlinkTXAck assert.NoError(ts.backend.unmarshal(msg.Payload(), &pl)) txAckChan <- pl }) token.Wait() assert.NoError(token.Error()) assert.NoError(ts.backend.PublishEvent(ts.gatewayID, "ack", id, &txAck)) txAckReceived := <-txAckChan assert.Equal(txAck, txAckReceived) } func (ts *MQTTBackendTestSuite) TestDownlinkFrameHandler() { assert := require.New(ts.T()) downlinkFrameChan := make(chan gw.DownlinkFrame, 1) ts.backend.SetDownlinkFrameFunc(func(pl gw.DownlinkFrame) { downlinkFrameChan <- pl }) downlink := gw.DownlinkFrame{ Items: []*gw.DownlinkFrameItem{ { PhyPayload: []byte{1, 2, 3, 4}, }, }, } b, err := ts.backend.marshal(&downlink) assert.NoError(err) token := ts.mqttClient.Publish("gateway/0807060504030201/command/down", 0, false, b) token.Wait() assert.NoError(token.Error()) receivedDownlink := <-downlinkFrameChan assert.Equal(downlink, receivedDownlink) } func (ts *MQTTBackendTestSuite) TestGatewayConfigHandler() { assert := require.New(ts.T()) gatewayConfigurationChan := make(chan gw.GatewayConfiguration, 1) ts.backend.SetGatewayConfigurationFunc(func(pl gw.GatewayConfiguration) { gatewayConfigurationChan <- pl }) config := gw.GatewayConfiguration{ GatewayId: ts.gatewayID[:], Version: "123", } b, err := ts.backend.marshal(&config) assert.NoError(err) token := ts.mqttClient.Publish("gateway/0807060504030201/command/config", 0, false, b) token.Wait() assert.NoError(token.Error()) receivedConfig := <-gatewayConfigurationChan assert.Equal(config, receivedConfig) } func (ts *MQTTBackendTestSuite) TestGatewayCommandExecRequest() { assert := require.New(ts.T()) gatewayComandExecRequestChan := make(chan gw.GatewayCommandExecRequest, 1) ts.backend.SetGatewayCommandExecRequestFunc(func(pl gw.GatewayCommandExecRequest) { gatewayComandExecRequestChan <- pl }) id, err := uuid.NewV4() assert.NoError(err) execReq := gw.GatewayCommandExecRequest{ GatewayId: ts.gatewayID[:], ExecId: id[:], Command: "reboot", Environment: map[string]string{ "FOO": "bar", }, } b, err := ts.backend.marshal(&execReq) assert.NoError(err) token := ts.mqttClient.Publish("gateway/0807060504030201/command/exec", 0, false, b) token.Wait() assert.NoError(token.Error()) receivedExecReq := <-gatewayComandExecRequestChan assert.Equal(execReq, receivedExecReq) } func (ts *MQTTBackendTestSuite) TestRawPacketForwarderCommand() { assert := require.New(ts.T()) rawPacketForwarderCommandChan := make(chan gw.RawPacketForwarderCommand, 1) ts.backend.SetRawPacketForwarderCommandFunc(func(pl gw.RawPacketForwarderCommand) { rawPacketForwarderCommandChan <- pl }) id, err := uuid.NewV4() assert.NoError(err) pl := gw.RawPacketForwarderCommand{ GatewayId: ts.gatewayID[:], RawId: id[:], Payload: []byte{0x01, 0x02, 0x03, 0x04}, } b, err := ts.backend.marshal(&pl) assert.NoError(err) token := ts.mqttClient.Publish("gateway/0807060504030201/command/raw", 0, false, b) token.Wait() assert.NoError(token.Error()) received := <-rawPacketForwarderCommandChan assert.Equal(pl, received) } func TestMQTTBackend(t *testing.T) { suite.Run(t, new(MQTTBackendTestSuite)) }
{ "content_hash": "52db91533dc5fe078eb4c798d9acce70", "timestamp": "", "source": "github", "line_count": 284, "max_line_length": 101, "avg_line_length": 26.496478873239436, "alnum_prop": 0.7169435215946844, "repo_name": "brocaar/lora-gateway-bridge", "id": "5a6b8c8cd1e8e6ef2428dd633b815981021f4a8b", "size": "7525", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "internal/integration/mqtt/backend_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "539" }, { "name": "Go", "bytes": "305318" }, { "name": "Makefile", "bytes": "1071" }, { "name": "Shell", "bytes": "4521" } ], "symlink_target": "" }
package com.amazonaws.services.wellarchitected.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.wellarchitected.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ConflictException JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ConflictExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller { private ConflictExceptionUnmarshaller() { super(com.amazonaws.services.wellarchitected.model.ConflictException.class, "ConflictException"); } @Override public com.amazonaws.services.wellarchitected.model.ConflictException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception { com.amazonaws.services.wellarchitected.model.ConflictException conflictException = new com.amazonaws.services.wellarchitected.model.ConflictException( null); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("ResourceId", targetDepth)) { context.nextToken(); conflictException.setResourceId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ResourceType", targetDepth)) { context.nextToken(); conflictException.setResourceType(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return conflictException; } private static ConflictExceptionUnmarshaller instance; public static ConflictExceptionUnmarshaller getInstance() { if (instance == null) instance = new ConflictExceptionUnmarshaller(); return instance; } }
{ "content_hash": "b4186b96df00ec7c4c1b5cb294d38b5f", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 158, "avg_line_length": 38.59154929577465, "alnum_prop": 0.6572992700729927, "repo_name": "aws/aws-sdk-java", "id": "b2e449f2364d65d45da53c876e4187a398dcbb8e", "size": "3320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-wellarchitected/src/main/java/com/amazonaws/services/wellarchitected/model/transform/ConflictExceptionUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// Copyright (c) 2001-2021 Aspose Pty Ltd. All Rights Reserved. // // This file is part of Aspose.Words. The source code in this file // is only intended as a supplement to the documentation, and is provided // "as is", without warranty of any kind, either expressed or implied. ////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using System.Globalization; using System.IO; using Aspose.Words; using Aspose.Words.Fonts; using Aspose.Words.Saving; using Aspose.Words.Settings; using NUnit.Framework; using ColorMode = Aspose.Words.Saving.ColorMode; using Document = Aspose.Words.Document; using IWarningCallback = Aspose.Words.IWarningCallback; using PdfSaveOptions = Aspose.Words.Saving.PdfSaveOptions; using SaveFormat = Aspose.Words.SaveFormat; using SaveOptions = Aspose.Words.Saving.SaveOptions; using WarningInfo = Aspose.Words.WarningInfo; using WarningType = Aspose.Words.WarningType; using Image = #if NET462 || JAVA System.Drawing.Image; #elif NETCOREAPP2_1 || __MOBILE__ SkiaSharp.SKBitmap; using SkiaSharp; #endif #if NET462 || NETCOREAPP2_1 || JAVA using Aspose.Pdf; using Aspose.Pdf.Annotations; using Aspose.Pdf.Facades; using Aspose.Pdf.Forms; using Aspose.Pdf.Operators; using Aspose.Pdf.Text; #endif namespace ApiExamples { [TestFixture] internal class ExPdfSaveOptions : ApiExampleBase { [Test] public void OnePage() { //ExStart //ExFor:FixedPageSaveOptions.PageSet //ExFor:Document.Save(Stream, SaveOptions) //ExSummary:Shows how to convert only some of the pages in a document to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Page 1."); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Page 2."); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Page 3."); using (Stream stream = File.Create(ArtifactsDir + "PdfSaveOptions.OnePage.pdf")) { // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "PageIndex" to "1" to render a portion of the document starting from the second page. options.PageSet = new PageSet(1); // This document will contain one page starting from page two, which will only contain the second page. doc.Save(stream, options); } //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.OnePage.pdf"); Assert.AreEqual(1, pdfDocument.Pages.Count); TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages.Accept(textFragmentAbsorber); Assert.AreEqual("Page 2.", textFragmentAbsorber.Text); #endif } [Test] public void HeadingsOutlineLevels() { //ExStart //ExFor:ParagraphFormat.IsHeading //ExFor:PdfSaveOptions.OutlineOptions //ExFor:PdfSaveOptions.SaveFormat //ExSummary:Shows how to limit the headings' level that will appear in the outline of a saved PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert headings that can serve as TOC entries of levels 1, 2, and then 3. builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1; Assert.True(builder.ParagraphFormat.IsHeading); builder.Writeln("Heading 1"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2; builder.Writeln("Heading 1.1"); builder.Writeln("Heading 1.2"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3; builder.Writeln("Heading 1.2.1"); builder.Writeln("Heading 1.2.2"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); saveOptions.SaveFormat = SaveFormat.Pdf; // The output PDF document will contain an outline, which is a table of contents that lists headings in the document body. // Clicking on an entry in this outline will take us to the location of its respective heading. // Set the "HeadingsOutlineLevels" property to "2" to exclude all headings whose levels are above 2 from the outline. // The last two headings we have inserted above will not appear. saveOptions.OutlineOptions.HeadingsOutlineLevels = 2; doc.Save(ArtifactsDir + "PdfSaveOptions.HeadingsOutlineLevels.pdf", saveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA PdfBookmarkEditor bookmarkEditor = new PdfBookmarkEditor(); bookmarkEditor.BindPdf(ArtifactsDir + "PdfSaveOptions.HeadingsOutlineLevels.pdf"); Bookmarks bookmarks = bookmarkEditor.ExtractBookmarks(); Assert.AreEqual(3, bookmarks.Count); #endif } [TestCase(false)] [TestCase(true)] public void CreateMissingOutlineLevels(bool createMissingOutlineLevels) { //ExStart //ExFor:OutlineOptions.CreateMissingOutlineLevels //ExFor:PdfSaveOptions.OutlineOptions //ExSummary:Shows how to work with outline levels that do not contain any corresponding headings when saving a PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert headings that can serve as TOC entries of levels 1 and 5. builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1; Assert.True(builder.ParagraphFormat.IsHeading); builder.Writeln("Heading 1"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading5; builder.Writeln("Heading 1.1.1.1.1"); builder.Writeln("Heading 1.1.1.1.2"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // The output PDF document will contain an outline, which is a table of contents that lists headings in the document body. // Clicking on an entry in this outline will take us to the location of its respective heading. // Set the "HeadingsOutlineLevels" property to "5" to include all headings of levels 5 and below in the outline. saveOptions.OutlineOptions.HeadingsOutlineLevels = 5; // This document contains headings of levels 1 and 5, and no headings with levels of 2, 3, and 4. // The output PDF document will treat outline levels 2, 3, and 4 as "missing". // Set the "CreateMissingOutlineLevels" property to "true" to include all missing levels in the outline, // leaving blank outline entries since there are no usable headings. // Set the "CreateMissingOutlineLevels" property to "false" to ignore missing outline levels, // and treat the outline level 5 headings as level 2. saveOptions.OutlineOptions.CreateMissingOutlineLevels = createMissingOutlineLevels; doc.Save(ArtifactsDir + "PdfSaveOptions.CreateMissingOutlineLevels.pdf", saveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA PdfBookmarkEditor bookmarkEditor = new PdfBookmarkEditor(); bookmarkEditor.BindPdf(ArtifactsDir + "PdfSaveOptions.CreateMissingOutlineLevels.pdf"); Bookmarks bookmarks = bookmarkEditor.ExtractBookmarks(); Assert.AreEqual(createMissingOutlineLevels ? 6 : 3, bookmarks.Count); #endif } [TestCase(false)] [TestCase(true)] public void TableHeadingOutlines(bool createOutlinesForHeadingsInTables) { //ExStart //ExFor:OutlineOptions.CreateOutlinesForHeadingsInTables //ExSummary:Shows how to create PDF document outline entries for headings inside tables. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Create a table with three rows. The first row, // whose text we will format in a heading-type style, will serve as the column header. builder.StartTable(); builder.InsertCell(); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1; builder.Write("Customers"); builder.EndRow(); builder.InsertCell(); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Normal; builder.Write("John Doe"); builder.EndRow(); builder.InsertCell(); builder.Write("Jane Doe"); builder.EndTable(); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); // The output PDF document will contain an outline, which is a table of contents that lists headings in the document body. // Clicking on an entry in this outline will take us to the location of its respective heading. // Set the "HeadingsOutlineLevels" property to "1" to get the outline // to only register headings with heading levels that are no larger than 1. pdfSaveOptions.OutlineOptions.HeadingsOutlineLevels = 1; // Set the "CreateOutlinesForHeadingsInTables" property to "false" to exclude all headings within tables, // such as the one we have created above from the outline. // Set the "CreateOutlinesForHeadingsInTables" property to "true" to include all headings within tables // in the outline, provided that they have a heading level that is no larger than the value of the "HeadingsOutlineLevels" property. pdfSaveOptions.OutlineOptions.CreateOutlinesForHeadingsInTables = createOutlinesForHeadingsInTables; doc.Save(ArtifactsDir + "PdfSaveOptions.TableHeadingOutlines.pdf", pdfSaveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDoc = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.TableHeadingOutlines.pdf"); if (createOutlinesForHeadingsInTables) { Assert.AreEqual(1, pdfDoc.Outlines.Count); Assert.AreEqual("Customers", pdfDoc.Outlines[1].Title); } else Assert.AreEqual(0, pdfDoc.Outlines.Count); TableAbsorber tableAbsorber = new TableAbsorber(); tableAbsorber.Visit(pdfDoc.Pages[1]); Assert.AreEqual("Customers", tableAbsorber.TableList[0].RowList[0].CellList[0].TextFragments[1].Text); Assert.AreEqual("John Doe", tableAbsorber.TableList[0].RowList[1].CellList[0].TextFragments[1].Text); Assert.AreEqual("Jane Doe", tableAbsorber.TableList[0].RowList[2].CellList[0].TextFragments[1].Text); #endif } [Test] public void ExpandedOutlineLevels() { //ExStart //ExFor:Document.Save(String, SaveOptions) //ExFor:PdfSaveOptions //ExFor:OutlineOptions.HeadingsOutlineLevels //ExFor:OutlineOptions.ExpandedOutlineLevels //ExSummary:Shows how to convert a whole document to PDF with three levels in the document outline. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert headings of levels 1 to 5. builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1; Assert.True(builder.ParagraphFormat.IsHeading); builder.Writeln("Heading 1"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2; builder.Writeln("Heading 1.1"); builder.Writeln("Heading 1.2"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3; builder.Writeln("Heading 1.2.1"); builder.Writeln("Heading 1.2.2"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading4; builder.Writeln("Heading 1.2.2.1"); builder.Writeln("Heading 1.2.2.2"); builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading5; builder.Writeln("Heading 1.2.2.2.1"); builder.Writeln("Heading 1.2.2.2.2"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // The output PDF document will contain an outline, which is a table of contents that lists headings in the document body. // Clicking on an entry in this outline will take us to the location of its respective heading. // Set the "HeadingsOutlineLevels" property to "4" to exclude all headings whose levels are above 4 from the outline. options.OutlineOptions.HeadingsOutlineLevels = 4; // If an outline entry has subsequent entries of a higher level inbetween itself and the next entry of the same or lower level, // an arrow will appear to the left of the entry. This entry is the "owner" of several such "sub-entries". // In our document, the outline entries from the 5th heading level are sub-entries of the second 4th level outline entry, // the 4th and 5th heading level entries are sub-entries of the second 3rd level entry, and so on. // In the outline, we can click on the arrow of the "owner" entry to collapse/expand all its sub-entries. // Set the "ExpandedOutlineLevels" property to "2" to automatically expand all heading level 2 and lower outline entries // and collapse all level and 3 and higher entries when we open the document. options.OutlineOptions.ExpandedOutlineLevels = 2; doc.Save(ArtifactsDir + "PdfSaveOptions.ExpandedOutlineLevels.pdf", options); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ExpandedOutlineLevels.pdf"); Assert.AreEqual(1, pdfDocument.Outlines.Count); Assert.AreEqual(5, pdfDocument.Outlines.VisibleCount); Assert.True(pdfDocument.Outlines[1].Open); Assert.AreEqual(1, pdfDocument.Outlines[1].Level); Assert.False(pdfDocument.Outlines[1][1].Open); Assert.AreEqual(2, pdfDocument.Outlines[1][1].Level); Assert.True(pdfDocument.Outlines[1][2].Open); Assert.AreEqual(2, pdfDocument.Outlines[1][2].Level); #endif } [TestCase(false)] [TestCase(true)] public void UpdateFields(bool updateFields) { //ExStart //ExFor:PdfSaveOptions.Clone //ExFor:SaveOptions.UpdateFields //ExSummary:Shows how to update all the fields in a document immediately before saving it to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert text with PAGE and NUMPAGES fields. These fields do not display the correct value in real time. // We will need to manually update them using updating methods such as "Field.Update()", and "Document.UpdateFields()" // each time we need them to display accurate values. builder.Write("Page "); builder.InsertField("PAGE", ""); builder.Write(" of "); builder.InsertField("NUMPAGES", ""); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Hello World!"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "UpdateFields" property to "false" to not update all the fields in a document right before a save operation. // This is the preferable option if we know that all our fields will be up to date before saving. // Set the "UpdateFields" property to "true" to iterate through all the document // fields and update them before we save it as a PDF. This will make sure that all the fields will display // the most accurate values in the PDF. options.UpdateFields = updateFields; // We can clone PdfSaveOptions objects. Assert.AreNotSame(options, options.Clone()); doc.Save(ArtifactsDir + "PdfSaveOptions.UpdateFields.pdf", options); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.UpdateFields.pdf"); TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages.Accept(textFragmentAbsorber); Assert.AreEqual(updateFields ? "Page 1 of 2" : "Page of ", textFragmentAbsorber.TextFragments[1].Text); #endif } [TestCase(false)] [TestCase(true)] public void PreserveFormFields(bool preserveFormFields) { //ExStart //ExFor:PdfSaveOptions.PreserveFormFields //ExSummary:Shows how to save a document to the PDF format using the Save method and the PdfSaveOptions class. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Write("Please select a fruit: "); // Insert a combo box which will allow a user to choose an option from a collection of strings. builder.InsertComboBox("MyComboBox", new[] { "Apple", "Banana", "Cherry" }, 0); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions pdfOptions = new PdfSaveOptions(); // Set the "PreserveFormFields" property to "true" to save form fields as interactive objects in the output PDF. // Set the "PreserveFormFields" property to "false" to freeze all form fields in the document at // their current values and display them as plain text in the output PDF. pdfOptions.PreserveFormFields = preserveFormFields; doc.Save(ArtifactsDir + "PdfSaveOptions.PreserveFormFields.pdf", pdfOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PreserveFormFields.pdf"); Assert.AreEqual(1, pdfDocument.Pages.Count); TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages.Accept(textFragmentAbsorber); if (preserveFormFields) { Assert.AreEqual("Please select a fruit: ", textFragmentAbsorber.Text); TestUtil.FileContainsString("10 0 obj\r\n" + "<</Type /Annot/Subtype /Widget/P 4 0 R/FT /Ch/F 4/Rect [168.39199829 707.35101318 217.87442017 722.64007568]/Ff 131072/T(þÿ\0M\0y\0C\0o\0m\0b\0o\0B\0o\0x)/Opt " + "[(þÿ\0A\0p\0p\0l\0e) (þÿ\0B\0a\0n\0a\0n\0a) (þÿ\0C\0h\0e\0r\0r\0y) ]/V(þÿ\0A\0p\0p\0l\0e)/DA(0 g /FAAABC 12 Tf )/AP<</N 11 0 R>>>>", ArtifactsDir + "PdfSaveOptions.PreserveFormFields.pdf"); Aspose.Pdf.Forms.Form form = pdfDocument.Form; Assert.AreEqual(1, pdfDocument.Form.Count); ComboBoxField field = (ComboBoxField)form.Fields[0]; Assert.AreEqual("MyComboBox", field.FullName); Assert.AreEqual(3, field.Options.Count); Assert.AreEqual("Apple", field.Value); } else { Assert.AreEqual("Please select a fruit: Apple", textFragmentAbsorber.Text); Assert.Throws<AssertionException>(() => { TestUtil.FileContainsString("/Widget", ArtifactsDir + "PdfSaveOptions.PreserveFormFields.pdf"); }); Assert.AreEqual(0, pdfDocument.Form.Count); } #endif } [TestCase(PdfCompliance.PdfA1b)] [TestCase(PdfCompliance.Pdf17)] [TestCase(PdfCompliance.PdfA1a)] public void Compliance(PdfCompliance pdfCompliance) { //ExStart //ExFor:PdfSaveOptions.Compliance //ExFor:PdfCompliance //ExSummary:Shows how to set the PDF standards compliance level of saved PDF documents. Document doc = new Document(MyDir + "Images.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "Compliance" property to "PdfCompliance.PdfA1b" to comply with the "PDF/A-1b" standard, // which aims to preserve the visual appearance of the document as Aspose.Words convert it to PDF. // Set the "Compliance" property to "PdfCompliance.Pdf17" to comply with the "1.7" standard. // Set the "Compliance" property to "PdfCompliance.PdfA1a" to comply with the "PDF/A-1a" standard, // which complies with "PDF/A-1b" as well as preserving the document structure of the original document. // This helps with making documents searchable but may significantly increase the size of already large documents. saveOptions.Compliance = pdfCompliance; doc.Save(ArtifactsDir + "PdfSaveOptions.Compliance.pdf", saveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.Compliance.pdf"); switch (pdfCompliance) { case PdfCompliance.Pdf17: Assert.AreEqual(PdfFormat.v_1_7, pdfDocument.PdfFormat); Assert.AreEqual("1.7", pdfDocument.Version); break; case PdfCompliance.PdfA1a: Assert.AreEqual(PdfFormat.PDF_A_1A, pdfDocument.PdfFormat); Assert.AreEqual("1.4", pdfDocument.Version); break; case PdfCompliance.PdfA1b: Assert.AreEqual(PdfFormat.PDF_A_1B, pdfDocument.PdfFormat); Assert.AreEqual("1.4", pdfDocument.Version); break; } #endif } [TestCase(PdfTextCompression.None)] [TestCase(PdfTextCompression.Flate)] public void TextCompression(PdfTextCompression pdfTextCompression) { //ExStart //ExFor:PdfSaveOptions //ExFor:PdfSaveOptions.TextCompression //ExFor:PdfTextCompression //ExSummary:Shows how to apply text compression when saving a document to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); for (int i = 0; i < 100; i++) builder.Writeln("Lorem ipsum dolor sit amet, consectetur adipiscing elit, " + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "TextCompression" property to "PdfTextCompression.None" to not apply any // compression to text when we save the document to PDF. // Set the "TextCompression" property to "PdfTextCompression.Flate" to apply ZIP compression // to text when we save the document to PDF. The larger the document, the bigger the impact that this will have. options.TextCompression = pdfTextCompression; doc.Save(ArtifactsDir + "PdfSaveOptions.TextCompression.pdf", options); //ExEnd switch (pdfTextCompression) { case PdfTextCompression.None: Assert.That(60000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.TextCompression.pdf").Length)); TestUtil.FileContainsString("5 0 obj\r\n<</Length 9 0 R>>stream", ArtifactsDir + "PdfSaveOptions.TextCompression.pdf"); break; case PdfTextCompression.Flate: Assert.That(30000, Is.AtLeast(new FileInfo(ArtifactsDir + "PdfSaveOptions.TextCompression.pdf").Length)); TestUtil.FileContainsString("5 0 obj\r\n<</Length 9 0 R/Filter /FlateDecode>>stream", ArtifactsDir + "PdfSaveOptions.TextCompression.pdf"); break; } } [TestCase(PdfImageCompression.Auto)] [TestCase(PdfImageCompression.Jpeg)] public void ImageCompression(PdfImageCompression pdfImageCompression) { //ExStart //ExFor:PdfSaveOptions.ImageCompression //ExFor:PdfSaveOptions.JpegQuality //ExFor:PdfImageCompression //ExSummary:Shows how to specify a compression type for all images in a document that we are converting to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Jpeg image:"); builder.InsertImage(ImageDir + "Logo.jpg"); builder.InsertParagraph(); builder.Writeln("Png image:"); builder.InsertImage(ImageDir + "Transparent background logo.png"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); // Set the "ImageCompression" property to "PdfImageCompression.Auto" to use the // "ImageCompression" property to control the quality of the Jpeg images that end up in the output PDF. // Set the "ImageCompression" property to "PdfImageCompression.Jpeg" to use the // "ImageCompression" property to control the quality of all images that end up in the output PDF. pdfSaveOptions.ImageCompression = pdfImageCompression; // Set the "JpegQuality" property to "10" to strengthen compression at the cost of image quality. pdfSaveOptions.JpegQuality = 10; doc.Save(ArtifactsDir + "PdfSaveOptions.ImageCompression.pdf", pdfSaveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ImageCompression.pdf"); Stream pdfDocImageStream = pdfDocument.Pages[1].Resources.Images[1].ToStream(); using (pdfDocImageStream) { TestUtil.VerifyImage(400, 400, pdfDocImageStream); } pdfDocImageStream = pdfDocument.Pages[1].Resources.Images[2].ToStream(); using (pdfDocImageStream) { switch (pdfImageCompression) { case PdfImageCompression.Auto: Assert.That(50000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.ImageCompression.pdf").Length)); #if NET462 Assert.Throws<ArgumentException>(() => { TestUtil.VerifyImage(400, 400, pdfDocImageStream); }); #elif NETCOREAPP2_1 Assert.Throws<NullReferenceException>(() => { TestUtil.VerifyImage(400, 400, pdfDocImageStream); }); #endif break; case PdfImageCompression.Jpeg: Assert.That(42000, Is.AtLeast(new FileInfo(ArtifactsDir + "PdfSaveOptions.ImageCompression.pdf").Length)); TestUtil.VerifyImage(400, 400, pdfDocImageStream); break; } } #endif } [TestCase(PdfImageColorSpaceExportMode.Auto)] [TestCase(PdfImageColorSpaceExportMode.SimpleCmyk)] public void ImageColorSpaceExportMode(PdfImageColorSpaceExportMode pdfImageColorSpaceExportMode) { //ExStart //ExFor:PdfImageColorSpaceExportMode //ExFor:PdfSaveOptions.ImageColorSpaceExportMode //ExSummary:Shows how to set a different color space for images in a document as we export it to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Jpeg image:"); builder.InsertImage(ImageDir + "Logo.jpg"); builder.InsertParagraph(); builder.Writeln("Png image:"); builder.InsertImage(ImageDir + "Transparent background logo.png"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); // Set the "ImageColorSpaceExportMode" property to "PdfImageColorSpaceExportMode.Auto" to get Aspose.Words to // automatically select the color space for images in the document that it converts to PDF. // In most cases, the color space will be RGB. // Set the "ImageColorSpaceExportMode" property to "PdfImageColorSpaceExportMode.SimpleCmyk" // to use the CMYK color space for all images in the saved PDF. // Aspose.Words will also apply Flate compression to all images and ignore the "ImageCompression" property's value. pdfSaveOptions.ImageColorSpaceExportMode = pdfImageColorSpaceExportMode; doc.Save(ArtifactsDir + "PdfSaveOptions.ImageColorSpaceExportMode.pdf", pdfSaveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ImageColorSpaceExportMode.pdf"); XImage pdfDocImage = pdfDocument.Pages[1].Resources.Images[1]; switch (pdfImageColorSpaceExportMode) { case PdfImageColorSpaceExportMode.Auto: Assert.That(20000, Is.LessThan(pdfDocImage.ToStream().Length)); break; case PdfImageColorSpaceExportMode.SimpleCmyk: Assert.That(100000, Is.LessThan(pdfDocImage.ToStream().Length)); break; } Assert.AreEqual(400, pdfDocImage.Width); Assert.AreEqual(400, pdfDocImage.Height); Assert.AreEqual(ColorType.Rgb, pdfDocImage.GetColorType()); pdfDocImage = pdfDocument.Pages[1].Resources.Images[2]; switch (pdfImageColorSpaceExportMode) { case PdfImageColorSpaceExportMode.Auto: Assert.That(25000, Is.AtLeast(pdfDocImage.ToStream().Length)); break; case PdfImageColorSpaceExportMode.SimpleCmyk: Assert.That(18000, Is.LessThan(pdfDocImage.ToStream().Length)); break; } Assert.AreEqual(400, pdfDocImage.Width); Assert.AreEqual(400, pdfDocImage.Height); Assert.AreEqual(ColorType.Rgb, pdfDocImage.GetColorType()); #endif } [Test] public void DownsampleOptions() { //ExStart //ExFor:DownsampleOptions //ExFor:DownsampleOptions.DownsampleImages //ExFor:DownsampleOptions.Resolution //ExFor:DownsampleOptions.ResolutionThreshold //ExFor:PdfSaveOptions.DownsampleOptions //ExSummary:Shows how to change the resolution of images in the PDF document. Document doc = new Document(MyDir + "Images.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // By default, Aspose.Words downsample all images in a document that we save to PDF to 220 ppi. Assert.True(options.DownsampleOptions.DownsampleImages); Assert.AreEqual(220, options.DownsampleOptions.Resolution); Assert.AreEqual(0, options.DownsampleOptions.ResolutionThreshold); doc.Save(ArtifactsDir + "PdfSaveOptions.DownsampleOptions.Default.pdf", options); // Set the "Resolution" property to "36" to downsample all images to 36 ppi. options.DownsampleOptions.Resolution = 36; // Set the "ResolutionThreshold" property to only apply the downsampling to // images with a resolution that is above 128 ppi. options.DownsampleOptions.ResolutionThreshold = 128; // Only the first two images from the document will be downsampled at this stage. doc.Save(ArtifactsDir + "PdfSaveOptions.DownsampleOptions.LowerResolution.pdf", options); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.DownsampleOptions.Default.pdf"); XImage pdfDocImage = pdfDocument.Pages[1].Resources.Images[1]; Assert.That(300000, Is.LessThan(pdfDocImage.ToStream().Length)); Assert.AreEqual(ColorType.Rgb, pdfDocImage.GetColorType()); #endif } [TestCase(ColorMode.Grayscale)] [TestCase(ColorMode.Normal)] public void ColorRendering(ColorMode colorMode) { //ExStart //ExFor:PdfSaveOptions //ExFor:ColorMode //ExFor:FixedPageSaveOptions.ColorMode //ExSummary:Shows how to change image color with saving options property. Document doc = new Document(MyDir + "Images.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. // Set the "ColorMode" property to "Grayscale" to render all images from the document in black and white. // The size of the output document may be larger with this setting. // Set the "ColorMode" property to "Normal" to render all images in color. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions { ColorMode = colorMode }; doc.Save(ArtifactsDir + "PdfSaveOptions.ColorRendering.pdf", pdfSaveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ColorRendering.pdf"); XImage pdfDocImage = pdfDocument.Pages[1].Resources.Images[1]; switch (colorMode) { case ColorMode.Normal: Assert.That(300000, Is.LessThan(pdfDocImage.ToStream().Length)); Assert.AreEqual(ColorType.Rgb, pdfDocImage.GetColorType()); break; case ColorMode.Grayscale: Assert.That(1000000, Is.LessThan(pdfDocImage.ToStream().Length)); Assert.AreEqual(ColorType.Grayscale, pdfDocImage.GetColorType()); break; } #endif } [TestCase(false)] [TestCase(true)] public void DocTitle(bool displayDocTitle) { //ExStart //ExFor:PdfSaveOptions.DisplayDocTitle //ExSummary:Shows how to display the title of the document as the title bar. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Hello world!"); doc.BuiltInDocumentProperties.Title = "Windows bar pdf title"; // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. // Set the "DisplayDocTitle" to "true" to get some PDF readers, such as Adobe Acrobat Pro, // to display the value of the document's "Title" built-in property in the tab that belongs to this document. // Set the "DisplayDocTitle" to "false" to get such readers to display the document's filename. PdfSaveOptions pdfSaveOptions = new PdfSaveOptions { DisplayDocTitle = displayDocTitle }; doc.Save(ArtifactsDir + "PdfSaveOptions.DocTitle.pdf", pdfSaveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.DocTitle.pdf"); Assert.AreEqual(displayDocTitle, pdfDocument.DisplayDocTitle); Assert.AreEqual("Windows bar pdf title", pdfDocument.Info.Title); #endif } [TestCase(false)] [TestCase(true)] public void MemoryOptimization(bool memoryOptimization) { //ExStart //ExFor:SaveOptions.CreateSaveOptions(SaveFormat) //ExFor:SaveOptions.MemoryOptimization //ExSummary:Shows an option to optimize memory consumption when rendering large documents to PDF. Document doc = new Document(MyDir + "Rendering.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. SaveOptions saveOptions = SaveOptions.CreateSaveOptions(SaveFormat.Pdf); // Set the "MemoryOptimization" property to "true" to lower the memory footprint of large documents' saving operations // at the cost of increasing the duration of the operation. // Set the "MemoryOptimization" property to "false" to save the document as a PDF normally. saveOptions.MemoryOptimization = memoryOptimization; doc.Save(ArtifactsDir + "PdfSaveOptions.MemoryOptimization.pdf", saveOptions); //ExEnd } [TestCase(@"https://www.google.com/search?q= aspose", "https://www.google.com/search?q=%20aspose", true)] [TestCase(@"https://www.google.com/search?q=%20aspose", "https://www.google.com/search?q=%20aspose", true)] [TestCase(@"https://www.google.com/search?q= aspose", "https://www.google.com/search?q= aspose", false)] [TestCase(@"https://www.google.com/search?q=%20aspose", "https://www.google.com/search?q=%20aspose", false)] public void EscapeUri(string uri, string result, bool isEscaped) { //ExStart //ExFor:PdfSaveOptions.EscapeUri //ExSummary:Shows how to escape hyperlinks in the document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.InsertHyperlink("Testlink", uri, false); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "EscapeUri" property to "true" if links in the document contain characters, // such as the blank space, that we need to replace with escape sequences, such as "%20". // Set the "EscapeUri" property to "false" if we are sure that this document's links // do not need any such escape character substitution. options.EscapeUri = isEscaped; doc.Save(ArtifactsDir + "PdfSaveOptions.EscapedUri.pdf", options); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EscapedUri.pdf"); Page page = pdfDocument.Pages[1]; LinkAnnotation linkAnnot = (LinkAnnotation)page.Annotations[1]; GoToURIAction action = (GoToURIAction)linkAnnot.Action; Assert.AreEqual(result, action.URI); #endif } [TestCase(false)] [TestCase(true)] public void OpenHyperlinksInNewWindow(bool openHyperlinksInNewWindow) { //ExStart //ExFor:PdfSaveOptions.OpenHyperlinksInNewWindow //ExSummary:Shows how to save hyperlinks in a document we convert to PDF so that they open new pages when we click on them. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.InsertHyperlink("Testlink", @"https://www.google.com/search?q=%20aspose", false); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "OpenHyperlinksInNewWindow" property to "true" to save all hyperlinks using Javascript code // that forces readers to open these links in new windows/browser tabs. // Set the "OpenHyperlinksInNewWindow" property to "false" to save all hyperlinks normally. options.OpenHyperlinksInNewWindow = openHyperlinksInNewWindow; doc.Save(ArtifactsDir + "PdfSaveOptions.OpenHyperlinksInNewWindow.pdf", options); //ExEnd if (openHyperlinksInNewWindow) TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [70.84999847 707.35101318 110.17799377 721.15002441]/BS " + "<</Type/Border/S/S/W 0>>/A<</Type /Action/S /JavaScript/JS(app.launchURL\\(\"https://www.google.com/search?q=%20aspose\", true\\);)>>>>", ArtifactsDir + "PdfSaveOptions.OpenHyperlinksInNewWindow.pdf"); else TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [70.84999847 707.35101318 110.17799377 721.15002441]/BS " + "<</Type/Border/S/S/W 0>>/A<</Type /Action/S /URI/URI(https://www.google.com/search?q=%20aspose)>>>>", ArtifactsDir + "PdfSaveOptions.OpenHyperlinksInNewWindow.pdf"); #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.OpenHyperlinksInNewWindow.pdf"); Page page = pdfDocument.Pages[1]; LinkAnnotation linkAnnot = (LinkAnnotation) page.Annotations[1]; Assert.AreEqual(openHyperlinksInNewWindow ? typeof(JavascriptAction) : typeof(GoToURIAction), linkAnnot.Action.GetType()); #endif } //ExStart //ExFor:MetafileRenderingMode //ExFor:MetafileRenderingOptions //ExFor:MetafileRenderingOptions.EmulateRasterOperations //ExFor:MetafileRenderingOptions.RenderingMode //ExFor:IWarningCallback //ExFor:FixedPageSaveOptions.MetafileRenderingOptions //ExSummary:Shows added a fallback to bitmap rendering and changing type of warnings about unsupported metafile records. [Test, Category("SkipMono")] //ExSkip public void HandleBinaryRasterWarnings() { Document doc = new Document(MyDir + "WMF with image.docx"); MetafileRenderingOptions metafileRenderingOptions = new MetafileRenderingOptions(); // Set the "EmulateRasterOperations" property to "false" to fall back to bitmap when // it encounters a metafile, which will require raster operations to render in the output PDF. metafileRenderingOptions.EmulateRasterOperations = false; // Set the "RenderingMode" property to "VectorWithFallback" to try to render every metafile using vector graphics. metafileRenderingOptions.RenderingMode = MetafileRenderingMode.VectorWithFallback; // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF and applies the configuration // in our MetafileRenderingOptions object to the saving operation. PdfSaveOptions saveOptions = new PdfSaveOptions(); saveOptions.MetafileRenderingOptions = metafileRenderingOptions; HandleDocumentWarnings callback = new HandleDocumentWarnings(); doc.WarningCallback = callback; doc.Save(ArtifactsDir + "PdfSaveOptions.HandleBinaryRasterWarnings.pdf", saveOptions); Assert.AreEqual(1, callback.Warnings.Count); Assert.AreEqual("'R2_XORPEN' binary raster operation is partly supported.", callback.Warnings[0].Description); } /// <summary> /// Prints and collects formatting loss-related warnings that occur upon saving a document. /// </summary> public class HandleDocumentWarnings : IWarningCallback { public void Warning(WarningInfo info) { if (info.WarningType == WarningType.MinorFormattingLoss) { Console.WriteLine("Unsupported operation: " + info.Description); Warnings.Warning(info); } } public WarningInfoCollection Warnings = new WarningInfoCollection(); } //ExEnd [TestCase(Aspose.Words.Saving.HeaderFooterBookmarksExportMode.None)] [TestCase(Aspose.Words.Saving.HeaderFooterBookmarksExportMode.First)] [TestCase(Aspose.Words.Saving.HeaderFooterBookmarksExportMode.All)] public void HeaderFooterBookmarksExportMode(HeaderFooterBookmarksExportMode headerFooterBookmarksExportMode) { //ExStart //ExFor:HeaderFooterBookmarksExportMode //ExFor:OutlineOptions //ExFor:OutlineOptions.DefaultBookmarksOutlineLevel //ExFor:PdfSaveOptions.HeaderFooterBookmarksExportMode //ExFor:PdfSaveOptions.PageMode //ExFor:PdfPageMode //ExSummary:Shows to process bookmarks in headers/footers in a document that we are rendering to PDF. Document doc = new Document(MyDir + "Bookmarks in headers and footers.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "PageMode" property to "PdfPageMode.UseOutlines" to display the outline navigation pane in the output PDF. saveOptions.PageMode = PdfPageMode.UseOutlines; // Set the "DefaultBookmarksOutlineLevel" property to "1" to display all // bookmarks at the first level of the outline in the output PDF. saveOptions.OutlineOptions.DefaultBookmarksOutlineLevel = 1; // Set the "HeaderFooterBookmarksExportMode" property to "HeaderFooterBookmarksExportMode.None" to // not export any bookmarks that are inside headers/footers. // Set the "HeaderFooterBookmarksExportMode" property to "HeaderFooterBookmarksExportMode.First" to // only export bookmarks in the first section's header/footers. // Set the "HeaderFooterBookmarksExportMode" property to "HeaderFooterBookmarksExportMode.All" to // export bookmarks that are in all headers/footers. saveOptions.HeaderFooterBookmarksExportMode = headerFooterBookmarksExportMode; doc.Save(ArtifactsDir + "PdfSaveOptions.HeaderFooterBookmarksExportMode.pdf", saveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDoc = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.HeaderFooterBookmarksExportMode.pdf"); string inputDocLocaleName = new CultureInfo(doc.Styles.DefaultFont.LocaleId).Name; TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(); pdfDoc.Pages.Accept(textFragmentAbsorber); switch (headerFooterBookmarksExportMode) { case Aspose.Words.Saving.HeaderFooterBookmarksExportMode.None: TestUtil.FileContainsString($"<</Type /Catalog/Pages 3 0 R/Lang({inputDocLocaleName})>>\r\n", ArtifactsDir + "PdfSaveOptions.HeaderFooterBookmarksExportMode.pdf"); Assert.AreEqual(0, pdfDoc.Outlines.Count); break; case Aspose.Words.Saving.HeaderFooterBookmarksExportMode.First: case Aspose.Words.Saving.HeaderFooterBookmarksExportMode.All: TestUtil.FileContainsString( $"<</Type /Catalog/Pages 3 0 R/Outlines 13 0 R/PageMode /UseOutlines/Lang({inputDocLocaleName})>>", ArtifactsDir + "PdfSaveOptions.HeaderFooterBookmarksExportMode.pdf"); OutlineCollection outlineItemCollection = pdfDoc.Outlines; Assert.AreEqual(4, outlineItemCollection.Count); Assert.AreEqual("Bookmark_1", outlineItemCollection[1].Title); Assert.AreEqual("1 XYZ 233 806 0", outlineItemCollection[1].Destination.ToString()); Assert.AreEqual("Bookmark_2", outlineItemCollection[2].Title); Assert.AreEqual("1 XYZ 84 47 0", outlineItemCollection[2].Destination.ToString()); Assert.AreEqual("Bookmark_3", outlineItemCollection[3].Title); Assert.AreEqual("2 XYZ 85 806 0", outlineItemCollection[3].Destination.ToString()); Assert.AreEqual("Bookmark_4", outlineItemCollection[4].Title); Assert.AreEqual("2 XYZ 85 48 0", outlineItemCollection[4].Destination.ToString()); break; } #endif } [Test] public void UnsupportedImageFormatWarning() { Document doc = new Document(MyDir + "Corrupted image.docx"); SaveWarningCallback saveWarningCallback = new SaveWarningCallback(); doc.WarningCallback = saveWarningCallback; doc.Save(ArtifactsDir + "PdfSaveOption.UnsupportedImageFormatWarning.pdf", SaveFormat.Pdf); Assert.That(saveWarningCallback.SaveWarnings[0].Description, Is.EqualTo("Image can not be processed. Possibly unsupported image format.")); } public class SaveWarningCallback : IWarningCallback { public void Warning(WarningInfo info) { if (info.WarningType == WarningType.MinorFormattingLoss) { Console.WriteLine($"{info.WarningType}: {info.Description}."); SaveWarnings.Warning(info); } } internal WarningInfoCollection SaveWarnings = new WarningInfoCollection(); } [TestCase(false)] [TestCase(true)] public void FontsScaledToMetafileSize(bool scaleWmfFonts) { //ExStart //ExFor:MetafileRenderingOptions.ScaleWmfFontsToMetafileSize //ExSummary:Shows how to WMF fonts scaling according to metafile size on the page. Document doc = new Document(MyDir + "WMF with text.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "ScaleWmfFontsToMetafileSize" property to "true" to scale fonts // that format text within WMF images according to the size of the metafile on the page. // Set the "ScaleWmfFontsToMetafileSize" property to "false" to // preserve the default scale of these fonts. saveOptions.MetafileRenderingOptions.ScaleWmfFontsToMetafileSize = scaleWmfFonts; doc.Save(ArtifactsDir + "PdfSaveOptions.FontsScaledToMetafileSize.pdf", saveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.FontsScaledToMetafileSize.pdf"); TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages[1].Accept(textAbsorber); Rectangle textFragmentRectangle = textAbsorber.TextFragments[3].Rectangle; Assert.AreEqual(scaleWmfFonts ? 1.589d : 5.045d, textFragmentRectangle.Width, 0.001d); #endif } [TestCase(false)] [TestCase(true)] public void EmbedFullFonts(bool embedFullFonts) { //ExStart //ExFor:PdfSaveOptions.#ctor //ExFor:PdfSaveOptions.EmbedFullFonts //ExSummary:Shows how to enable or disable subsetting when embedding fonts while rendering a document to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Font.Name = "Arial"; builder.Writeln("Hello world!"); builder.Font.Name = "Arvo"; builder.Writeln("The quick brown fox jumps over the lazy dog."); // Configure our font sources to ensure that we have access to both the fonts in this document. FontSourceBase[] originalFontsSources = FontSettings.DefaultInstance.GetFontsSources(); Aspose.Words.Fonts.FolderFontSource folderFontSource = new Aspose.Words.Fonts.FolderFontSource(FontsDir, true); FontSettings.DefaultInstance.SetFontsSources(new[] { originalFontsSources[0], folderFontSource }); FontSourceBase[] fontSources = FontSettings.DefaultInstance.GetFontsSources(); Assert.True(fontSources[0].GetAvailableFonts().Any(f => f.FullFontName == "Arial")); Assert.True(fontSources[1].GetAvailableFonts().Any(f => f.FullFontName == "Arvo")); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Since our document contains a custom font, embedding in the output document may be desirable. // Set the "EmbedFullFonts" property to "true" to embed every glyph of every embedded font in the output PDF. // The document's size may become very large, but we will have full use of all fonts if we edit the PDF. // Set the "EmbedFullFonts" property to "false" to apply subsetting to fonts, saving only the glyphs // that the document is using. The file will be considerably smaller, // but we may need access to any custom fonts if we edit the document. options.EmbedFullFonts = embedFullFonts; doc.Save(ArtifactsDir + "PdfSaveOptions.EmbedFullFonts.pdf", options); if (embedFullFonts) Assert.That(500000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedFullFonts.pdf").Length)); else Assert.That(25000, Is.AtLeast(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedFullFonts.pdf").Length)); // Restore the original font sources. FontSettings.DefaultInstance.SetFontsSources(originalFontsSources); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EmbedFullFonts.pdf"); Aspose.Pdf.Text.Font[] pdfDocFonts = pdfDocument.FontUtilities.GetAllFonts(); Assert.AreEqual("ArialMT", pdfDocFonts[0].FontName); Assert.AreNotEqual(embedFullFonts, pdfDocFonts[0].IsSubset); Assert.AreEqual("Arvo", pdfDocFonts[1].FontName); Assert.AreNotEqual(embedFullFonts, pdfDocFonts[1].IsSubset); #endif } [TestCase(PdfFontEmbeddingMode.EmbedAll)] [TestCase(PdfFontEmbeddingMode.EmbedNone)] [TestCase(PdfFontEmbeddingMode.EmbedNonstandard)] public void EmbedWindowsFonts(PdfFontEmbeddingMode pdfFontEmbeddingMode) { //ExStart //ExFor:PdfSaveOptions.FontEmbeddingMode //ExFor:PdfFontEmbeddingMode //ExSummary:Shows how to set Aspose.Words to skip embedding Arial and Times New Roman fonts into a PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // "Arial" is a standard font, and "Courier New" is a nonstandard font. builder.Font.Name = "Arial"; builder.Writeln("Hello world!"); builder.Font.Name = "Courier New"; builder.Writeln("The quick brown fox jumps over the lazy dog."); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "EmbedFullFonts" property to "true" to embed every glyph of every embedded font in the output PDF. options.EmbedFullFonts = true; // Set the "FontEmbeddingMode" property to "EmbedAll" to embed all fonts in the output PDF. // Set the "FontEmbeddingMode" property to "EmbedNonstandard" to only allow nonstandard fonts' embedding in the output PDF. // Set the "FontEmbeddingMode" property to "EmbedNone" to not embed any fonts in the output PDF. options.FontEmbeddingMode = pdfFontEmbeddingMode; doc.Save(ArtifactsDir + "PdfSaveOptions.EmbedWindowsFonts.pdf", options); switch (pdfFontEmbeddingMode) { case PdfFontEmbeddingMode.EmbedAll: Assert.That(1000000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedWindowsFonts.pdf").Length)); break; case PdfFontEmbeddingMode.EmbedNonstandard: Assert.That(480000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedWindowsFonts.pdf").Length)); break; case PdfFontEmbeddingMode.EmbedNone: Assert.That(4000, Is.AtLeast(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedWindowsFonts.pdf").Length)); break; } //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EmbedWindowsFonts.pdf"); Aspose.Pdf.Text.Font[] pdfDocFonts = pdfDocument.FontUtilities.GetAllFonts(); Assert.AreEqual("ArialMT", pdfDocFonts[0].FontName); Assert.AreEqual(pdfFontEmbeddingMode == PdfFontEmbeddingMode.EmbedAll, pdfDocFonts[0].IsEmbedded); Assert.AreEqual("CourierNewPSMT", pdfDocFonts[1].FontName); Assert.AreEqual(pdfFontEmbeddingMode == PdfFontEmbeddingMode.EmbedAll || pdfFontEmbeddingMode == PdfFontEmbeddingMode.EmbedNonstandard, pdfDocFonts[1].IsEmbedded); #endif } [TestCase(false)] [TestCase(true)] public void EmbedCoreFonts(bool useCoreFonts) { //ExStart //ExFor:PdfSaveOptions.UseCoreFonts //ExSummary:Shows how enable/disable PDF Type 1 font substitution. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Font.Name = "Arial"; builder.Writeln("Hello world!"); builder.Font.Name = "Courier New"; builder.Writeln("The quick brown fox jumps over the lazy dog."); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "UseCoreFonts" property to "true" to replace some fonts, // including the two fonts in our document, with their PDF Type 1 equivalents. // Set the "UseCoreFonts" property to "false" to not apply PDF Type 1 fonts. options.UseCoreFonts = useCoreFonts; doc.Save(ArtifactsDir + "PdfSaveOptions.EmbedCoreFonts.pdf", options); if (useCoreFonts) Assert.That(3000, Is.AtLeast(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedCoreFonts.pdf").Length)); else Assert.That(30000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.EmbedCoreFonts.pdf").Length)); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EmbedCoreFonts.pdf"); Aspose.Pdf.Text.Font[] pdfDocFonts = pdfDocument.FontUtilities.GetAllFonts(); if (useCoreFonts) { Assert.AreEqual("Helvetica", pdfDocFonts[0].FontName); Assert.AreEqual("Courier", pdfDocFonts[1].FontName); } else { Assert.AreEqual("ArialMT", pdfDocFonts[0].FontName); Assert.AreEqual("CourierNewPSMT", pdfDocFonts[1].FontName); } Assert.AreNotEqual(useCoreFonts, pdfDocFonts[0].IsEmbedded); Assert.AreNotEqual(useCoreFonts, pdfDocFonts[1].IsEmbedded); #endif } [TestCase(false)] [TestCase(true)] public void AdditionalTextPositioning(bool applyAdditionalTextPositioning) { //ExStart //ExFor:PdfSaveOptions.AdditionalTextPositioning //ExSummary:Show how to write additional text positioning operators. Document doc = new Document(MyDir + "Text positioning operators.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions { TextCompression = PdfTextCompression.None, // Set the "AdditionalTextPositioning" property to "true" to attempt to fix incorrect // element positioning in the output PDF, should there be any, at the cost of increased file size. // Set the "AdditionalTextPositioning" property to "false" to render the document as usual. AdditionalTextPositioning = applyAdditionalTextPositioning }; doc.Save(ArtifactsDir + "PdfSaveOptions.AdditionalTextPositioning.pdf", saveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.AdditionalTextPositioning.pdf"); TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages[1].Accept(textAbsorber); SetGlyphsPositionShowText tjOperator = (SetGlyphsPositionShowText) textAbsorber.TextFragments[1].Page.Contents[85]; if (applyAdditionalTextPositioning) { Assert.That(100000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.AdditionalTextPositioning.pdf").Length)); Assert.AreEqual( "[0 (S) 0 (a) 0 (m) 0 (s) 0 (t) 0 (a) -1 (g) 1 (,) 0 ( ) 0 (1) 0 (0) 0 (.) 0 ( ) 0 (N) 0 (o) 0 (v) 0 (e) 0 (m) 0 (b) 0 (e) 0 (r) -1 ( ) 1 (2) -1 (0) 0 (1) 0 (8)] TJ", tjOperator.ToString()); } else { Assert.That(97000, Is.LessThan(new FileInfo(ArtifactsDir + "PdfSaveOptions.AdditionalTextPositioning.pdf").Length)); Assert.AreEqual("[(Samsta) -1 (g) 1 (, 10. November) -1 ( ) 1 (2) -1 (018)] TJ", tjOperator.ToString()); } #endif } [TestCase(false, Category = "SkipMono")] [TestCase(true, Category = "SkipMono")] public void SaveAsPdfBookFold(bool renderTextAsBookfold) { //ExStart //ExFor:PdfSaveOptions.UseBookFoldPrintingSettings //ExSummary:Shows how to save a document to the PDF format in the form of a book fold. Document doc = new Document(MyDir + "Paragraphs.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "UseBookFoldPrintingSettings" property to "true" to arrange the contents // in the output PDF in a way that helps us use it to make a booklet. // Set the "UseBookFoldPrintingSettings" property to "false" to render the PDF normally. options.UseBookFoldPrintingSettings = renderTextAsBookfold; // If we are rendering the document as a booklet, we must set the "MultiplePages" // properties of the page setup objects of all sections to "MultiplePagesType.BookFoldPrinting". if (renderTextAsBookfold) foreach (Section s in doc.Sections) { s.PageSetup.MultiplePages = MultiplePagesType.BookFoldPrinting; } // Once we print this document on both sides of the pages, we can fold all the pages down the middle at once, // and the contents will line up in a way that creates a booklet. doc.Save(ArtifactsDir + "PdfSaveOptions.SaveAsPdfBookFold.pdf", options); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.SaveAsPdfBookFold.pdf"); TextAbsorber textAbsorber = new TextAbsorber(); pdfDocument.Pages.Accept(textAbsorber); if (renderTextAsBookfold) { Assert.True(textAbsorber.Text.IndexOf("Heading #1", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #2", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #2", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #3", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #3", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #4", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #4", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #5", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #5", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #6", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #6", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #7", StringComparison.Ordinal)); Assert.False(textAbsorber.Text.IndexOf("Heading #7", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #8", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #8", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #9", StringComparison.Ordinal)); Assert.False(textAbsorber.Text.IndexOf("Heading #9", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #10", StringComparison.Ordinal)); } else { Assert.True(textAbsorber.Text.IndexOf("Heading #1", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #2", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #2", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #3", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #3", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #4", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #4", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #5", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #5", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #6", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #6", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #7", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #7", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #8", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #8", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #9", StringComparison.Ordinal)); Assert.True(textAbsorber.Text.IndexOf("Heading #9", StringComparison.Ordinal) < textAbsorber.Text.IndexOf("Heading #10", StringComparison.Ordinal)); } #endif } [Test] public void ZoomBehaviour() { //ExStart //ExFor:PdfSaveOptions.ZoomBehavior //ExFor:PdfSaveOptions.ZoomFactor //ExFor:PdfZoomBehavior //ExSummary:Shows how to set the default zooming that a reader applies when opening a rendered PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Hello world!"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. // Set the "ZoomBehavior" property to "PdfZoomBehavior.ZoomFactor" to get a PDF reader to // apply a percentage-based zoom factor when we open the document with it. // Set the "ZoomFactor" property to "25" to give the zoom factor a value of 25%. PdfSaveOptions options = new PdfSaveOptions { ZoomBehavior = PdfZoomBehavior.ZoomFactor, ZoomFactor = 25 }; // When we open this document using a reader such as Adobe Acrobat, we will see the document scaled at 1/4 of its actual size. doc.Save(ArtifactsDir + "PdfSaveOptions.ZoomBehaviour.pdf", options); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ZoomBehaviour.pdf"); GoToAction action = (GoToAction)pdfDocument.OpenAction; Assert.AreEqual(0.25d, (action.Destination as XYZExplicitDestination).Zoom); #endif } [TestCase(PdfPageMode.FullScreen)] [TestCase(PdfPageMode.UseThumbs)] [TestCase(PdfPageMode.UseOC)] [TestCase(PdfPageMode.UseOutlines)] [TestCase(PdfPageMode.UseNone)] public void PageMode(PdfPageMode pageMode) { //ExStart //ExFor:PdfSaveOptions.PageMode //ExFor:PdfPageMode //ExSummary:Shows how to set instructions for some PDF readers to follow when opening an output document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Hello world!"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "PageMode" property to "PdfPageMode.FullScreen" to get the PDF reader to open the saved // document in full-screen mode, which takes over the monitor's display and has no controls visible. // Set the "PageMode" property to "PdfPageMode.UseThumbs" to get the PDF reader to display a separate panel // with a thumbnail for each page in the document. // Set the "PageMode" property to "PdfPageMode.UseOC" to get the PDF reader to display a separate panel // that allows us to work with any layers present in the document. // Set the "PageMode" property to "PdfPageMode.UseOutlines" to get the PDF reader // also to display the outline, if possible. // Set the "PageMode" property to "PdfPageMode.UseNone" to get the PDF reader to display just the document itself. options.PageMode = pageMode; doc.Save(ArtifactsDir + "PdfSaveOptions.PageMode.pdf", options); //ExEnd string docLocaleName = new CultureInfo(doc.Styles.DefaultFont.LocaleId).Name; switch (pageMode) { case PdfPageMode.FullScreen: TestUtil.FileContainsString( $"<</Type /Catalog/Pages 3 0 R/PageMode /FullScreen/Lang({docLocaleName})>>\r\n", ArtifactsDir + "PdfSaveOptions.PageMode.pdf"); break; case PdfPageMode.UseThumbs: TestUtil.FileContainsString( $"<</Type /Catalog/Pages 3 0 R/PageMode /UseThumbs/Lang({docLocaleName})>>", ArtifactsDir + "PdfSaveOptions.PageMode.pdf"); break; case PdfPageMode.UseOC: TestUtil.FileContainsString( $"<</Type /Catalog/Pages 3 0 R/PageMode /UseOC/Lang({docLocaleName})>>\r\n", ArtifactsDir + "PdfSaveOptions.PageMode.pdf"); break; case PdfPageMode.UseOutlines: case PdfPageMode.UseNone: TestUtil.FileContainsString($"<</Type /Catalog/Pages 3 0 R/Lang({docLocaleName})>>\r\n", ArtifactsDir + "PdfSaveOptions.PageMode.pdf"); break; } #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PageMode.pdf"); switch (pageMode) { case PdfPageMode.UseNone: case PdfPageMode.UseOutlines: Assert.AreEqual(Aspose.Pdf.PageMode.UseNone, pdfDocument.PageMode); break; case PdfPageMode.UseThumbs: Assert.AreEqual(Aspose.Pdf.PageMode.UseThumbs, pdfDocument.PageMode); break; case PdfPageMode.FullScreen: Assert.AreEqual(Aspose.Pdf.PageMode.FullScreen, pdfDocument.PageMode); break; case PdfPageMode.UseOC: Assert.AreEqual(Aspose.Pdf.PageMode.UseOC, pdfDocument.PageMode); break; } #endif } [TestCase(false)] [TestCase(true)] public void NoteHyperlinks(bool createNoteHyperlinks) { //ExStart //ExFor:PdfSaveOptions.CreateNoteHyperlinks //ExSummary:Shows how to make footnotes and endnotes function as hyperlinks. Document doc = new Document(MyDir + "Footnotes and endnotes.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "CreateNoteHyperlinks" property to "true" to turn all footnote/endnote symbols // in the text act as links that, upon clicking, take us to their respective footnotes/endnotes. // Set the "CreateNoteHyperlinks" property to "false" not to have footnote/endnote symbols link to anything. options.CreateNoteHyperlinks = createNoteHyperlinks; doc.Save(ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf", options); //ExEnd if (createNoteHyperlinks) { TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [157.80099487 720.90106201 159.35600281 733.55004883]/BS <</Type/Border/S/S/W 0>>/Dest[4 0 R /XYZ 85 677 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [202.16900635 720.90106201 206.06201172 733.55004883]/BS <</Type/Border/S/S/W 0>>/Dest[4 0 R /XYZ 85 79 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [212.23199463 699.2510376 215.34199524 711.90002441]/BS <</Type/Border/S/S/W 0>>/Dest[4 0 R /XYZ 85 654 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [258.15499878 699.2510376 262.04800415 711.90002441]/BS <</Type/Border/S/S/W 0>>/Dest[4 0 R /XYZ 85 68 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [85.05000305 68.19905853 88.66500092 79.69805908]/BS <</Type/Border/S/S/W 0>>/Dest[4 0 R /XYZ 202 733 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [85.05000305 56.70005798 88.66500092 68.19905853]/BS <</Type/Border/S/S/W 0>>/Dest[4 0 R /XYZ 258 711 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [85.05000305 666.10205078 86.4940033 677.60107422]/BS <</Type/Border/S/S/W 0>>/Dest[4 0 R /XYZ 157 733 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); TestUtil.FileContainsString( "<</Type /Annot/Subtype /Link/Rect [85.05000305 643.10406494 87.93800354 654.60308838]/BS <</Type/Border/S/S/W 0>>/Dest[4 0 R /XYZ 212 711 0]>>", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); } else { if (!IsRunningOnMono()) Assert.Throws<AssertionException>(() => TestUtil.FileContainsString("<</Type /Annot/Subtype /Link/Rect", ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf")); } #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.NoteHyperlinks.pdf"); Page page = pdfDocument.Pages[1]; AnnotationSelector annotationSelector = new AnnotationSelector(new LinkAnnotation(page, Rectangle.Trivial)); page.Accept(annotationSelector); List<LinkAnnotation> linkAnnotations = annotationSelector.Selected.Cast<LinkAnnotation>().ToList(); if (createNoteHyperlinks) { Assert.AreEqual(8, linkAnnotations.Count(a => a.AnnotationType == AnnotationType.Link)); Assert.AreEqual("1 XYZ 85 677 0", linkAnnotations[0].Destination.ToString()); Assert.AreEqual("1 XYZ 85 79 0", linkAnnotations[1].Destination.ToString()); Assert.AreEqual("1 XYZ 85 654 0", linkAnnotations[2].Destination.ToString()); Assert.AreEqual("1 XYZ 85 68 0", linkAnnotations[3].Destination.ToString()); Assert.AreEqual("1 XYZ 202 733 0", linkAnnotations[4].Destination.ToString()); Assert.AreEqual("1 XYZ 258 711 0", linkAnnotations[5].Destination.ToString()); Assert.AreEqual("1 XYZ 157 733 0", linkAnnotations[6].Destination.ToString()); Assert.AreEqual("1 XYZ 212 711 0", linkAnnotations[7].Destination.ToString()); } else { Assert.AreEqual(0, annotationSelector.Selected.Count); } #endif } [TestCase(PdfCustomPropertiesExport.None)] [TestCase(PdfCustomPropertiesExport.Standard)] [TestCase(PdfCustomPropertiesExport.Metadata)] public void CustomPropertiesExport(PdfCustomPropertiesExport pdfCustomPropertiesExportMode) { //ExStart //ExFor:PdfCustomPropertiesExport //ExFor:PdfSaveOptions.CustomPropertiesExport //ExSummary:Shows how to export custom properties while converting a document to PDF. Document doc = new Document(); doc.CustomDocumentProperties.Add("Company", "My value"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "CustomPropertiesExport" property to "PdfCustomPropertiesExport.None" to discard // custom document properties as we save the document to .PDF. // Set the "CustomPropertiesExport" property to "PdfCustomPropertiesExport.Standard" // to preserve custom properties within the output PDF document. // Set the "CustomPropertiesExport" property to "PdfCustomPropertiesExport.Metadata" // to preserve custom properties in an XMP packet. options.CustomPropertiesExport = pdfCustomPropertiesExportMode; doc.Save(ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf", options); //ExEnd switch (pdfCustomPropertiesExportMode) { case PdfCustomPropertiesExport.None: if (!IsRunningOnMono()) { Assert.Throws<AssertionException>(() => TestUtil.FileContainsString( doc.CustomDocumentProperties[0].Name, ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf")); Assert.Throws<AssertionException>(() => TestUtil.FileContainsString( "<</Type /Metadata/Subtype /XML/Length 8 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf")); } break; case PdfCustomPropertiesExport.Standard: TestUtil.FileContainsString( "<</Creator(þÿ\0A\0s\0p\0o\0s\0e\0.\0W\0o\0r\0d\0s)/Producer(þÿ\0A\0s\0p\0o\0s\0e\0.\0W\0o\0r\0d\0s\0 \0f\0o\0r\0", ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf"); TestUtil.FileContainsString("/Company (þÿ\0M\0y\0 \0v\0a\0l\0u\0e)>>", ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf"); break; case PdfCustomPropertiesExport.Metadata: TestUtil.FileContainsString("<</Type /Metadata/Subtype /XML/Length 8 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf"); break; } #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.CustomPropertiesExport.pdf"); Assert.AreEqual("Aspose.Words", pdfDocument.Info.Creator); Assert.True(pdfDocument.Info.Producer.StartsWith("Aspose.Words")); switch (pdfCustomPropertiesExportMode) { case PdfCustomPropertiesExport.None: Assert.AreEqual(2, pdfDocument.Info.Count); Assert.AreEqual(0, pdfDocument.Metadata.Count); break; case PdfCustomPropertiesExport.Metadata: Assert.AreEqual(2, pdfDocument.Info.Count); Assert.AreEqual(2, pdfDocument.Metadata.Count); Assert.AreEqual("Aspose.Words", pdfDocument.Metadata["xmp:CreatorTool"].ToString()); Assert.AreEqual("Company", pdfDocument.Metadata["custprops:Property1"].ToString()); break; case PdfCustomPropertiesExport.Standard: Assert.AreEqual(3, pdfDocument.Info.Count); Assert.AreEqual(0, pdfDocument.Metadata.Count); Assert.AreEqual("My value", pdfDocument.Info["Company"]); break; } #endif } [TestCase(DmlEffectsRenderingMode.None)] [TestCase(DmlEffectsRenderingMode.Simplified)] [TestCase(DmlEffectsRenderingMode.Fine)] public void DrawingMLEffects(DmlEffectsRenderingMode effectsRenderingMode) { //ExStart //ExFor:DmlRenderingMode //ExFor:DmlEffectsRenderingMode //ExFor:PdfSaveOptions.DmlEffectsRenderingMode //ExFor:SaveOptions.DmlEffectsRenderingMode //ExFor:SaveOptions.DmlRenderingMode //ExSummary:Shows how to configure the rendering quality of DrawingML effects in a document as we save it to PDF. Document doc = new Document(MyDir + "DrawingML shape effects.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "DmlEffectsRenderingMode" property to "DmlEffectsRenderingMode.None" to discard all DrawingML effects. // Set the "DmlEffectsRenderingMode" property to "DmlEffectsRenderingMode.Simplified" // to render a simplified version of DrawingML effects. // Set the "DmlEffectsRenderingMode" property to "DmlEffectsRenderingMode.Fine" to // render DrawingML effects with more accuracy and also with more processing cost. options.DmlEffectsRenderingMode = effectsRenderingMode; Assert.AreEqual(DmlRenderingMode.DrawingML, options.DmlRenderingMode); doc.Save(ArtifactsDir + "PdfSaveOptions.DrawingMLEffects.pdf", options); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.DrawingMLEffects.pdf"); ImagePlacementAbsorber imagePlacementAbsorber = new ImagePlacementAbsorber(); imagePlacementAbsorber.Visit(pdfDocument.Pages[1]); TableAbsorber tableAbsorber = new TableAbsorber(); tableAbsorber.Visit(pdfDocument.Pages[1]); switch (effectsRenderingMode) { case DmlEffectsRenderingMode.None: case DmlEffectsRenderingMode.Simplified: TestUtil.FileContainsString("4 0 obj\r\n" + "<</Type /Page/Parent 3 0 R/Contents 5 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAH 7 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.DrawingMLEffects.pdf"); Assert.AreEqual(0, imagePlacementAbsorber.ImagePlacements.Count); Assert.AreEqual(28, tableAbsorber.TableList.Count); break; case DmlEffectsRenderingMode.Fine: TestUtil.FileContainsString( "4 0 obj\r\n<</Type /Page/Parent 3 0 R/Contents 5 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAH 7 0 R>>/XObject<</X1 9 0 R/X2 10 0 R/X3 11 0 R/X4 12 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.DrawingMLEffects.pdf"); Assert.AreEqual(21, imagePlacementAbsorber.ImagePlacements.Count); Assert.AreEqual(4, tableAbsorber.TableList.Count); break; } #endif } [TestCase(DmlRenderingMode.Fallback)] [TestCase(DmlRenderingMode.DrawingML)] public void DrawingMLFallback(DmlRenderingMode dmlRenderingMode) { //ExStart //ExFor:DmlRenderingMode //ExFor:SaveOptions.DmlRenderingMode //ExSummary:Shows how to render fallback shapes when saving to PDF. Document doc = new Document(MyDir + "DrawingML shape fallbacks.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "DmlRenderingMode" property to "DmlRenderingMode.Fallback" // to substitute DML shapes with their fallback shapes. // Set the "DmlRenderingMode" property to "DmlRenderingMode.DrawingML" // to render the DML shapes themselves. options.DmlRenderingMode = dmlRenderingMode; doc.Save(ArtifactsDir + "PdfSaveOptions.DrawingMLFallback.pdf", options); //ExEnd switch (dmlRenderingMode) { case DmlRenderingMode.DrawingML: TestUtil.FileContainsString( "<</Type /Page/Parent 3 0 R/Contents 5 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAH 7 0 R/FAAABA 10 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.DrawingMLFallback.pdf"); break; case DmlRenderingMode.Fallback: TestUtil.FileContainsString( "4 0 obj\r\n<</Type /Page/Parent 3 0 R/Contents 5 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAH 7 0 R/FAAABC 12 0 R>>/ExtGState<</GS1 9 0 R/GS2 10 0 R>>>>/Group ", ArtifactsDir + "PdfSaveOptions.DrawingMLFallback.pdf"); break; } #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.DrawingMLFallback.pdf"); ImagePlacementAbsorber imagePlacementAbsorber = new ImagePlacementAbsorber(); imagePlacementAbsorber.Visit(pdfDocument.Pages[1]); TableAbsorber tableAbsorber = new TableAbsorber(); tableAbsorber.Visit(pdfDocument.Pages[1]); switch (dmlRenderingMode) { case DmlRenderingMode.DrawingML: Assert.AreEqual(6, tableAbsorber.TableList.Count); break; case DmlRenderingMode.Fallback: Assert.AreEqual(15, tableAbsorber.TableList.Count); break; } #endif } [TestCase(false)] [TestCase(true)] public void ExportDocumentStructure(bool exportDocumentStructure) { //ExStart //ExFor:PdfSaveOptions.ExportDocumentStructure //ExSummary:Shows how to preserve document structure elements, which can assist in programmatically interpreting our document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.ParagraphFormat.Style = doc.Styles["Heading 1"]; builder.Writeln("Hello world!"); builder.ParagraphFormat.Style = doc.Styles["Normal"]; builder.Write( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "ExportDocumentStructure" property to "true" to make the document structure, such tags, available via the // "Content" navigation pane of Adobe Acrobat at the cost of increased file size. // Set the "ExportDocumentStructure" property to "false" to not export the document structure. options.ExportDocumentStructure = exportDocumentStructure; // Suppose we export document structure while saving this document. In that case, // we can open it using Adobe Acrobat and find tags for elements such as the heading // and the next paragraph via "View" -> "Show/Hide" -> "Navigation panes" -> "Tags". doc.Save(ArtifactsDir + "PdfSaveOptions.ExportDocumentStructure.pdf", options); //ExEnd if (exportDocumentStructure) { TestUtil.FileContainsString("4 0 obj\r\n" + "<</Type /Page/Parent 3 0 R/Contents 5 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAH 7 0 R/FAAABB 11 0 R>>/ExtGState<</GS1 9 0 R/GS2 13 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>/StructParents 0/Tabs /S>>", ArtifactsDir + "PdfSaveOptions.ExportDocumentStructure.pdf"); } else { TestUtil.FileContainsString("4 0 obj\r\n" + "<</Type /Page/Parent 3 0 R/Contents 5 0 R/MediaBox [0 0 612 792]/Resources<</Font<</FAAAAH 7 0 R/FAAABA 10 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.ExportDocumentStructure.pdf"); } } #if NET462 || JAVA [TestCase(false, Category = "SkipMono")] [TestCase(true, Category = "SkipMono")] public void PreblendImages(bool preblendImages) { //ExStart //ExFor:PdfSaveOptions.PreblendImages //ExSummary:Shows how to preblend images with transparent backgrounds while saving a document to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Image img = Image.FromFile(ImageDir + "Transparent background logo.png"); builder.InsertImage(img); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "PreblendImages" property to "true" to preblend transparent images // with a background, which may reduce artifacts. // Set the "PreblendImages" property to "false" to render transparent images normally. options.PreblendImages = preblendImages; doc.Save(ArtifactsDir + "PdfSaveOptions.PreblendImages.pdf", options); //ExEnd Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PreblendImages.pdf"); XImage image = pdfDocument.Pages[1].Resources.Images[1]; using (MemoryStream stream = new MemoryStream()) { image.Save(stream); if (preblendImages) { TestUtil.FileContainsString("9 0 obj\r\n20849 ", ArtifactsDir + "PdfSaveOptions.PreblendImages.pdf"); Assert.AreEqual(17898, stream.Length); } else { TestUtil.FileContainsString("9 0 obj\r\n19289 ", ArtifactsDir + "PdfSaveOptions.PreblendImages.pdf"); Assert.AreEqual(19216, stream.Length); } } } [TestCase(false)] [TestCase(true)] public void InterpolateImages(bool interpolateImages) { //ExStart //ExFor:PdfSaveOptions.InterpolateImages //ExSummary:Shows how to perform interpolation on images while saving a document to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Image img = Image.FromFile(ImageDir + "Transparent background logo.png"); builder.InsertImage(img); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "InterpolateImages" property to "true" to get the reader that opens this document to interpolate images. // Their resolution should be lower than that of the device that is displaying the document. // Set the "InterpolateImages" property to "false" to make it so that the reader does not apply any interpolation. saveOptions.InterpolateImages = interpolateImages; // When we open this document with a reader such as Adobe Acrobat, we will need to zoom in on the image // to see the interpolation effect if we saved the document with it enabled. doc.Save(ArtifactsDir + "PdfSaveOptions.InterpolateImages.pdf", saveOptions); //ExEnd if (interpolateImages) { TestUtil.FileContainsString("6 0 obj\r\n" + "<</Type /XObject/Subtype /Image/Width 400/Height 400/ColorSpace /DeviceRGB/BitsPerComponent 8/SMask 8 0 R/Interpolate true/Length 9 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.InterpolateImages.pdf"); } else { TestUtil.FileContainsString("6 0 obj\r\n" + "<</Type /XObject/Subtype /Image/Width 400/Height 400/ColorSpace /DeviceRGB/BitsPerComponent 8/SMask 8 0 R/Length 9 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.InterpolateImages.pdf"); } } [Test, Category("SkipMono")] public void Dml3DEffectsRenderingModeTest() { Document doc = new Document(MyDir + "DrawingML shape 3D effects.docx"); RenderCallback warningCallback = new RenderCallback(); doc.WarningCallback = warningCallback; PdfSaveOptions saveOptions = new PdfSaveOptions(); saveOptions.Dml3DEffectsRenderingMode = Dml3DEffectsRenderingMode.Advanced; doc.Save(ArtifactsDir + "PdfSaveOptions.Dml3DEffectsRenderingModeTest.pdf", saveOptions); Assert.AreEqual(43, warningCallback.Count); } public class RenderCallback : IWarningCallback { public void Warning(WarningInfo info) { Console.WriteLine($"{info.WarningType}: {info.Description}."); mWarnings.Add(info); } public WarningInfo this[int i] => mWarnings[i]; /// <summary> /// Clears warning collection. /// </summary> public void Clear() { mWarnings.Clear(); } public int Count => mWarnings.Count; /// <summary> /// Returns true if a warning with the specified properties has been generated. /// </summary> public bool Contains(WarningSource source, WarningType type, string description) { return mWarnings.Any(warning => warning.Source == source && warning.WarningType == type && warning.Description == description); } private readonly List<WarningInfo> mWarnings = new List<WarningInfo>(); } #elif NETCOREAPP2_1 [TestCase(false)] [TestCase(true)] public void PreblendImagesNetStandard2(bool preblendImages) { //ExStart //ExFor:PdfSaveOptions.PreblendImages //ExSummary:Shows how to preblend images with transparent backgrounds (.NetStandard 2.0). Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); using (Image image = Image.Decode(ImageDir + "Transparent background logo.png")) builder.InsertImage(image); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "PreblendImages" property to "true" to preblend transparent images // with a background, which may reduce artifacts. // Set the "PreblendImages" property to "false" to render transparent images normally. options.PreblendImages = preblendImages; doc.Save(ArtifactsDir + "PdfSaveOptions.PreblendImagesNetStandard2.pdf", options); //ExEnd Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PreblendImagesNetStandard2.pdf"); XImage xImage = pdfDocument.Pages[1].Resources.Images[1]; using (MemoryStream stream = new MemoryStream()) { xImage.Save(stream); if (preblendImages) { TestUtil.FileContainsString("9 0 obj\r\n20849 ", ArtifactsDir + "PdfSaveOptions.PreblendImagesNetStandard2.pdf"); Assert.AreEqual(17898, stream.Length); } else { TestUtil.FileContainsString("9 0 obj\r\n20266 ", ArtifactsDir + "PdfSaveOptions.PreblendImagesNetStandard2.pdf"); Assert.AreEqual(19135, stream.Length); } } } [TestCase(false)] [TestCase(true)] public void InterpolateImagesNetStandard2(bool interpolateImages) { //ExStart //ExFor:PdfSaveOptions.InterpolateImages //ExSummary:Shows how to improve the quality of an image in the rendered documents (.NetStandard 2.0). Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); using (Image image = Image.Decode(ImageDir + "Transparent background logo.png")) builder.InsertImage(image); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "InterpolateImages" property to "true" to get the reader that opens this document to interpolate images. // Their resolution should be lower than that of the device that is displaying the document. // Set the "InterpolateImages" property to "false" to make it so that the reader does not apply any interpolation. saveOptions.InterpolateImages = interpolateImages; // When we open this document with a reader such as Adobe Acrobat, we will need to zoom in on the image // to see the interpolation effect if we saved the document with it enabled. doc.Save(ArtifactsDir + "PdfSaveOptions.InterpolateImagesNetStandard2.pdf", saveOptions); //ExEnd if (interpolateImages) { TestUtil.FileContainsString("6 0 obj\r\n" + "<</Type /XObject/Subtype /Image/Width 400/Height 400/ColorSpace /DeviceRGB/BitsPerComponent 8/SMask 8 0 R/Interpolate true/Length 9 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.InterpolateImagesNetStandard2.pdf"); } else { TestUtil.FileContainsString("6 0 obj\r\n" + "<</Type /XObject/Subtype /Image/Width 400/Height 400/ColorSpace /DeviceRGB/BitsPerComponent 8/SMask 8 0 R/Length 9 0 R/Filter /FlateDecode>>", ArtifactsDir + "PdfSaveOptions.InterpolateImagesNetStandard2.pdf"); } } #endif [Test] public void PdfDigitalSignature() { //ExStart //ExFor:PdfDigitalSignatureDetails //ExFor:PdfDigitalSignatureDetails.#ctor //ExFor:PdfDigitalSignatureDetails.#ctor(CertificateHolder, String, String, DateTime) //ExFor:PdfDigitalSignatureDetails.HashAlgorithm //ExFor:PdfDigitalSignatureDetails.Location //ExFor:PdfDigitalSignatureDetails.Reason //ExFor:PdfDigitalSignatureDetails.SignatureDate //ExFor:PdfDigitalSignatureHashAlgorithm //ExFor:PdfSaveOptions.DigitalSignatureDetails //ExSummary:Shows how to sign a generated PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Contents of signed PDF."); CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Configure the "DigitalSignatureDetails" object of the "SaveOptions" object to // digitally sign the document as we render it with the "Save" method. DateTime signingTime = DateTime.Now; options.DigitalSignatureDetails = new PdfDigitalSignatureDetails(certificateHolder, "Test Signing", "My Office", signingTime); options.DigitalSignatureDetails.HashAlgorithm = PdfDigitalSignatureHashAlgorithm.Sha256; Assert.AreEqual("Test Signing", options.DigitalSignatureDetails.Reason); Assert.AreEqual("My Office", options.DigitalSignatureDetails.Location); Assert.AreEqual(signingTime.ToUniversalTime(), options.DigitalSignatureDetails.SignatureDate); doc.Save(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignature.pdf", options); //ExEnd TestUtil.FileContainsString("6 0 obj\r\n" + "<</Type /Annot/Subtype /Widget/FT /Sig/DR <<>>/F 132/Rect [0 0 0 0]/V 7 0 R/P 4 0 R/T(þÿ\0A\0s\0p\0o\0s\0e\0D\0i\0g\0i\0t\0a\0l\0S\0i\0g\0n\0a\0t\0u\0r\0e)/AP <</N 8 0 R>>>>", ArtifactsDir + "PdfSaveOptions.PdfDigitalSignature.pdf"); Assert.False(FileFormatUtil.DetectFileFormat(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignature.pdf") .HasDigitalSignature); #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignature.pdf"); Assert.False(pdfDocument.Form.SignaturesExist); SignatureField signatureField = (SignatureField)pdfDocument.Form[1]; Assert.AreEqual("AsposeDigitalSignature", signatureField.FullName); Assert.AreEqual("AsposeDigitalSignature", signatureField.PartialName); Assert.AreEqual(typeof(Aspose.Pdf.Forms.PKCS7), signatureField.Signature.GetType()); Assert.AreEqual(DateTime.Today, signatureField.Signature.Date.Date); Assert.AreEqual("þÿ\0M\0o\0r\0z\0a\0l\0.\0M\0e", signatureField.Signature.Authority); Assert.AreEqual("þÿ\0M\0y\0 \0O\0f\0f\0i\0c\0e", signatureField.Signature.Location); Assert.AreEqual("þÿ\0T\0e\0s\0t\0 \0S\0i\0g\0n\0i\0n\0g", signatureField.Signature.Reason); #endif } [Test] public void PdfDigitalSignatureTimestamp() { //ExStart //ExFor:PdfDigitalSignatureDetails.TimestampSettings //ExFor:PdfDigitalSignatureTimestampSettings //ExFor:PdfDigitalSignatureTimestampSettings.#ctor //ExFor:PdfDigitalSignatureTimestampSettings.#ctor(String,String,String) //ExFor:PdfDigitalSignatureTimestampSettings.#ctor(String,String,String,TimeSpan) //ExFor:PdfDigitalSignatureTimestampSettings.Password //ExFor:PdfDigitalSignatureTimestampSettings.ServerUrl //ExFor:PdfDigitalSignatureTimestampSettings.Timeout //ExFor:PdfDigitalSignatureTimestampSettings.UserName //ExSummary:Shows how to sign a saved PDF document digitally and timestamp it. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Signed PDF contents."); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Create a digital signature and assign it to our SaveOptions object to sign the document when we save it to PDF. CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw"); options.DigitalSignatureDetails = new PdfDigitalSignatureDetails(certificateHolder, "Test Signing", "Aspose Office", DateTime.Now); // Create a timestamp authority-verified timestamp. options.DigitalSignatureDetails.TimestampSettings = new PdfDigitalSignatureTimestampSettings("https://freetsa.org/tsr", "JohnDoe", "MyPassword"); // The default lifespan of the timestamp is 100 seconds. Assert.AreEqual(100.0d, options.DigitalSignatureDetails.TimestampSettings.Timeout.TotalSeconds); // We can set our timeout period via the constructor. options.DigitalSignatureDetails.TimestampSettings = new PdfDigitalSignatureTimestampSettings("https://freetsa.org/tsr", "JohnDoe", "MyPassword", TimeSpan.FromMinutes(30)); Assert.AreEqual(1800.0d, options.DigitalSignatureDetails.TimestampSettings.Timeout.TotalSeconds); Assert.AreEqual("https://freetsa.org/tsr", options.DigitalSignatureDetails.TimestampSettings.ServerUrl); Assert.AreEqual("JohnDoe", options.DigitalSignatureDetails.TimestampSettings.UserName); Assert.AreEqual("MyPassword", options.DigitalSignatureDetails.TimestampSettings.Password); // The "Save" method will apply our signature to the output document at this time. doc.Save(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignatureTimestamp.pdf", options); //ExEnd Assert.False(FileFormatUtil.DetectFileFormat(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignatureTimestamp.pdf").HasDigitalSignature); TestUtil.FileContainsString("6 0 obj\r\n" + "<</Type /Annot/Subtype /Widget/FT /Sig/DR <<>>/F 132/Rect [0 0 0 0]/V 7 0 R/P 4 0 R/T(þÿ\0A\0s\0p\0o\0s\0e\0D\0i\0g\0i\0t\0a\0l\0S\0i\0g\0n\0a\0t\0u\0r\0e)/AP <</N 8 0 R>>>>", ArtifactsDir + "PdfSaveOptions.PdfDigitalSignatureTimestamp.pdf"); #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.PdfDigitalSignatureTimestamp.pdf"); Assert.False(pdfDocument.Form.SignaturesExist); SignatureField signatureField = (SignatureField)pdfDocument.Form[1]; Assert.AreEqual("AsposeDigitalSignature", signatureField.FullName); Assert.AreEqual("AsposeDigitalSignature", signatureField.PartialName); Assert.AreEqual(typeof(Aspose.Pdf.Forms.PKCS7), signatureField.Signature.GetType()); Assert.AreEqual(new DateTime(1, 1, 1, 0, 0, 0), signatureField.Signature.Date); Assert.AreEqual("þÿ\0M\0o\0r\0z\0a\0l\0.\0M\0e", signatureField.Signature.Authority); Assert.AreEqual("þÿ\0A\0s\0p\0o\0s\0e\0 \0O\0f\0f\0i\0c\0e", signatureField.Signature.Location); Assert.AreEqual("þÿ\0T\0e\0s\0t\0 \0S\0i\0g\0n\0i\0n\0g", signatureField.Signature.Reason); Assert.Null(signatureField.Signature.TimestampSettings); #endif } [TestCase(EmfPlusDualRenderingMode.Emf)] [TestCase(EmfPlusDualRenderingMode.EmfPlus)] [TestCase(EmfPlusDualRenderingMode.EmfPlusWithFallback)] public void RenderMetafile(EmfPlusDualRenderingMode renderingMode) { //ExStart //ExFor:EmfPlusDualRenderingMode //ExFor:MetafileRenderingOptions.EmfPlusDualRenderingMode //ExFor:MetafileRenderingOptions.UseEmfEmbeddedToWmf //ExSummary:Shows how to configure Enhanced Windows Metafile-related rendering options when saving to PDF. Document doc = new Document(MyDir + "EMF.docx"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Set the "EmfPlusDualRenderingMode" property to "EmfPlusDualRenderingMode.Emf" // to only render the EMF part of an EMF+ dual metafile. // Set the "EmfPlusDualRenderingMode" property to "EmfPlusDualRenderingMode.EmfPlus" to // to render the EMF+ part of an EMF+ dual metafile. // Set the "EmfPlusDualRenderingMode" property to "EmfPlusDualRenderingMode.EmfPlusWithFallback" // to render the EMF+ part of an EMF+ dual metafile if all of the EMF+ records are supported. // Otherwise, Aspose.Words will render the EMF part. saveOptions.MetafileRenderingOptions.EmfPlusDualRenderingMode = renderingMode; // Set the "UseEmfEmbeddedToWmf" property to "true" to render embedded EMF data // for metafiles that we can render as vector graphics. saveOptions.MetafileRenderingOptions.UseEmfEmbeddedToWmf = true; doc.Save(ArtifactsDir + "PdfSaveOptions.RenderMetafile.pdf", saveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.RenderMetafile.pdf"); switch (renderingMode) { case EmfPlusDualRenderingMode.Emf: case EmfPlusDualRenderingMode.EmfPlusWithFallback: Assert.AreEqual(0, pdfDocument.Pages[1].Resources.Images.Count); TestUtil.FileContainsString("4 0 obj\r\n" + "<</Type /Page/Parent 3 0 R/Contents 5 0 R/MediaBox [0 0 595.29998779 841.90002441]/Resources<</Font<</FAAAAH 7 0 R/FAAABA 10 0 R/FAAABD 13 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.RenderMetafile.pdf"); break; case EmfPlusDualRenderingMode.EmfPlus: Assert.AreEqual(1, pdfDocument.Pages[1].Resources.Images.Count); TestUtil.FileContainsString("4 0 obj\r\n" + "<</Type /Page/Parent 3 0 R/Contents 5 0 R/MediaBox [0 0 595.29998779 841.90002441]/Resources<</Font<</FAAAAH 7 0 R/FAAABB 11 0 R/FAAABE 14 0 R>>/XObject<</X1 9 0 R>>>>/Group <</Type/Group/S/Transparency/CS/DeviceRGB>>>>", ArtifactsDir + "PdfSaveOptions.RenderMetafile.pdf"); break; } #endif } [Test] public void EncryptionPermissions() { //ExStart //ExFor:PdfEncryptionDetails.#ctor //ExFor:PdfSaveOptions.EncryptionDetails //ExFor:PdfEncryptionDetails.Permissions //ExFor:PdfEncryptionDetails.EncryptionAlgorithm //ExFor:PdfEncryptionDetails.OwnerPassword //ExFor:PdfEncryptionDetails.UserPassword //ExFor:PdfEncryptionAlgorithm //ExFor:PdfPermissions //ExFor:PdfEncryptionDetails //ExSummary:Shows how to set permissions on a saved PDF document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Hello world!"); PdfEncryptionDetails encryptionDetails = new PdfEncryptionDetails("password", string.Empty, PdfEncryptionAlgorithm.RC4_128); // Start by disallowing all permissions. encryptionDetails.Permissions = PdfPermissions.DisallowAll; // Extend permissions to allow the editing of annotations. encryptionDetails.Permissions = PdfPermissions.ModifyAnnotations | PdfPermissions.DocumentAssembly; // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions saveOptions = new PdfSaveOptions(); // Enable encryption via the "EncryptionDetails" property. saveOptions.EncryptionDetails = encryptionDetails; // When we open this document, we will need to provide the password before accessing its contents. doc.Save(ArtifactsDir + "PdfSaveOptions.EncryptionPermissions.pdf", saveOptions); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument; Assert.Throws<InvalidPasswordException>(() => pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EncryptionPermissions.pdf")); pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.EncryptionPermissions.pdf", "password"); TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages[1].Accept(textAbsorber); Assert.AreEqual("Hello world!", textAbsorber.Text); #endif } [TestCase(NumeralFormat.ArabicIndic)] [TestCase(NumeralFormat.Context)] [TestCase(NumeralFormat.EasternArabicIndic)] [TestCase(NumeralFormat.European)] [TestCase(NumeralFormat.System)] public void SetNumeralFormat(NumeralFormat numeralFormat) { //ExStart //ExFor:FixedPageSaveOptions.NumeralFormat //ExFor:NumeralFormat //ExSummary:Shows how to set the numeral format used when saving to PDF. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Font.LocaleId = new CultureInfo("ar-AR").LCID; builder.Writeln("1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 50, 100"); // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Set the "NumeralFormat" property to "NumeralFormat.ArabicIndic" to // use glyphs from the U+0660 to U+0669 range as numbers. // Set the "NumeralFormat" property to "NumeralFormat.Context" to // look up the locale to determine what number of glyphs to use. // Set the "NumeralFormat" property to "NumeralFormat.EasternArabicIndic" to // use glyphs from the U+06F0 to U+06F9 range as numbers. // Set the "NumeralFormat" property to "NumeralFormat.European" to use european numerals. // Set the "NumeralFormat" property to "NumeralFormat.System" to determine the symbol set from regional settings. options.NumeralFormat = numeralFormat; doc.Save(ArtifactsDir + "PdfSaveOptions.SetNumeralFormat.pdf", options); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.SetNumeralFormat.pdf"); TextFragmentAbsorber textAbsorber = new TextFragmentAbsorber(); pdfDocument.Pages[1].Accept(textAbsorber); switch (numeralFormat) { case NumeralFormat.European: Assert.AreEqual("1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 50, 100", textAbsorber.Text); break; case NumeralFormat.ArabicIndic: Assert.AreEqual(", ٢, ٣, ٤, ٥, ٦, ٧, ٨, ٩, ١٠, ٥٠, ١١٠٠", textAbsorber.Text); break; case NumeralFormat.EasternArabicIndic: Assert.AreEqual("۱۰۰ ,۵۰ ,۱۰ ,۹ ,۸ ,۷ ,۶ ,۵ ,۴ ,۳ ,۲ ,۱", textAbsorber.Text); break; } #endif } [Test] public void ExportPageSet() { //ExStart //ExFor:FixedPageSaveOptions.PageSet //ExSummary:Shows how to export Odd pages from the document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); for (int i = 0; i < 5; i++) { builder.Writeln($"Page {i + 1} ({(i % 2 == 0 ? "odd" : "even")})"); if (i < 4) builder.InsertBreak(BreakType.PageBreak); } // Create a "PdfSaveOptions" object that we can pass to the document's "Save" method // to modify how that method converts the document to .PDF. PdfSaveOptions options = new PdfSaveOptions(); // Below are three PageSet properties that we can use to filter out a set of pages from // our document to save in an output PDF document based on the parity of their page numbers. // 1 - Save only the even-numbered pages: options.PageSet = PageSet.Even; doc.Save(ArtifactsDir + "PdfSaveOptions.ExportPageSet.Even.pdf", options); // 2 - Save only the odd-numbered pages: options.PageSet = PageSet.Odd; doc.Save(ArtifactsDir + "PdfSaveOptions.ExportPageSet.Odd.pdf", options); // 3 - Save every page: options.PageSet = PageSet.All; doc.Save(ArtifactsDir + "PdfSaveOptions.ExportPageSet.All.pdf", options); //ExEnd #if NET462 || NETCOREAPP2_1 || JAVA Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ExportPageSet.Even.pdf"); TextAbsorber textAbsorber = new TextAbsorber(); pdfDocument.Pages.Accept(textAbsorber); Assert.AreEqual("Page 2 (even)\r\n" + "Page 4 (even)", textAbsorber.Text); pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ExportPageSet.Odd.pdf"); textAbsorber = new TextAbsorber(); pdfDocument.Pages.Accept(textAbsorber); Assert.AreEqual("Page 1 (odd)\r\n" + "Page 3 (odd)\r\n" + "Page 5 (odd)", textAbsorber.Text); pdfDocument = new Aspose.Pdf.Document(ArtifactsDir + "PdfSaveOptions.ExportPageSet.All.pdf"); textAbsorber = new TextAbsorber(); pdfDocument.Pages.Accept(textAbsorber); Assert.AreEqual("Page 1 (odd)\r\n" + "Page 2 (even)\r\n" + "Page 3 (odd)\r\n" + "Page 4 (even)\r\n" + "Page 5 (odd)", textAbsorber.Text); #endif } } }
{ "content_hash": "15c730ecbae36dda74f6961328aa268a", "timestamp": "", "source": "github", "line_count": 2415, "max_line_length": 272, "avg_line_length": 51.924223602484474, "alnum_prop": 0.6283802642806446, "repo_name": "aspose-words/Aspose.Words-for-.NET", "id": "8f7daeeb58f3e3ccbcf004b613ed160122f10054", "size": "125463", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Examples/ApiExamples/ApiExamples.Xamarin/Examples/ExPdfSaveOptions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "113189" }, { "name": "C#", "bytes": "935653" }, { "name": "CSS", "bytes": "20447" }, { "name": "HTML", "bytes": "200130" }, { "name": "JavaScript", "bytes": "179162" }, { "name": "PHP", "bytes": "4795" }, { "name": "Rich Text Format", "bytes": "15884" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyToolBar"> <attr name="showSearchView" format="boolean"/> <attr name="leftButtonIcon" format="reference"/> <attr name="rightButtonIcon" format="reference"/> <attr name="myTitle" format="string"/> </declare-styleable> <declare-styleable name="MySettingView"> <attr name="showIndicate" format="boolean"/> <attr name="showRightImage" format="boolean"/> <attr name="showDotImage" format="boolean"/> <attr name="showRightTv" format="boolean"/> <attr name="leftTvText" format="string"/> <attr name="rightTvText" format="string"/> <attr name="ringhtTvTextColor" format="reference"/> <attr name="rightImageIcon" format="reference"/> </declare-styleable> <declare-styleable name="TabTitleView"> <attr name="showRightTextView" format="boolean"/> <attr name="leftImageIcon" format="reference"/> <attr name="rightTvColor" format="reference"/> <attr name="titleText" format="string"/> <attr name="rightText" format="string"/> </declare-styleable> <!--qrcode--> <declare-styleable name="qr_ViewfinderView"> <attr name="qr_angleColor" format="color"/> <attr name="qr_hint" format="string"/> <attr name="qr_textHintColor" format="color"/> <attr name="qr_errorHint" format="string"/> <attr name="qr_textErrorHintColor" format="color"/> <attr name="qr_offsetX" format="integer"/> <attr name="qr_offsetY" format="integer"/> <attr name="qr_showPossiblePoint" format="boolean"/> </declare-styleable> </resources>
{ "content_hash": "b7aca8ac5527ba17d636103db76472c4", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 64, "avg_line_length": 38.297872340425535, "alnum_prop": 0.5988888888888889, "repo_name": "yiwent/Mobike", "id": "53962f6717aa3ea5c29a126cb3f1ded8870e7fcb", "size": "1800", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values/attrs.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1131259" } ], "symlink_target": "" }
require 'spec_helper' RSpec.describe Alchemy::PagesController, 'OnPageLayout mixin', type: :controller do routes { Alchemy::Engine.routes } before(:all) do ApplicationController.send(:extend, Alchemy::OnPageLayout) end let(:page) { create(:alchemy_page, :public, page_layout: 'standard') } describe '.on_page_layout' do context 'with :all as argument for page_layout' do before do ApplicationController.class_eval do on_page_layout(:all) do @on_all_layouts = @page.page_layout end end end context "for show action" do %w(standard news).each do |page_layout| it "runs callback on #{page_layout} layout" do page = create(:alchemy_page, :public, page_layout: page_layout) get :show, params: {urlname: page.urlname} expect(assigns(:on_all_layouts)).to eq(page_layout) end end end context "for index action" do %w(standard news).each do |page_layout| it "runs callback on #{page_layout} layout" do create(:alchemy_page, :language_root, page_layout: page_layout) get :index expect(assigns(:on_all_layouts)).to eq(page_layout) end end end end context 'with :standard as argument for page_layout' do before do ApplicationController.class_eval do on_page_layout(:standard) do @successful_for_standard = true end end end context 'and page having standard layout' do context "for show action" do let(:page) { create(:alchemy_page, :public, page_layout: 'standard') } it 'runs the callback' do get :show, params: {urlname: page.urlname} expect(assigns(:successful_for_standard)).to eq(true) end end context "for index action" do let!(:page) { create(:alchemy_page, :language_root, page_layout: 'standard') } it 'runs the callback' do get :index expect(assigns(:successful_for_standard)).to eq(true) end end end context 'and page not having standard layout' do let(:page) { create(:alchemy_page, :public, page_layout: 'news') } context "for show action" do it "doesn't run the callback" do get :show, params: {urlname: page.urlname} expect(assigns(:successful_for_standard)).to eq(nil) end end context "for index action" do let!(:page) { create(:alchemy_page, :language_root, page_layout: 'news') } it "doesn't run the callback" do get :index expect(assigns(:successful_for_standard)).to eq(nil) end end end end context 'when defining two callbacks for different page layouts' do context "for show action" do before do ApplicationController.class_eval do on_page_layout(:standard) do @urlname = @page.urlname end on_page_layout(:news) do @urlname = @page.urlname end end end %w(standard news).each do |page_layout| it "runs both callbacks for #{page_layout} layout" do page = create(:alchemy_page, :public, page_layout: page_layout) get :show, params: {urlname: page.urlname} expect(assigns(:urlname)).to eq(page.urlname) end end end context "for index action" do before do ApplicationController.class_eval do on_page_layout(:standard) do @page_layout = @page.page_layout end on_page_layout(:news) do @page_layout = @page.page_layout end end end %w(standard news).each do |page_layout| it "runs both callbacks on #{page_layout} layout" do create(:alchemy_page, :language_root, page_layout: page_layout) get :index expect(assigns(:page_layout)).to eq(page_layout) end end end end context 'when defining two callbacks for the same page_layout' do before do ApplicationController.class_eval do on_page_layout(:standard) do @successful_for_standard_first = true end on_page_layout(:standard) do @successful_for_standard_second = true end end end context "for show action" do it 'runs both callbacks' do get :show, params: {urlname: page.urlname} expect(assigns(:successful_for_standard_first)).to eq(true) expect(assigns(:successful_for_standard_second)).to eq(true) end end context "for index action" do let!(:page) { create(:alchemy_page, :language_root, page_layout: 'standard') } it 'runs both callbacks' do get :index expect(assigns(:successful_for_standard_first)).to eq(true) expect(assigns(:successful_for_standard_second)).to eq(true) end end end context 'when block is given' do before do ApplicationController.class_eval do on_page_layout :standard do @successful_for_callback_method = true end end end context 'for show action' do it 'evaluates the given block' do get :show, params: {urlname: page.urlname} expect(assigns(:successful_for_callback_method)).to eq(true) end end context 'for index action' do let!(:page) { create(:alchemy_page, :language_root, page_layout: 'standard') } it 'evaluates the given block' do get :index expect(assigns(:successful_for_callback_method)).to eq(true) end end end context 'when callback method name is given' do before do ApplicationController.class_eval do on_page_layout :standard, :run_method def run_method @successful_for_callback_method = true end end end context 'for show action' do it 'runs the given callback method' do get :show, params: {urlname: page.urlname} expect(assigns(:successful_for_callback_method)).to eq(true) end end context 'for index action' do let!(:page) { create(:alchemy_page, :language_root, page_layout: 'standard') } it 'runs the given callback method' do get :index expect(assigns(:successful_for_callback_method)).to eq(true) end end end context 'when neither callback method name nor block given' do it 'raises an ArgumentError' do expect do ApplicationController.class_eval do on_page_layout :standard end end.to raise_error(ArgumentError) end end context 'when passing two page_layouts for a callback' do before do ApplicationController.class_eval do on_page_layout([:standard, :news]) do @successful = @page.page_layout end end end %w(standard news).each do |page_layout| it 'evaluates the given callback on both page_layouts for show action' do page = create(:alchemy_page, :public, page_layout: page_layout) get :show, params: {urlname: page.urlname} expect(assigns(:successful)).to eq(page_layout) end end %w(standard news).each do |page_layout| it 'evaluates the given callback on both page_layouts for index action' do create(:alchemy_page, :language_root, page_layout: page_layout) get :index expect(assigns(:successful)).to eq(page_layout) end end end end end RSpec.describe ApplicationController, 'OnPageLayout mixin', type: :controller do before(:all) do ApplicationController.send(:extend, Alchemy::OnPageLayout) end controller do def index @another_controller = true head :ok end end context 'in another controller' do before do ApplicationController.class_eval do on_page_layout(:standard) do @successful_for_another_controller = true end end end it 'callback does not run' do get :index expect(assigns(:another_controller)).to eq(true) expect(assigns(:successful_for_another_controller)).to eq(nil) end end end RSpec.describe Alchemy::Admin::PagesController, 'OnPageLayout mixin', type: :controller do routes { Alchemy::Engine.routes } before(:all) do ApplicationController.send(:extend, Alchemy::OnPageLayout) end context 'in admin/pages_controller' do before do ApplicationController.class_eval do on_page_layout(:standard) do @successful_for_alchemy_admin_pages_controller = true end end authorize_user(:as_admin) end context "for show action" do let(:page) { create(:alchemy_page, page_layout: 'standard') } it 'callback also runs' do get :show, params: {id: page.id} expect(assigns(:successful_for_alchemy_admin_pages_controller)).to be(true) end end context "for index action" do it 'does not run callback' do get :index expect(assigns(:successful_for_alchemy_admin_pages_controller)).to be(nil) end end end after(:all) do Alchemy::OnPageLayout.instance_variable_set(:@callbacks, nil) end end
{ "content_hash": "e244b1314cd9f8b38e18dad8794a472e", "timestamp": "", "source": "github", "line_count": 334, "max_line_length": 90, "avg_line_length": 28.904191616766468, "alnum_prop": 0.5931220219598095, "repo_name": "mtomov/alchemy_cms", "id": "b997ef79eae7642bea3a85446375a404e7b3d348", "size": "9654", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spec/controllers/alchemy/on_page_layout_mixin_spec.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "178306" }, { "name": "CoffeeScript", "bytes": "87907" }, { "name": "HTML", "bytes": "174815" }, { "name": "JavaScript", "bytes": "11380" }, { "name": "Ruby", "bytes": "1126064" }, { "name": "Shell", "bytes": "157" } ], "symlink_target": "" }
package com.lightbend.lagom.internal.scaladsl.persistence import akka.actor.Actor import akka.actor.ActorLogging import akka.actor.Props import akka.actor.Status import akka.persistence.query.Offset import akka.stream.scaladsl.Keep import akka.stream.scaladsl.RestartSource import akka.stream.scaladsl.Sink import akka.stream.scaladsl.Source import akka.stream.KillSwitch import akka.stream.KillSwitches import akka.stream.Materializer import akka.util.Timeout import akka.Done import akka.NotUsed import akka.stream.scaladsl.Flow import com.lightbend.lagom.internal.persistence.ReadSideConfig import com.lightbend.lagom.internal.persistence.cluster.ClusterStartupTask import com.lightbend.lagom.scaladsl.persistence._ import scala.concurrent.Future private[lagom] object ReadSideActor { def props[Event <: AggregateEvent[Event]]( tagName: String, config: ReadSideConfig, clazz: Class[Event], globalPrepareTask: ClusterStartupTask, eventStreamFactory: (AggregateEventTag[Event], Offset) => Source[EventStreamElement[Event], NotUsed], processor: () => ReadSideProcessor[Event] )(implicit mat: Materializer) = Props( new ReadSideActor[Event]( tagName, config, clazz, globalPrepareTask, eventStreamFactory, processor ) ) case object Prepare case object Start } /** * Read side actor */ private[lagom] class ReadSideActor[Event <: AggregateEvent[Event]]( tagName: String, config: ReadSideConfig, clazz: Class[Event], globalPrepareTask: ClusterStartupTask, eventStreamFactory: (AggregateEventTag[Event], Offset) => Source[EventStreamElement[Event], NotUsed], processor: () => ReadSideProcessor[Event] )(implicit mat: Materializer) extends Actor with ActorLogging { import ReadSideActor._ import akka.pattern.pipe import context.dispatcher /** Switch used to terminate the on-going stream when this actor is stopped.*/ private var shutdown: Option[KillSwitch] = None override def postStop: Unit = { shutdown.foreach(_.shutdown()) } override def preStart(): Unit = { super.preStart() implicit val timeout: Timeout = Timeout(config.globalPrepareTimeout) globalPrepareTask .askExecute() .map { _ => Start } .pipeTo(self) } def receive: Receive = { case Start => val tag = new AggregateEventTag(clazz, tagName) val backOffSource: Source[Done, NotUsed] = RestartSource.withBackoff( config.minBackoff, config.maxBackoff, config.randomBackoffFactor ) { () => val handler: ReadSideProcessor.ReadSideHandler[Event] = processor().buildHandler() val futureOffset: Future[Offset] = handler.prepare(tag) Source .fromFuture(futureOffset) .initialTimeout(config.offsetTimeout) .flatMapConcat { offset => val eventStreamSource = eventStreamFactory(tag, offset) val usersFlow = handler.handle() eventStreamSource.via(usersFlow) } } val (killSwitch, streamDone) = backOffSource .viaMat(KillSwitches.single)(Keep.right) .toMat(Sink.ignore)(Keep.both) .run() shutdown = Some(killSwitch) streamDone.pipeTo(self) case Done => // This `Done` is materialization of the `Sink.ignore` above. throw new IllegalStateException("Stream terminated when it shouldn't") case Status.Failure(cause) => // Crash if the globalPrepareTask or the event stream fail // This actor will be restarted by WorkerCoordinator throw cause } }
{ "content_hash": "c45660b00261a78a6966aad69db9fb35", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 107, "avg_line_length": 29.76, "alnum_prop": 0.685752688172043, "repo_name": "ignasi35/lagom", "id": "16b8525422762ccc9e7596d01ef832880b8345c8", "size": "3796", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "persistence/scaladsl/src/main/scala/com/lightbend/lagom/internal/scaladsl/persistence/ReadSideActor.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "348" }, { "name": "HTML", "bytes": "559" }, { "name": "Java", "bytes": "1029007" }, { "name": "JavaScript", "bytes": "48" }, { "name": "Perl", "bytes": "1102" }, { "name": "Roff", "bytes": "6976" }, { "name": "Scala", "bytes": "1945802" }, { "name": "Shell", "bytes": "8427" } ], "symlink_target": "" }
/* * Test parsing of a long string regexp: minimal features used by * the regexp but exercises buffer handling for parsing and emitting * regexp bytecode. Regexp is not executed. */ if (typeof print !== 'function') { print = console.log; } function test() { var txt = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'; var i; for (i = 0; i < 10; i++) { txt = txt + txt; } var regexpdata = '/' + txt + '/'; // periods will be wildcards print(regexpdata.length); for (i = 0; i < 100; i++) { void new RegExp(regexpdata); void new RegExp(regexpdata); void new RegExp(regexpdata); void new RegExp(regexpdata); void new RegExp(regexpdata); void new RegExp(regexpdata); void new RegExp(regexpdata); void new RegExp(regexpdata); void new RegExp(regexpdata); void new RegExp(regexpdata); } } try { test(); } catch (e) { print(e.stack || e); throw e; }
{ "content_hash": "0b4ca681b66ec4136a61aa1059ba02d2", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 462, "avg_line_length": 35.61538461538461, "alnum_prop": 0.6587473002159827, "repo_name": "harold-b/duktape", "id": "91a191c60b25d017fc397ae895206858ad7bc19e", "size": "1389", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "tests/perf/test-regexp-string-parse.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3648567" }, { "name": "C++", "bytes": "35955" }, { "name": "CSS", "bytes": "32873" }, { "name": "CoffeeScript", "bytes": "130" }, { "name": "HTML", "bytes": "4384224" }, { "name": "Java", "bytes": "3043" }, { "name": "JavaScript", "bytes": "10116953" }, { "name": "Lua", "bytes": "34905" }, { "name": "Makefile", "bytes": "62975" }, { "name": "Perl", "bytes": "177" }, { "name": "Perl6", "bytes": "33007" }, { "name": "Python", "bytes": "226061" }, { "name": "Ruby", "bytes": "28928" }, { "name": "Shell", "bytes": "11275" } ], "symlink_target": "" }
<?php $installer = $this; /* @var $installer Mage_Core_Model_Resource_Setup */ $installer->startSetup(); $installer->getConnection()->addConstraint('FK_REVIEW_STORE_REVIEW', $installer->getTable('review/review_store'), 'review_id', $installer->getTable('review/review'), 'review_id', 'CASCADE', 'CASCADE', true); $installer->endSetup();
{ "content_hash": "e3ec72a40d25a408fbb232f6bd0064f2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 68, "avg_line_length": 27.153846153846153, "alnum_prop": 0.6827195467422096, "repo_name": "namkingkong/org.namma.magento.learning", "id": "c572a441ea9ab604dce8624171e05f90e9af7612", "size": "1308", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "app/code/core/Mage/Review/sql/review_setup/mysql4-upgrade-0.7.3-0.7.4.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "19946" }, { "name": "CSS", "bytes": "1655613" }, { "name": "JavaScript", "bytes": "1036085" }, { "name": "PHP", "bytes": "44383675" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Ruby", "bytes": "288" }, { "name": "Shell", "bytes": "1753" }, { "name": "XSLT", "bytes": "2066" } ], "symlink_target": "" }
import requests import webbrowser import re import os import sys from bs4 import BeautifulSoup BASE_URL = "http://www.reddit.com/r/dailyprogrammer/new/" def get_soup(url): return BeautifulSoup(requests.get(url).text) def get_page_challenges(soup): return [challenge for challenge in soup.find_all('div', class_='thing')] def get_completed_challenges(): regex = re.compile("^challenge_(\d{1,}).py$") return [f[10:-3] for f in os.listdir(os.getcwd()) if regex.match(f)] def build_challenges(page_challenges): challenges = [] regex = re.compile("^.{21}#(\d{1,}) \[([a-zA-Z]{4,12})\] (.+)$") for page_challenge in page_challenges: title = page_challenge.find('a', class_='title') result = regex.match(title.text) if result is None: continue challenge = { 'fullname': page_challenge.get('data-fullname'), 'name': result.group(3), 'number': result.group(1), 'url': title.get('href'), 'difficulty': result.group(2).lower(), 'title': result.group(0) } challenges.append(challenge) return challenges def main(): if len(sys.argv) != 2: print "Usage: new_challenge.py <difficulty>" exit(-1) difficulty = sys.argv[1] if difficulty.lower() not in ['easy', 'intermediate', 'hard']: print "Invalid type of difficulty. "\ "Available choices: easy, intermediate or hard." exit(-1) # process completed files and get new challenges from reddit completed = get_completed_challenges() page_challenges = get_page_challenges(get_soup(BASE_URL)) # chooses the first one that hasn't been completed while True: challenges = build_challenges(page_challenges) if not challenges: print "No challenges found!" exit() for c in challenges: if c['number'] not in completed and c['difficulty'] == difficulty: print c webbrowser.open_new("".join([ "http://www.reddit.com", c['url']])) exit() # no challenges available in the current page, go to next page page_challenges = get_page_challenges(get_soup("".join( [BASE_URL, "?count=", str(len(page_challenges)), "&after=", challenges[len(challenges)-1]['fullname'] ]))) if __name__ == "__main__": main()
{ "content_hash": "7a233d7840dfdb4d7821cdfc560fa288", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 78, "avg_line_length": 26.79787234042553, "alnum_prop": 0.5712584358872569, "repo_name": "miguelgazela/reddit-dailyprogrammer", "id": "6664ca5e55366a04dbc498a69eaf78433382047d", "size": "2542", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "new_challenge.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "8184" } ], "symlink_target": "" }
module.exports = { verbose: true, coveragePathIgnorePatterns: ['./lib/'], testPathIgnorePatterns: ['./lib/'] };
{ "content_hash": "1b2eb0c5611d6347f018d5d2eb5db7a5", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 43, "avg_line_length": 24.8, "alnum_prop": 0.6290322580645161, "repo_name": "ZakZubair/currency-map-country", "id": "aa60cc9c4ff5c8827192104b593a652c4932ef74", "size": "124", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jest.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "40155" } ], "symlink_target": "" }
package com.proyecti.twincoders.twinpush.operations; import com.proyecti.twincoders.twinpush.interfaz.TwinPushConnection; import com.proyecti.twincoders.twinpush.operations.devices.TwinPushDevicesOperations; import com.proyecti.twincoders.twinpush.operations.devices.TwinPushDevicesOperationsImpl; import com.proyecti.twincoders.twinpush.operations.notifications.TwinPushNotificationsOperations; import com.proyecti.twincoders.twinpush.operations.notifications.TwinPushNotificationsOperationsImpl; import com.proyecti.twincoders.twinpush.operations.statistics.TwinPushStatisticsOperations; import com.proyecti.twincoders.twinpush.operations.statistics.TwinPushStatisticsOperationsImpl; public final class TwinPushConnectionImpl implements TwinPushConnection { private String host; private String apiVersion; private String token; private TwinPushStatisticsOperations twinPushStatisticsOperations; private TwinPushDevicesOperations twinPushDevicesOperations; private TwinPushNotificationsOperations twinPushNotificationsOperations; public TwinPushConnectionImpl(String host, String apiVersion, String token) { super(); this.host = host; this.apiVersion = apiVersion; this.token = token; this.twinPushStatisticsOperations = new TwinPushStatisticsOperationsImpl(token); this.twinPushDevicesOperations = new TwinPushDevicesOperationsImpl(token); this.twinPushNotificationsOperations = new TwinPushNotificationsOperationsImpl(token); } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getApiVersion() { return apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public TwinPushStatisticsOperations getTwinPushStatisticsOperations() { return twinPushStatisticsOperations; } public TwinPushDevicesOperations getTwinPushDevicesOperations() { return twinPushDevicesOperations; } public TwinPushNotificationsOperations getTwinPushNotificationsOperations() { return twinPushNotificationsOperations; } }
{ "content_hash": "e73ca146724b70547eb4d4d40f1562a2", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 101, "avg_line_length": 32.417910447761194, "alnum_prop": 0.8328729281767956, "repo_name": "ProyecTI/twinpush-spring-bean", "id": "dae7f8e590465ee07b6278ce6edc06494f58c7c0", "size": "2172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/proyecti/twincoders/twinpush/operations/TwinPushConnectionImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "68147" } ], "symlink_target": "" }
'use strict'; // TODO: use pooled connections var fs = require('fs'); var path = require('path'); var sock = require('./line_socket'); var smtp_regexp = /^([0-9]{3})([ -])(.*)/; exports.register = function () { var plugin = this; plugin.load_avg_ini(); }; exports.load_avg_ini = function () { var plugin = this; plugin.cfg = plugin.config.get('avg.ini', { booleans: [ '+defer.timeout', '+defer.error', ], }, function () { plugin.load_avg_ini(); }); }; exports.get_tmp_file = function (transaction) { var plugin = this; var tmpdir = plugin.cfg.main.tmpdir || '/tmp'; return path.join(tmpdir, transaction.uuid + '.tmp'); }; exports.hook_data_post = function (next, connection) { var plugin = this; if (!connection.transaction) return next(); var tmpfile = plugin.get_tmp_file(connection.transaction); var ws = fs.createWriteStream(tmpfile); ws.once('error', function(err) { connection.results.add(plugin, { err: 'Error writing temporary file: ' + err.message }); if (!plugin.cfg.defer.error) return next(); return next(DENYSOFT, 'Virus scanner error (AVG)'); }); ws.once('close', function() { var start_time = Date.now(); var socket = new sock.Socket(); socket.setTimeout((plugin.cfg.main.connect_timeout || 10) * 1000); var connected = false; var command = 'connect'; var response = []; var do_next = function (code, msg) { fs.unlink(tmpfile, function(){}); return next(code, msg); }; socket.send_command = function (cmd, data) { var line = cmd + (data ? (' ' + data) : ''); connection.logprotocol(plugin, '> ' + line); this.write(line + '\r\n'); command = cmd.toLowerCase(); response = []; }; socket.on('timeout', function () { var msg = (connected ? 'connection' : 'session') + ' timed out'; connection.results.add(plugin, { err: msg }); if (!plugin.cfg.defer.timeout) return do_next(); return do_next(DENYSOFT, 'Virus scanner timeout (AVG)'); }); socket.on('error', function (err) { connection.results.add(plugin, { err: err.message }); if (!plugin.cfg.defer.error) return do_next(); return do_next(DENYSOFT, 'Virus scanner error (AVG)'); }); socket.on('connect', function () { connected = true; this.setTimeout((plugin.cfg.main.session_timeout || 30) * 1000); }); socket.on('line', function (line) { var matches = smtp_regexp.exec(line); connection.logprotocol(plugin, '< ' + line); if (!matches) { connection.results.add(plugin, { err: 'Unrecognized response: ' + line, }); socket.end(); if (!plugin.cfg.defer.error) return do_next(); return do_next(DENYSOFT, 'Virus scanner error (AVG)'); } var code = matches[1]; var cont = matches[2]; var rest = matches[3]; response.push(rest); if (cont !== ' ') { return; } switch (command) { case 'connect': if (code !== '220') { // Error connection.results.add(plugin, { err: 'Unrecognized response: ' + line, }); if (!plugin.cfg.defer.timeout) return do_next(); return do_next(DENYSOFT, 'Virus scanner error (AVG)'); } else { socket.send_command('SCAN', tmpfile); } break; case 'scan': var end_time = Date.now(); var elapsed = end_time - start_time; connection.loginfo(plugin, 'time=' + elapsed + 'ms ' + 'code=' + code + ' ' + 'response="' + response.join(' ') + '"'); // Check code switch (code) { case '200': // 200 ok // Message did not contain a virus connection.results.add(plugin, { pass: 'clean' }); socket.send_command('QUIT'); return do_next(); case '403': // File 'eicar.com', 'Virus identified EICAR_Test' connection.results.add(plugin, { fail: response.join(' ') }); socket.send_command('QUIT'); return do_next(DENY, response.join(' ')); default: // Any other result is an error connection.results.add(plugin, { err: 'Bad response: ' + response.join(' ') }); } socket.send_command('QUIT'); if (!plugin.cfg.defer.error) return do_next(); return do_next(DENYSOFT, 'Virus scanner error (AVG)'); case 'quit': socket.end(); break; default: throw new Error('Unknown command: ' + command); } }); socket.connect((plugin.cfg.main.port || 54322), plugin.cfg.main.host); }); connection.transaction.message_stream.pipe(ws, { line_endings: '\r\n' }); };
{ "content_hash": "00d67aee5b25aa265a1a7b502a6d57a8", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 78, "avg_line_length": 36.358024691358025, "alnum_prop": 0.4536502546689304, "repo_name": "slattery/Haraka", "id": "4b97deb87abcb71b4bf3cc9ad2a7809ef05ab379", "size": "5917", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "plugins/avg.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4475" }, { "name": "HTML", "bytes": "4819" }, { "name": "JavaScript", "bytes": "1344813" }, { "name": "Perl", "bytes": "1852" }, { "name": "Shell", "bytes": "7294" } ], "symlink_target": "" }
// OCMockito by Jon Reid, http://qualitycoding.org/about/ // Copyright 2015 Jonathan M. Reid. See LICENSE.txt #import "MKTBaseMockObject.h" /*! * @abstract Mock object of a given class. */ @interface MKTObjectMock : MKTBaseMockObject - (instancetype)initWithClass:(Class)aClass; @end
{ "content_hash": "596d0e634c600c7a1a36fd3b58d3f43e", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 58, "avg_line_length": 20.928571428571427, "alnum_prop": 0.7337883959044369, "repo_name": "HockeyWX/HockeySDK-iOSDemo-Swift", "id": "536e8cc86edd2f8c5bf403b6320a8600fd6016bc", "size": "293", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "Vendor/HockeySDK/Support/HockeySDKTests/Vendor/OCMockitoIOS.framework/Versions/A/Headers/MKTObjectMock.h", "mode": "33261", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "229" }, { "name": "Swift", "bytes": "40308" } ], "symlink_target": "" }
import Vue from './instance/vue' import directives from './directives/public/index' import elementDirectives from './directives/element/index' import filters from './filters/index' import { inBrowser } from './util/index' Vue.version = '1.0.11' /** * Vue and every constructor that extends Vue has an * associated options object, which can be accessed during * compilation steps as `this.constructor.options`. * * These can be seen as the default options of every * Vue instance. */ Vue.options = { directives, elementDirectives, filters, transitions: {}, components: {}, partials: {}, replace: true } export default Vue // devtools global hook /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && inBrowser) { if (window.__VUE_DEVTOOLS_GLOBAL_HOOK__) { window.__VUE_DEVTOOLS_GLOBAL_HOOK__.emit('init', Vue) } else if (/Chrome\/\d+/.test(navigator.userAgent)) { console.log( 'Download the Vue Devtools for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ) } }
{ "content_hash": "35ef53c03d47bf4fae844f5bb029c1ff", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 74, "avg_line_length": 25.926829268292682, "alnum_prop": 0.6886171213546566, "repo_name": "mockjs/mockjs.github.com", "id": "1b624e469a6710b5e76742365adedb5bd92cbbdd", "size": "1063", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bower_components/vue/src/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "51371" }, { "name": "HTML", "bytes": "288541" }, { "name": "JavaScript", "bytes": "907294" }, { "name": "Shell", "bytes": "54" } ], "symlink_target": "" }
Article 1606 ---- La délivrance des effets mobiliers s'opère : Ou par la remise de la chose, Ou par la remise des clefs des bâtiments qui les contiennent, Ou même par le seul consentement des parties, si le transport ne peut pas s'en faire au moment de la vente, ou si l'acheteur les avait déjà en son pouvoir à un autre titre.
{ "content_hash": "2866e8fa4552fecf3e0aa88b62183d25", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 80, "avg_line_length": 30.09090909090909, "alnum_prop": 0.7643504531722054, "repo_name": "oneminot/illacceptanything", "id": "79ba3f82ed4f6f3f379d8b6138757f696d2b6c42", "size": "338", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "data/france.code-civil/Livre III/Titre VI/Article 1606.md", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "109" }, { "name": "AppleScript", "bytes": "61" }, { "name": "Arduino", "bytes": "709" }, { "name": "Assembly", "bytes": "2005" }, { "name": "Brainfuck", "bytes": "66542" }, { "name": "C", "bytes": "38598" }, { "name": "C#", "bytes": "55496" }, { "name": "C++", "bytes": "16638" }, { "name": "CMake", "bytes": "235" }, { "name": "CSS", "bytes": "97227" }, { "name": "Clojure", "bytes": "94838" }, { "name": "CoffeeScript", "bytes": "153782" }, { "name": "Common Lisp", "bytes": "1120" }, { "name": "Crystal", "bytes": "7261" }, { "name": "Dart", "bytes": "800" }, { "name": "Eagle", "bytes": "1297646" }, { "name": "Emacs Lisp", "bytes": "60" }, { "name": "Go", "bytes": "19658" }, { "name": "HTML", "bytes": "6432616" }, { "name": "Haskell", "bytes": "100" }, { "name": "JSONiq", "bytes": "536" }, { "name": "Java", "bytes": "14922" }, { "name": "JavaScript", "bytes": "5422014" }, { "name": "Julia", "bytes": "25" }, { "name": "KiCad", "bytes": "321244" }, { "name": "Lua", "bytes": "336811" }, { "name": "Makefile", "bytes": "1019" }, { "name": "OCaml", "bytes": "78" }, { "name": "Objective-C", "bytes": "3260" }, { "name": "PHP", "bytes": "1039" }, { "name": "Python", "bytes": "106335" }, { "name": "Racket", "bytes": "4918" }, { "name": "Ruby", "bytes": "18502" }, { "name": "Rust", "bytes": "42" }, { "name": "Shell", "bytes": "42068" }, { "name": "Swift", "bytes": "12055" }, { "name": "VimL", "bytes": "60880" }, { "name": "Visual Basic", "bytes": "1007" } ], "symlink_target": "" }
// Copyright 2013 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/web_contents/web_contents_android.h" #include <stdint.h> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/android/callback_android.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "base/json/json_writer.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/metrics/user_metrics.h" #include "base/threading/scoped_blocking_call.h" #include "content/browser/android/java/gin_java_bridge_dispatcher_host.h" #include "content/browser/media/media_web_contents_observer.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/web_contents/view_structure_builder_android.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/browser/web_contents/web_contents_view_android.h" #include "content/common/frame.mojom.h" #include "content/public/android/content_jni_headers/WebContentsImpl_jni.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/message_port_provider.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" #include "third_party/blink/public/mojom/input/input_handler.mojom-blink.h" #include "ui/accessibility/ax_assistant_structure.h" #include "ui/accessibility/ax_node_data.h" #include "ui/accessibility/ax_tree_update.h" #include "ui/accessibility/mojom/ax_assistant_structure.mojom.h" #include "ui/android/overscroll_refresh_handler.h" #include "ui/android/window_android.h" #include "ui/gfx/android/java_bitmap.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "url/android/gurl_android.h" #include "url/gurl.h" using base::android::AttachCurrentThread; using base::android::ConvertJavaStringToUTF16; using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF16ToJavaString; using base::android::ConvertUTF8ToJavaString; using base::android::JavaParamRef; using base::android::JavaRef; using base::android::ScopedJavaGlobalRef; using base::android::ScopedJavaLocalRef; using base::android::ToJavaArrayOfStringArray; using base::android::ToJavaArrayOfStrings; using base::android::ToJavaIntArray; namespace content { namespace { // Track all WebContentsAndroid objects here so that we don't deserialize a // destroyed WebContents object. base::LazyInstance<std::unordered_set<WebContentsAndroid*>>::Leaky g_allocated_web_contents_androids = LAZY_INSTANCE_INITIALIZER; void JavaScriptResultCallback(const ScopedJavaGlobalRef<jobject>& callback, base::Value result) { JNIEnv* env = base::android::AttachCurrentThread(); std::string json; base::JSONWriter::Write(result, &json); ScopedJavaLocalRef<jstring> j_json = ConvertUTF8ToJavaString(env, json); Java_WebContentsImpl_onEvaluateJavaScriptResult(env, j_json, callback); } void SmartClipCallback(const ScopedJavaGlobalRef<jobject>& callback, const std::u16string& text, const std::u16string& html, const gfx::Rect& clip_rect) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> j_text = ConvertUTF16ToJavaString(env, text); ScopedJavaLocalRef<jstring> j_html = ConvertUTF16ToJavaString(env, html); Java_WebContentsImpl_onSmartClipDataExtracted( env, j_text, j_html, clip_rect.x(), clip_rect.y(), clip_rect.right(), clip_rect.bottom(), callback); } void CreateJavaAXSnapshot(JNIEnv* env, const ui::AssistantTree* tree, const ui::AssistantNode* node, const JavaRef<jobject>& j_view_structure_node, const JavaRef<jobject>& j_view_structure_builder, bool is_root) { ScopedJavaLocalRef<jstring> j_text = ConvertUTF16ToJavaString(env, node->text); // The (fake) Android java class name. ScopedJavaLocalRef<jstring> j_class = ConvertUTF8ToJavaString(env, node->class_name); bool has_selection = node->selection.has_value(); int sel_start = has_selection ? node->selection->start() : 0; int sel_end = has_selection ? node->selection->end() : 0; int child_count = static_cast<int>(node->children_indices.size()); ViewStructureBuilder_populateViewStructureNode( env, j_view_structure_builder, j_view_structure_node, j_text, has_selection, sel_start, sel_end, node->color, node->bgcolor, node->text_size, node->bold, node->italic, node->underline, node->line_through, j_class, child_count); // Bounding box. ViewStructureBuilder_setViewStructureNodeBounds( env, j_view_structure_builder, j_view_structure_node, is_root, node->rect.x(), node->rect.y(), node->rect.width(), node->rect.height()); // HTML/CSS attributes. ScopedJavaLocalRef<jstring> j_html_tag = ConvertUTF8ToJavaString(env, node->html_tag); ScopedJavaLocalRef<jstring> j_css_display = ConvertUTF8ToJavaString(env, node->css_display); std::vector<std::vector<std::u16string>> html_attrs; for (const auto& attr : node->html_attributes) { html_attrs.push_back( {base::UTF8ToUTF16(attr.first), base::UTF8ToUTF16(attr.second)}); } ScopedJavaLocalRef<jobjectArray> j_attrs = ToJavaArrayOfStringArray(env, html_attrs); ViewStructureBuilder_setViewStructureNodeHtmlInfo( env, j_view_structure_builder, j_view_structure_node, j_html_tag, j_css_display, j_attrs); for (int child_index = 0; child_index < child_count; child_index++) { int child_id = node->children_indices[child_index]; ScopedJavaLocalRef<jobject> j_child = ViewStructureBuilder_addViewStructureNodeChild( env, j_view_structure_builder, j_view_structure_node, child_index); CreateJavaAXSnapshot(env, tree, tree->nodes[child_id].get(), j_child, j_view_structure_builder, false); } if (!is_root) { ViewStructureBuilder_commitViewStructureNode(env, j_view_structure_builder, j_view_structure_node); } } void AddTreeLevelDataToViewStructure( JNIEnv* env, const JavaRef<jobject>& view_structure_root, const JavaRef<jobject>& view_structure_builder, const ui::AXTreeUpdate& ax_tree_update) { const auto& metadata_strings = ax_tree_update.tree_data.metadata; if (metadata_strings.empty()) return; ScopedJavaLocalRef<jobjectArray> j_metadata_strings = ToJavaArrayOfStrings(env, metadata_strings); ViewStructureBuilder_setViewStructureNodeHtmlMetadata( env, view_structure_builder, view_structure_root, j_metadata_strings); } } // namespace // static WebContents* WebContents::FromJavaWebContents( const JavaRef<jobject>& jweb_contents_android) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (jweb_contents_android.is_null()) return NULL; WebContentsAndroid* web_contents_android = reinterpret_cast<WebContentsAndroid*>( Java_WebContentsImpl_getNativePointer(AttachCurrentThread(), jweb_contents_android)); if (!web_contents_android) return NULL; return web_contents_android->web_contents(); } // static static void JNI_WebContentsImpl_DestroyWebContents( JNIEnv* env, jlong jweb_contents_android_ptr) { WebContentsAndroid* web_contents_android = reinterpret_cast<WebContentsAndroid*>(jweb_contents_android_ptr); if (!web_contents_android) return; WebContents* web_contents = web_contents_android->web_contents(); if (!web_contents) return; delete web_contents; } // static ScopedJavaLocalRef<jobject> JNI_WebContentsImpl_FromNativePtr( JNIEnv* env, jlong web_contents_ptr) { WebContentsAndroid* web_contents_android = reinterpret_cast<WebContentsAndroid*>(web_contents_ptr); if (!web_contents_android) return ScopedJavaLocalRef<jobject>(); // Check to make sure this object hasn't been destroyed. if (g_allocated_web_contents_androids.Get().find(web_contents_android) == g_allocated_web_contents_androids.Get().end()) { return ScopedJavaLocalRef<jobject>(); } return web_contents_android->GetJavaObject(); } WebContentsAndroid::WebContentsAndroid(WebContentsImpl* web_contents) : web_contents_(web_contents), navigation_controller_(&(web_contents->GetController())) { g_allocated_web_contents_androids.Get().insert(this); JNIEnv* env = AttachCurrentThread(); obj_.Reset(env, Java_WebContentsImpl_create(env, reinterpret_cast<intptr_t>(this), navigation_controller_.GetJavaObject()) .obj()); } WebContentsAndroid::~WebContentsAndroid() { DCHECK(g_allocated_web_contents_androids.Get().find(this) != g_allocated_web_contents_androids.Get().end()); g_allocated_web_contents_androids.Get().erase(this); for (auto& observer : destruction_observers_) observer.WebContentsAndroidDestroyed(this); Java_WebContentsImpl_clearNativePtr(AttachCurrentThread(), obj_); } base::android::ScopedJavaLocalRef<jobject> WebContentsAndroid::GetJavaObject() { return base::android::ScopedJavaLocalRef<jobject>(obj_); } void WebContentsAndroid::ClearNativeReference(JNIEnv* env) { return web_contents_->ClearWebContentsAndroid(); } void WebContentsAndroid::AddDestructionObserver(DestructionObserver* observer) { destruction_observers_.AddObserver(observer); } void WebContentsAndroid::RemoveDestructionObserver( DestructionObserver* observer) { destruction_observers_.RemoveObserver(observer); } base::android::ScopedJavaLocalRef<jobject> WebContentsAndroid::GetTopLevelNativeWindow(JNIEnv* env) { ui::WindowAndroid* window_android = web_contents_->GetTopLevelNativeWindow(); if (!window_android) return nullptr; return window_android->GetJavaObject(); } void WebContentsAndroid::SetTopLevelNativeWindow( JNIEnv* env, const JavaParamRef<jobject>& jwindow_android) { ui::WindowAndroid* window = ui::WindowAndroid::FromJavaWindowAndroid(jwindow_android); auto* old_window = web_contents_->GetTopLevelNativeWindow(); if (window == old_window) return; auto* view = web_contents_->GetNativeView(); if (old_window) view->RemoveFromParent(); if (window) window->AddChild(view); } void WebContentsAndroid::SetViewAndroidDelegate( JNIEnv* env, const JavaParamRef<jobject>& jview_delegate) { ui::ViewAndroid* view_android = web_contents_->GetView()->GetNativeView(); view_android->SetDelegate(jview_delegate); } ScopedJavaLocalRef<jobject> WebContentsAndroid::GetMainFrame( JNIEnv* env) const { return web_contents_->GetPrimaryMainFrame()->GetJavaRenderFrameHost(); } ScopedJavaLocalRef<jobject> WebContentsAndroid::GetFocusedFrame( JNIEnv* env) const { RenderFrameHostImpl* rfh = web_contents_->GetFocusedFrame(); if (!rfh) return nullptr; return rfh->GetJavaRenderFrameHost(); } ScopedJavaLocalRef<jobject> WebContentsAndroid::GetRenderFrameHostFromId( JNIEnv* env, jint render_process_id, jint render_frame_id) const { RenderFrameHost* rfh = RenderFrameHost::FromID(render_process_id, render_frame_id); if (!rfh) return nullptr; return rfh->GetJavaRenderFrameHost(); } ScopedJavaLocalRef<jobjectArray> WebContentsAndroid::GetAllRenderFrameHosts( JNIEnv* env) const { std::vector<RenderFrameHost*> frames; web_contents_->ForEachRenderFrameHost( [&frames](RenderFrameHostImpl* rfh) { frames.push_back(rfh); }); ScopedJavaLocalRef<jobjectArray> jframes = Java_WebContentsImpl_createRenderFrameHostArray(env, frames.size()); for (size_t i = 0; i < frames.size(); i++) { Java_WebContentsImpl_addRenderFrameHostToArray( env, jframes, i, frames[i]->GetJavaRenderFrameHost()); } return jframes; } ScopedJavaLocalRef<jstring> WebContentsAndroid::GetTitle(JNIEnv* env) const { return base::android::ConvertUTF16ToJavaString(env, web_contents_->GetTitle()); } ScopedJavaLocalRef<jobject> WebContentsAndroid::GetVisibleURL( JNIEnv* env) const { return url::GURLAndroid::FromNativeGURL(env, web_contents_->GetVisibleURL()); } jint WebContentsAndroid::GetVirtualKeyboardMode(JNIEnv* env) const { return static_cast<jint>(web_contents_->GetVirtualKeyboardMode()); } bool WebContentsAndroid::IsLoading(JNIEnv* env) const { return web_contents_->IsLoading(); } bool WebContentsAndroid::ShouldShowLoadingUI(JNIEnv* env) const { return web_contents_->ShouldShowLoadingUI(); } void WebContentsAndroid::DispatchBeforeUnload(JNIEnv* env, bool auto_cancel) { web_contents_->DispatchBeforeUnload(auto_cancel); } void WebContentsAndroid::Stop(JNIEnv* env) { web_contents_->Stop(); } void WebContentsAndroid::Cut(JNIEnv* env) { web_contents_->Cut(); } void WebContentsAndroid::Copy(JNIEnv* env) { web_contents_->Copy(); } void WebContentsAndroid::Paste(JNIEnv* env) { web_contents_->Paste(); } void WebContentsAndroid::PasteAsPlainText(JNIEnv* env) { // Paste as if user typed the characters, which should match current style of // the caret location. web_contents_->PasteAndMatchStyle(); } void WebContentsAndroid::Replace(JNIEnv* env, const JavaParamRef<jstring>& jstr) { web_contents_->Replace(base::android::ConvertJavaStringToUTF16(env, jstr)); } void WebContentsAndroid::SelectAll(JNIEnv* env) { web_contents_->SelectAll(); } void WebContentsAndroid::CollapseSelection(JNIEnv* env) { web_contents_->CollapseSelection(); } ScopedJavaLocalRef<jobject> WebContentsAndroid::GetRenderWidgetHostView( JNIEnv* env) { RenderWidgetHostViewAndroid* rwhva = GetRenderWidgetHostViewAndroid(); if (!rwhva) return nullptr; return rwhva->GetJavaObject(); } ScopedJavaLocalRef<jobjectArray> WebContentsAndroid::GetInnerWebContents( JNIEnv* env) { std::vector<WebContents*> inner_web_contents = web_contents_->GetInnerWebContents(); jclass clazz = org_chromium_content_browser_webcontents_WebContentsImpl_clazz(env); jobjectArray array = env->NewObjectArray(inner_web_contents.size(), clazz, nullptr); for (size_t i = 0; i < inner_web_contents.size(); i++) { ScopedJavaLocalRef<jobject> contents_java = inner_web_contents[i]->GetJavaWebContents(); env->SetObjectArrayElement(array, i, contents_java.obj()); } return ScopedJavaLocalRef<jobjectArray>(env, array); } jint WebContentsAndroid::GetVisibility(JNIEnv* env) { return static_cast<jint>(web_contents_->GetVisibility()); } RenderWidgetHostViewAndroid* WebContentsAndroid::GetRenderWidgetHostViewAndroid() { RenderWidgetHostView* rwhv = NULL; rwhv = web_contents_->GetRenderWidgetHostView(); return static_cast<RenderWidgetHostViewAndroid*>(rwhv); } jint WebContentsAndroid::GetBackgroundColor(JNIEnv* env) { RenderWidgetHostViewAndroid* rwhva = GetRenderWidgetHostViewAndroid(); // Return transparent as an indicator that the web content background color // is not specified, and a default background color will be used on the Java // side. if (!rwhva || !rwhva->GetCachedBackgroundColor()) return SK_ColorTRANSPARENT; return *rwhva->GetCachedBackgroundColor(); } ScopedJavaLocalRef<jobject> WebContentsAndroid::GetLastCommittedURL( JNIEnv* env) const { return url::GURLAndroid::FromNativeGURL(env, web_contents_->GetLastCommittedURL()); } jboolean WebContentsAndroid::IsIncognito(JNIEnv* env) { return web_contents_->GetBrowserContext()->IsOffTheRecord(); } void WebContentsAndroid::ResumeLoadingCreatedWebContents(JNIEnv* env) { web_contents_->ResumeLoadingCreatedWebContents(); } void WebContentsAndroid::OnHide(JNIEnv* env) { web_contents_->WasHidden(); } void WebContentsAndroid::OnShow(JNIEnv* env) { web_contents_->WasShown(); } void WebContentsAndroid::SetImportance(JNIEnv* env, jint primary_main_frame_importance) { web_contents_->SetPrimaryMainFrameImportance( static_cast<ChildProcessImportance>(primary_main_frame_importance)); } void WebContentsAndroid::SuspendAllMediaPlayers(JNIEnv* env) { web_contents_->media_web_contents_observer()->SuspendAllMediaPlayers(); } void WebContentsAndroid::SetAudioMuted(JNIEnv* env, jboolean mute) { web_contents_->SetAudioMuted(mute); } jboolean WebContentsAndroid::FocusLocationBarByDefault(JNIEnv* env) { return web_contents_->FocusLocationBarByDefault(); } bool WebContentsAndroid::IsFullscreenForCurrentTab(JNIEnv* env) { return web_contents_->IsFullscreen(); } void WebContentsAndroid::ExitFullscreen(JNIEnv* env) { web_contents_->ExitFullscreen(/*will_cause_resize=*/false); } void WebContentsAndroid::ScrollFocusedEditableNodeIntoView(JNIEnv* env) { auto* input_handler = web_contents_->GetFocusedFrameWidgetInputHandler(); if (!input_handler) return; bool should_overlay_content = web_contents_->GetPrimaryPage().virtual_keyboard_mode() == ui::mojom::VirtualKeyboardMode::kOverlaysContent; // TODO(bokan): Autofill is notified of focus changes at the end of the // scrollIntoView call using DidCompleteFocusChangeInFrame, see // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/frame/web_local_frame_impl.cc;l=3047;drc=aeadb03c8553c39e88d5d11d10f706d42f06a1d7. // By avoiding this call in should_overlay_content, we never notify autofill // of changed focus so we don't e.g. show the keyboard accessory. if (!should_overlay_content) input_handler->ScrollFocusedEditableNodeIntoView(); } void WebContentsAndroid::SelectAroundCaretAck( blink::mojom::SelectAroundCaretResultPtr result) { RenderWidgetHostViewAndroid* rwhva = GetRenderWidgetHostViewAndroid(); if (rwhva) { rwhva->SelectAroundCaretAck(std::move(result)); } } void WebContentsAndroid::SelectAroundCaret(JNIEnv* env, jint granularity, jboolean should_show_handle, jboolean should_show_context_menu) { auto* input_handler = web_contents_->GetFocusedFrameWidgetInputHandler(); if (!input_handler) return; input_handler->SelectAroundCaret( static_cast<blink::mojom::SelectionGranularity>(granularity), should_show_handle, should_show_context_menu, base::BindOnce(&WebContentsAndroid::SelectAroundCaretAck, weak_factory_.GetWeakPtr())); } void WebContentsAndroid::AdjustSelectionByCharacterOffset( JNIEnv* env, jint start_adjust, jint end_adjust, jboolean show_selection_menu) { web_contents_->AdjustSelectionByCharacterOffset(start_adjust, end_adjust, show_selection_menu); } bool WebContentsAndroid::InitializeRenderFrameForJavaScript() { if (!web_contents_->GetPrimaryFrameTree() .root() ->render_manager() ->InitializeMainRenderFrameForImmediateUse()) { LOG(ERROR) << "Failed to initialize RenderFrame to evaluate javascript"; return false; } return true; } void WebContentsAndroid::EvaluateJavaScript( JNIEnv* env, const JavaParamRef<jstring>& script, const JavaParamRef<jobject>& callback) { RenderViewHost* rvh = web_contents_->GetRenderViewHost(); DCHECK(rvh); if (!InitializeRenderFrameForJavaScript()) return; if (!callback) { // No callback requested. web_contents_->GetPrimaryMainFrame()->ExecuteJavaScript( ConvertJavaStringToUTF16(env, script), base::NullCallback()); return; } // Secure the Java callback in a scoped object and give ownership of it to the // base::OnceCallback below. ScopedJavaGlobalRef<jobject> j_callback; j_callback.Reset(env, callback); web_contents_->GetPrimaryMainFrame()->ExecuteJavaScript( ConvertJavaStringToUTF16(env, script), base::BindOnce(&JavaScriptResultCallback, j_callback)); } void WebContentsAndroid::EvaluateJavaScriptForTests( JNIEnv* env, const JavaParamRef<jstring>& script, const JavaParamRef<jobject>& callback) { RenderViewHost* rvh = web_contents_->GetRenderViewHost(); DCHECK(rvh); if (!InitializeRenderFrameForJavaScript()) return; if (!callback) { // No callback requested. web_contents_->GetPrimaryMainFrame()->ExecuteJavaScriptForTests( ConvertJavaStringToUTF16(env, script), base::NullCallback()); return; } // Secure the Java callback in a scoped object and give ownership of it to the // base::OnceCallback below. ScopedJavaGlobalRef<jobject> j_callback; j_callback.Reset(env, callback); web_contents_->GetPrimaryMainFrame()->ExecuteJavaScriptForTests( ConvertJavaStringToUTF16(env, script), base::BindOnce(&JavaScriptResultCallback, j_callback)); } void WebContentsAndroid::AddMessageToDevToolsConsole( JNIEnv* env, jint level, const JavaParamRef<jstring>& message) { DCHECK_GE(level, 0); DCHECK_LE(level, static_cast<int>(blink::mojom::ConsoleMessageLevel::kError)); web_contents_->GetPrimaryMainFrame()->AddMessageToConsole( static_cast<blink::mojom::ConsoleMessageLevel>(level), ConvertJavaStringToUTF8(env, message)); } void WebContentsAndroid::PostMessageToMainFrame( JNIEnv* env, const JavaParamRef<jobject>& jmessage, const JavaParamRef<jstring>& jsource_origin, const JavaParamRef<jstring>& jtarget_origin, const JavaParamRef<jobjectArray>& jports) { content::MessagePortProvider::PostMessageToFrame( web_contents_->GetPrimaryPage(), env, jsource_origin, jtarget_origin, jmessage, jports); } jboolean WebContentsAndroid::HasAccessedInitialDocument(JNIEnv* env) { return static_cast<WebContentsImpl*>(web_contents_)-> HasAccessedInitialDocument(); } jint WebContentsAndroid::GetThemeColor(JNIEnv* env) { return web_contents_->GetThemeColor().value_or(SK_ColorTRANSPARENT); } jfloat WebContentsAndroid::GetLoadProgress(JNIEnv* env) { return web_contents_->GetLoadProgress(); } void WebContentsAndroid::RequestSmartClipExtract( JNIEnv* env, const JavaParamRef<jobject>& callback, jint x, jint y, jint width, jint height) { // Secure the Java callback in a scoped object and give ownership of it to the // base::OnceCallback below. ScopedJavaGlobalRef<jobject> j_callback; j_callback.Reset(env, callback); web_contents_->GetPrimaryMainFrame()->RequestSmartClipExtract( base::BindOnce(&SmartClipCallback, j_callback), gfx::Rect(x, y, width, height)); } void WebContentsAndroid::AXTreeSnapshotCallback( const JavaRef<jobject>& view_structure_root, const JavaRef<jobject>& view_structure_builder, const JavaRef<jobject>& callback, const ui::AXTreeUpdate& result) { JNIEnv* env = base::android::AttachCurrentThread(); if (result.nodes.empty()) { RunRunnableAndroid(callback); return; } std::unique_ptr<ui::AssistantTree> assistant_tree = ui::CreateAssistantTree(result); CreateJavaAXSnapshot(env, assistant_tree.get(), assistant_tree->nodes.front().get(), view_structure_root, view_structure_builder, true); AddTreeLevelDataToViewStructure(env, view_structure_root, view_structure_builder, result); RunRunnableAndroid(callback); } void WebContentsAndroid::RequestAccessibilitySnapshot( JNIEnv* env, const JavaParamRef<jobject>& view_structure_root, const JavaParamRef<jobject>& view_structure_builder, const JavaParamRef<jobject>& callback) { // Secure the Java objects in scoped objects and give ownership of them to the // base::OnceCallback below. ScopedJavaGlobalRef<jobject> j_callback; j_callback.Reset(env, callback); ScopedJavaGlobalRef<jobject> j_view_structure_root; j_view_structure_root.Reset(env, view_structure_root); ScopedJavaGlobalRef<jobject> j_view_structure_builder; j_view_structure_builder.Reset(env, view_structure_builder); // Set a timeout of 2.0 seconds to compute the snapshot of the // accessibility tree because Google Assistant ignores results that // don't come back within 3.0 seconds. static_cast<WebContentsImpl*>(web_contents_) ->RequestAXTreeSnapshot( base::BindOnce( &WebContentsAndroid::AXTreeSnapshotCallback, weak_factory_.GetWeakPtr(), std::move(j_view_structure_root), std::move(j_view_structure_builder), std::move(j_callback)), ui::AXMode(ui::kAXModeComplete.flags() | ui::AXMode::kHTMLMetadata), /* exclude_offscreen= */ false, /* max_nodes= */ 5000, /* timeout= */ base::Seconds(2)); } ScopedJavaLocalRef<jstring> WebContentsAndroid::GetEncoding(JNIEnv* env) const { return base::android::ConvertUTF8ToJavaString(env, web_contents_->GetEncoding()); } void WebContentsAndroid::SetOverscrollRefreshHandler( JNIEnv* env, const base::android::JavaParamRef<jobject>& overscroll_refresh_handler) { WebContentsViewAndroid* view = static_cast<WebContentsViewAndroid*>(web_contents_->GetView()); view->SetOverscrollRefreshHandler( std::make_unique<ui::OverscrollRefreshHandler>( overscroll_refresh_handler)); } void WebContentsAndroid::SetSpatialNavigationDisabled(JNIEnv* env, bool disabled) { web_contents_->SetSpatialNavigationDisabled(disabled); } void WebContentsAndroid::SetStylusHandwritingEnabled(JNIEnv* env, bool enabled) { web_contents_->SetStylusHandwritingEnabled(enabled); } int WebContentsAndroid::DownloadImage( JNIEnv* env, const base::android::JavaParamRef<jobject>& jurl, jboolean is_fav_icon, jint max_bitmap_size, jboolean bypass_cache, const base::android::JavaParamRef<jobject>& jcallback) { const gfx::Size preferred_size; return web_contents_->DownloadImage( *url::GURLAndroid::ToNativeGURL(env, jurl), is_fav_icon, preferred_size, max_bitmap_size, bypass_cache, base::BindOnce(&WebContentsAndroid::OnFinishDownloadImage, weak_factory_.GetWeakPtr(), obj_, ScopedJavaGlobalRef<jobject>(env, jcallback))); } void WebContentsAndroid::SetHasPersistentVideo(JNIEnv* env, jboolean value) { web_contents_->SetHasPersistentVideo(value); } bool WebContentsAndroid::HasActiveEffectivelyFullscreenVideo(JNIEnv* env) { return web_contents_->HasActiveEffectivelyFullscreenVideo(); } bool WebContentsAndroid::IsPictureInPictureAllowedForFullscreenVideo( JNIEnv* env) { return web_contents_->IsPictureInPictureAllowedForFullscreenVideo(); } base::android::ScopedJavaLocalRef<jobject> WebContentsAndroid::GetFullscreenVideoSize(JNIEnv* env) { if (!web_contents_->GetFullscreenVideoSize()) return ScopedJavaLocalRef<jobject>(); // Return null. gfx::Size size = web_contents_->GetFullscreenVideoSize().value(); return Java_WebContentsImpl_createSize(env, size.width(), size.height()); } void WebContentsAndroid::SetSize(JNIEnv* env, jint width, jint height) { web_contents_->GetNativeView()->OnSizeChanged(width, height); } int WebContentsAndroid::GetWidth(JNIEnv* env) { return web_contents_->GetNativeView()->GetSize().width(); } int WebContentsAndroid::GetHeight(JNIEnv* env) { return web_contents_->GetNativeView()->GetSize().height(); } ScopedJavaLocalRef<jobject> WebContentsAndroid::GetOrCreateEventForwarder( JNIEnv* env) { gfx::NativeView native_view = web_contents_->GetView()->GetNativeView(); return native_view->GetEventForwarder(); } void WebContentsAndroid::OnFinishDownloadImage( const JavaRef<jobject>& obj, const JavaRef<jobject>& callback, int id, int http_status_code, const GURL& url, const std::vector<SkBitmap>& bitmaps, const std::vector<gfx::Size>& sizes) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jobject> jbitmaps = Java_WebContentsImpl_createBitmapList(env); ScopedJavaLocalRef<jobject> jsizes = Java_WebContentsImpl_createSizeList(env); ScopedJavaLocalRef<jobject> jurl = url::GURLAndroid::FromNativeGURL(env, url); for (const SkBitmap& bitmap : bitmaps) { // WARNING: convering to java bitmaps results in duplicate memory // allocations, which increases the chance of OOMs if DownloadImage() is // misused. ScopedJavaLocalRef<jobject> jbitmap = gfx::ConvertToJavaBitmap(bitmap); Java_WebContentsImpl_addToBitmapList(env, jbitmaps, jbitmap); } for (const gfx::Size& size : sizes) { Java_WebContentsImpl_createSizeAndAddToList(env, jsizes, size.width(), size.height()); } Java_WebContentsImpl_onDownloadImageFinished( env, obj, callback, id, http_status_code, jurl, jbitmaps, jsizes); } void WebContentsAndroid::SetMediaSession( const ScopedJavaLocalRef<jobject>& j_media_session) { JNIEnv* env = base::android::AttachCurrentThread(); Java_WebContentsImpl_setMediaSession(env, obj_, j_media_session); } void WebContentsAndroid::SendOrientationChangeEvent(JNIEnv* env, jint orientation) { base::RecordAction(base::UserMetricsAction("ScreenOrientationChange")); WebContentsViewAndroid* view = static_cast<WebContentsViewAndroid*>(web_contents_->GetView()); view->set_device_orientation(orientation); RenderWidgetHostViewAndroid* rwhva = GetRenderWidgetHostViewAndroid(); if (rwhva) rwhva->UpdateScreenInfo(); web_contents_->OnScreenOrientationChange(); } void WebContentsAndroid::OnScaleFactorChanged(JNIEnv* env) { RenderWidgetHostViewAndroid* rwhva = GetRenderWidgetHostViewAndroid(); if (rwhva) { // |SendScreenRects()| indirectly calls GetViewSize() that asks Java layer. web_contents_->SendScreenRects(); rwhva->SynchronizeVisualProperties(cc::DeadlinePolicy::UseDefaultDeadline(), absl::nullopt); } } void WebContentsAndroid::SetFocus(JNIEnv* env, jboolean focused) { WebContentsViewAndroid* view = static_cast<WebContentsViewAndroid*>(web_contents_->GetView()); view->SetFocus(focused); } bool WebContentsAndroid::IsBeingDestroyed(JNIEnv* env) { return web_contents_->IsBeingDestroyed(); } void WebContentsAndroid::SetDisplayCutoutSafeArea(JNIEnv* env, int top, int left, int bottom, int right) { web_contents()->SetDisplayCutoutSafeArea( gfx::Insets::TLBR(top, left, bottom, right)); } void WebContentsAndroid::NotifyRendererPreferenceUpdate(JNIEnv* env) { web_contents_->OnWebPreferencesChanged(); } void WebContentsAndroid::NotifyBrowserControlsHeightChanged(JNIEnv* env) { web_contents_->GetNativeView()->OnBrowserControlsHeightChanged(); } } // namespace content
{ "content_hash": "748222e13af9644046dba0ecec68609e", "timestamp": "", "source": "github", "line_count": 866, "max_line_length": 176, "avg_line_length": 36.43533487297921, "alnum_prop": 0.7142902418153583, "repo_name": "chromium/chromium", "id": "72f835f0739ea0772107ccc20b32e444df12a96e", "size": "31553", "binary": false, "copies": "5", "ref": "refs/heads/main", "path": "content/browser/web_contents/web_contents_android.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <title>Uses of Class org.deidentifier.arx.Data (ARX Developer Documentation)</title> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.deidentifier.arx.Data (ARX Developer Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/deidentifier/arx/class-use/Data.html" target="_top">Frames</a></li> <li><a href="Data.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.deidentifier.arx.Data" class="title">Uses of Class<br>org.deidentifier.arx.Data</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.deidentifier.arx">org.deidentifier.arx</a></td> <td class="colLast"> <div class="block">This package provides the public API for the ARX anonymization framework.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.deidentifier.arx"> <!-- --> </a> <h3>Uses of <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a> in <a href="../../../../org/deidentifier/arx/package-summary.html">org.deidentifier.arx</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a> in <a href="../../../../org/deidentifier/arx/package-summary.html">org.deidentifier.arx</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../org/deidentifier/arx/Data.DefaultData.html" title="class in org.deidentifier.arx">Data.DefaultData</a></strong></code> <div class="block">The default implementation of a data object.</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/deidentifier/arx/package-summary.html">org.deidentifier.arx</a> that return <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(org.deidentifier.arx.DataSource)">create</a></strong>(<a href="../../../../org/deidentifier/arx/DataSource.html" title="class in org.deidentifier.arx">DataSource</a>&nbsp;source)</code> <div class="block">Creates a new data object from the given data source specification.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.File)">create</a></strong>(java.io.File&nbsp;file)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.File,%20char)">create</a></strong>(java.io.File&nbsp;file, char&nbsp;delimiter)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.File,%20char,%20char)">create</a></strong>(java.io.File&nbsp;file, char&nbsp;delimiter, char&nbsp;quote)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.File,%20char,%20char,%20char)">create</a></strong>(java.io.File&nbsp;file, char&nbsp;delimiter, char&nbsp;quote, char&nbsp;escape)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.File,%20char,%20char,%20char,%20char[])">create</a></strong>(java.io.File&nbsp;file, char&nbsp;delimiter, char&nbsp;quote, char&nbsp;escape, char[]&nbsp;linebreak)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.File,%20org.deidentifier.arx.io.CSVSyntax)">create</a></strong>(java.io.File&nbsp;file, <a href="../../../../org/deidentifier/arx/io/CSVSyntax.html" title="class in org.deidentifier.arx.io">CSVSyntax</a>&nbsp;config)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.File,%20org.deidentifier.arx.io.CSVSyntax,%20org.deidentifier.arx.DataType[])">create</a></strong>(java.io.File&nbsp;file, <a href="../../../../org/deidentifier/arx/io/CSVSyntax.html" title="class in org.deidentifier.arx.io">CSVSyntax</a>&nbsp;config, <a href="../../../../org/deidentifier/arx/DataType.html" title="class in org.deidentifier.arx">DataType</a>&lt;org.apache.poi.ss.formula.functions.T&gt;[]&nbsp;datatypes)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.InputStream)">create</a></strong>(java.io.InputStream&nbsp;stream)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.InputStream,%20char)">create</a></strong>(java.io.InputStream&nbsp;stream, char&nbsp;delimiter)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.InputStream,%20char,%20char)">create</a></strong>(java.io.InputStream&nbsp;stream, char&nbsp;delimiter, char&nbsp;quote)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.InputStream,%20char,%20char,%20char)">create</a></strong>(java.io.InputStream&nbsp;stream, char&nbsp;delimiter, char&nbsp;quote, char&nbsp;escape)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.InputStream,%20char,%20char,%20char,%20char[])">create</a></strong>(java.io.InputStream&nbsp;stream, char&nbsp;delimiter, char&nbsp;quote, char&nbsp;escape, char[]&nbsp;linebreak)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.InputStream,%20org.deidentifier.arx.io.CSVSyntax)">create</a></strong>(java.io.InputStream&nbsp;stream, <a href="../../../../org/deidentifier/arx/io/CSVSyntax.html" title="class in org.deidentifier.arx.io">CSVSyntax</a>&nbsp;config)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.io.InputStream,%20org.deidentifier.arx.io.CSVSyntax,%20org.deidentifier.arx.DataType[])">create</a></strong>(java.io.InputStream&nbsp;stream, <a href="../../../../org/deidentifier/arx/io/CSVSyntax.html" title="class in org.deidentifier.arx.io">CSVSyntax</a>&nbsp;config, <a href="../../../../org/deidentifier/arx/DataType.html" title="class in org.deidentifier.arx">DataType</a>&lt;org.apache.poi.ss.formula.functions.T&gt;[]&nbsp;datatypes)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.util.Iterator)">create</a></strong>(java.util.Iterator&lt;java.lang.String[]&gt;&nbsp;iterator)</code> <div class="block">Creates a new data object from an iterator over tuples.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.util.List)">create</a></strong>(java.util.List&lt;java.lang.String[]&gt;&nbsp;list)</code> <div class="block">Creates a new data object from a list.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.lang.String)">create</a></strong>(java.lang.String&nbsp;path)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.lang.String[][])">create</a></strong>(java.lang.String[][]&nbsp;array)</code> <div class="block">Creates a new data object from a two-dimensional string array.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.lang.String,%20char)">create</a></strong>(java.lang.String&nbsp;path, char&nbsp;delimiter)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.lang.String,%20char,%20char)">create</a></strong>(java.lang.String&nbsp;path, char&nbsp;delimiter, char&nbsp;quote)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.lang.String,%20char,%20char,%20char)">create</a></strong>(java.lang.String&nbsp;path, char&nbsp;delimiter, char&nbsp;quote, char&nbsp;escape)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.lang.String,%20char,%20char,%20char,%20char[])">create</a></strong>(java.lang.String&nbsp;path, char&nbsp;delimiter, char&nbsp;quote, char&nbsp;escape, char[]&nbsp;linebreak)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.lang.String,%20org.deidentifier.arx.io.CSVSyntax)">create</a></strong>(java.lang.String&nbsp;path, <a href="../../../../org/deidentifier/arx/io/CSVSyntax.html" title="class in org.deidentifier.arx.io">CSVSyntax</a>&nbsp;config)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></code></td> <td class="colLast"><span class="strong">Data.</span><code><strong><a href="../../../../org/deidentifier/arx/Data.html#create(java.lang.String,%20org.deidentifier.arx.io.CSVSyntax,%20org.deidentifier.arx.DataType[])">create</a></strong>(java.lang.String&nbsp;path, <a href="../../../../org/deidentifier/arx/io/CSVSyntax.html" title="class in org.deidentifier.arx.io">CSVSyntax</a>&nbsp;config, <a href="../../../../org/deidentifier/arx/DataType.html" title="class in org.deidentifier.arx">DataType</a>&lt;org.apache.poi.ss.formula.functions.T&gt;[]&nbsp;datatypes)</code> <div class="block">Creates a new data object from a CSV file.</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../org/deidentifier/arx/package-summary.html">org.deidentifier.arx</a> with parameters of type <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../org/deidentifier/arx/ARXResult.html" title="class in org.deidentifier.arx">ARXResult</a></code></td> <td class="colLast"><span class="strong">ARXAnonymizer.</span><code><strong><a href="../../../../org/deidentifier/arx/ARXAnonymizer.html#anonymize(org.deidentifier.arx.Data,%20org.deidentifier.arx.ARXConfiguration)">anonymize</a></strong>(<a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a>&nbsp;data, <a href="../../../../org/deidentifier/arx/ARXConfiguration.html" title="class in org.deidentifier.arx">ARXConfiguration</a>&nbsp;config)</code> <div class="block">Performs data anonymization.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/RowSet.html" title="class in org.deidentifier.arx">RowSet</a></code></td> <td class="colLast"><span class="strong">RowSet.</span><code><strong><a href="../../../../org/deidentifier/arx/RowSet.html#create(org.deidentifier.arx.Data)">create</a></strong>(<a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a>&nbsp;data)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/DataSelector.html" title="class in org.deidentifier.arx">DataSelector</a></code></td> <td class="colLast"><span class="strong">DataSelector.</span><code><strong><a href="../../../../org/deidentifier/arx/DataSelector.html#create(org.deidentifier.arx.Data)">create</a></strong>(<a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a>&nbsp;data)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/DataSubset.html" title="class in org.deidentifier.arx">DataSubset</a></code></td> <td class="colLast"><span class="strong">DataSubset.</span><code><strong><a href="../../../../org/deidentifier/arx/DataSubset.html#create(org.deidentifier.arx.Data,%20org.deidentifier.arx.Data)">create</a></strong>(<a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a>&nbsp;data, <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a>&nbsp;subset)</code> <div class="block">Create a subset by matching two data instances.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/DataSubset.html" title="class in org.deidentifier.arx">DataSubset</a></code></td> <td class="colLast"><span class="strong">DataSubset.</span><code><strong><a href="../../../../org/deidentifier/arx/DataSubset.html#create(org.deidentifier.arx.Data,%20org.deidentifier.arx.DataSelector)">create</a></strong>(<a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a>&nbsp;data, <a href="../../../../org/deidentifier/arx/DataSelector.html" title="class in org.deidentifier.arx">DataSelector</a>&nbsp;selector)</code> <div class="block">Creates a subset from the given selector.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/DataSubset.html" title="class in org.deidentifier.arx">DataSubset</a></code></td> <td class="colLast"><span class="strong">DataSubset.</span><code><strong><a href="../../../../org/deidentifier/arx/DataSubset.html#create(org.deidentifier.arx.Data,%20org.deidentifier.arx.RowSet)">create</a></strong>(<a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a>&nbsp;data, <a href="../../../../org/deidentifier/arx/RowSet.html" title="class in org.deidentifier.arx">RowSet</a>&nbsp;subset)</code> <div class="block">Creates a new subset from the given row set, from which a copy is created.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/DataSubset.html" title="class in org.deidentifier.arx">DataSubset</a></code></td> <td class="colLast"><span class="strong">DataSubset.</span><code><strong><a href="../../../../org/deidentifier/arx/DataSubset.html#create(org.deidentifier.arx.Data,%20java.util.Set)">create</a></strong>(<a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a>&nbsp;data, java.util.Set&lt;java.lang.Integer&gt;&nbsp;subset)</code> <div class="block">Creates a new subset from the given set of tuple indices.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/deidentifier/arx/DataSelector.html" title="class in org.deidentifier.arx">DataSelector</a></code></td> <td class="colLast"><span class="strong">DataSelector.</span><code><strong><a href="../../../../org/deidentifier/arx/DataSelector.html#create(org.deidentifier.arx.Data,%20java.lang.String)">create</a></strong>(<a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a>&nbsp;data, java.lang.String&nbsp;query)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><span class="strong">DataHandleInput.</span><code><strong><a href="../../../../org/deidentifier/arx/DataHandleInput.html#update(org.deidentifier.arx.Data)">update</a></strong>(<a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a>&nbsp;data)</code> <div class="block">Update the definition.</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../org/deidentifier/arx/package-summary.html">org.deidentifier.arx</a> with parameters of type <a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../org/deidentifier/arx/DataHandleInput.html#DataHandleInput(org.deidentifier.arx.Data)">DataHandleInput</a></strong>(<a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Data</a>&nbsp;data)</code> <div class="block">Creates a new data handle.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/deidentifier/arx/Data.html" title="class in org.deidentifier.arx">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/deidentifier/arx/class-use/Data.html" target="_top">Frames</a></li> <li><a href="Data.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "1aa0f753b3d3e21bb9e08452d330e9fd", "timestamp": "", "source": "github", "line_count": 431, "max_line_length": 349, "avg_line_length": 63.754060324825986, "alnum_prop": 0.671082320401776, "repo_name": "tijanat/arx", "id": "93f79bd0b9d0c05cb673f3c3e2cbebd645a3de4a", "size": "27478", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "doc/dev/org/deidentifier/arx/class-use/Data.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "61796" }, { "name": "Java", "bytes": "4034485" } ], "symlink_target": "" }
<?php namespace GOC\LocaleBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('goc_locale'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
{ "content_hash": "3c4382b90a3dff17b962da7cf1a43133", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 131, "avg_line_length": 28.29032258064516, "alnum_prop": 0.7137970353477765, "repo_name": "gardenofconcepts/GOCLocaleBundle", "id": "9332a3a72d9c18ae2c98c1e93062b5611ea890fd", "size": "1202", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DependencyInjection/Configuration.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "27994" } ], "symlink_target": "" }
var DEPTHNOISE_EFFECT = { Apply: function( inGeometry, inParameters ) { var positions = inGeometry.getAttribute( 'position' ).array, scaleDepth = inParameters.depth / 255; for( var i = 1; i < positions.length; i += 3 ) { positions[i] += scaleDepth * inParameters.alea.Random(); } }, };
{ "content_hash": "1b650953b4b0e12dc4a8403813e86bb0", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 62, "avg_line_length": 22, "alnum_prop": 0.6461038961038961, "repo_name": "catarak/withoutcolors", "id": "fcd33937cf02e359f36ff0cd8ea0d7f1b1687500", "size": "308", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "js/deps/terrain-generator/depthnoise.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "7597" }, { "name": "JavaScript", "bytes": "989423" }, { "name": "Makefile", "bytes": "144" }, { "name": "Shell", "bytes": "746" } ], "symlink_target": "" }
package org.apache.lucene.facet.search.sampling; /** * Parameters for sampling, dictating whether sampling is to take place and how. * * @lucene.experimental */ public class SamplingParams { /** * Default factor by which more results are requested over the sample set. * @see SamplingParams#getOversampleFactor() */ public static final double DEFAULT_OVERSAMPLE_FACTOR = 2d; /** * Default ratio between size of sample to original size of document set. * @see Sampler#getSampleSet(org.apache.lucene.facet.search.ScoredDocIDs) */ public static final double DEFAULT_SAMPLE_RATIO = 0.01; /** * Default maximum size of sample. * @see Sampler#getSampleSet(org.apache.lucene.facet.search.ScoredDocIDs) */ public static final int DEFAULT_MAX_SAMPLE_SIZE = 10000; /** * Default minimum size of sample. * @see Sampler#getSampleSet(org.apache.lucene.facet.search.ScoredDocIDs) */ public static final int DEFAULT_MIN_SAMPLE_SIZE = 100; /** * Default sampling threshold, if number of results is less than this number - no sampling will take place * @see SamplingParams#getSampleRatio() */ public static final int DEFAULT_SAMPLING_THRESHOLD = 75000; private int maxSampleSize = DEFAULT_MAX_SAMPLE_SIZE; private int minSampleSize = DEFAULT_MIN_SAMPLE_SIZE; private double sampleRatio = DEFAULT_SAMPLE_RATIO; private int samplingThreshold = DEFAULT_SAMPLING_THRESHOLD; private double oversampleFactor = DEFAULT_OVERSAMPLE_FACTOR; /** * Return the maxSampleSize. * In no case should the resulting sample size exceed this value. * @see Sampler#getSampleSet(org.apache.lucene.facet.search.ScoredDocIDs) */ public final int getMaxSampleSize() { return maxSampleSize; } /** * Return the minSampleSize. * In no case should the resulting sample size be smaller than this value. * @see Sampler#getSampleSet(org.apache.lucene.facet.search.ScoredDocIDs) */ public final int getMinSampleSize() { return minSampleSize; } /** * @return the sampleRatio * @see Sampler#getSampleSet(org.apache.lucene.facet.search.ScoredDocIDs) */ public final double getSampleRatio() { return sampleRatio; } /** * Return the samplingThreshold. * Sampling would be performed only for document sets larger than this. */ public final int getSamplingThreshold() { return samplingThreshold; } /** * @param maxSampleSize * the maxSampleSize to set * @see #getMaxSampleSize() */ public void setMaxSampleSize(int maxSampleSize) { this.maxSampleSize = maxSampleSize; } /** * @param minSampleSize * the minSampleSize to set * @see #getMinSampleSize() */ public void setMinSampleSize(int minSampleSize) { this.minSampleSize = minSampleSize; } /** * @param sampleRatio * the sampleRatio to set * @see #getSampleRatio() */ public void setSampleRatio(double sampleRatio) { this.sampleRatio = sampleRatio; } /** * Set a sampling-threshold * @see #getSamplingThreshold() */ public void setSampingThreshold(int sampingThreshold) { this.samplingThreshold = sampingThreshold; } /** * Check validity of sampling settings, making sure that * <ul> * <li> <code>minSampleSize <= maxSampleSize <= samplingThreshold </code></li> * <li> <code>0 < samplingRatio <= 1 </code></li> * </ul> * * @return true if valid, false otherwise */ public boolean validate() { return samplingThreshold >= maxSampleSize && maxSampleSize >= minSampleSize && sampleRatio > 0 && sampleRatio < 1; } /** * Return the oversampleFactor. When sampling, we would collect that much more * results, so that later, when selecting top out of these, chances are higher * to get actual best results. Note that having this value larger than 1 only * makes sense when using a SampleFixer which finds accurate results, such as * <code>TakmiSampleFixer</code>. When this value is smaller than 1, it is * ignored and no oversampling takes place. */ public final double getOversampleFactor() { return oversampleFactor; } /** * @param oversampleFactor the oversampleFactor to set * @see #getOversampleFactor() */ public void setOversampleFactor(double oversampleFactor) { this.oversampleFactor = oversampleFactor; } }
{ "content_hash": "0d81f911b21896a127b1cdb0e6f9a30a", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 108, "avg_line_length": 29.766233766233768, "alnum_prop": 0.6697207678883071, "repo_name": "terrancesnyder/solr-analytics", "id": "45bafd867760174cb2bff53d9046562f8013861f", "size": "5400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lucene/facet/src/java/org/apache/lucene/facet/search/sampling/SamplingParams.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "13898" }, { "name": "Java", "bytes": "31968690" }, { "name": "JavaScript", "bytes": "1221046" }, { "name": "Perl", "bytes": "81566" }, { "name": "Python", "bytes": "179898" }, { "name": "Shell", "bytes": "19867" } ], "symlink_target": "" }
package org.bbop.apollo.gwt.client; import com.google.gwt.user.client.ui.HTML; import org.gwtbootstrap3.client.ui.Modal; import org.gwtbootstrap3.client.ui.ModalBody; import org.gwtbootstrap3.client.ui.constants.ModalBackdrop; /** * Created by ndunn on 4/30/15. */ public class LinkDialog extends Modal{ // private Boolean showOnBuild = true ; // public LinkDialog(boolean showOnConstruct){ // this("Loading ...",null,showOnConstruct); // } // // public LinkDialog(){ // this("Loading ...",null,true); // } // public LinkDialog(String title){ // this(title,null,true); // // } public LinkDialog(String title, String message, Boolean showOnConstruct){ setTitle(title); setClosable(true); setFade(true); setDataBackdrop(ModalBackdrop.STATIC); if(message!=null){ HTML content = new HTML(message); ModalBody modalBody = new ModalBody(); modalBody.add(content); add( modalBody ); } if(showOnConstruct){ show(); } } }
{ "content_hash": "2bcc9859a9980b3e6b4e302dd2ff1756", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 77, "avg_line_length": 24.886363636363637, "alnum_prop": 0.6155251141552511, "repo_name": "nathandunn/Apollo3", "id": "f383273ed7951214891d82eb72ba1211b3274c1d", "size": "1095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/bbop/apollo/gwt/client/LinkDialog.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "19483" }, { "name": "Groovy", "bytes": "1686547" }, { "name": "Java", "bytes": "410423" }, { "name": "JavaScript", "bytes": "598" } ], "symlink_target": "" }
package microsoft.exchange.webservices.data.enumeration; /** * Defines the offset's base point in a paged view. */ public enum OffsetBasePoint { // The offset is from the beginning of the view. /** * The Beginning. */ Beginning, // The offset is from the end of the view. /** * The End. */ End }
{ "content_hash": "774e615d07d78d6a4e49e52b18f43a5c", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 56, "avg_line_length": 14.909090909090908, "alnum_prop": 0.6371951219512195, "repo_name": "easel/ews-java-api", "id": "f0ebb458f1ec0c12ee39e671ba759c392f03b2a0", "size": "1472", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/microsoft/exchange/webservices/data/enumeration/OffsetBasePoint.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "3778080" }, { "name": "Shell", "bytes": "2533" } ], "symlink_target": "" }
#ifndef ALINOUS_RUNTIME_DOM_TYPED_SHORTVARIABLE_H_ #define ALINOUS_RUNTIME_DOM_TYPED_SHORTVARIABLE_H_ namespace alinous{namespace annotation{ class OneSource; }} namespace alinous {namespace runtime {namespace dom {namespace typed { class ShortVariable;}}}} namespace alinous {namespace html { class DomNode;}} namespace alinous {namespace html {namespace xpath { class IVariableValue;}}} namespace java {namespace lang { class Throwable;}} namespace alinous {namespace html { class Attribute;}} namespace alinous {namespace runtime {namespace variant { class VariantValue;}}} namespace alinous {namespace runtime {namespace dom { class IAlinousVariable;}}} namespace alinous {namespace runtime {namespace dom { class IDomVariable;}}} namespace alinous {namespace runtime {namespace dom { class DomVariable;}}} namespace alinous {namespace runtime {namespace dom {namespace typed { class LongVariable;}}}} namespace alinous {namespace runtime {namespace dom {namespace typed { class BoolVariable;}}}} namespace alinous {namespace runtime {namespace dom { class VariableException;}}} namespace alinous {namespace runtime {namespace dom {namespace typed { class ByteVariable;}}}} namespace alinous {namespace runtime {namespace dom {namespace typed { class CharVariable;}}}} namespace alinous {namespace runtime {namespace dom {namespace typed { class DoubleVariable;}}}} namespace alinous {namespace runtime {namespace dom {namespace typed { class FloatVariable;}}}} namespace alinous {namespace runtime {namespace dom {namespace typed { class IntegerVariable;}}}} namespace alinous {namespace runtime {namespace dom {namespace typed { class StringVariable;}}}} namespace java {namespace lang { class StringBuffer;}} namespace alinous {namespace runtime {namespace dom {namespace typed { class BigDecimalVariable;}}}} namespace alinous {namespace numeric { class BigDecimal;}} namespace alinous {namespace runtime {namespace dom {namespace typed { class TimeVariable;}}}} namespace alinous {namespace numeric { class TimeOnlyTimestamp;}} namespace alinous {namespace runtime {namespace dom {namespace typed { class TimestampVariable;}}}} namespace java {namespace sql { class Timestamp;}} namespace alinous {namespace runtime {namespace dom {namespace typed { class TypedVariableArray;}}}} namespace alinous {namespace remote {namespace socket { class NetworkBinaryBuffer;}}} namespace alinous {namespace runtime {namespace dom {namespace typed { class AbstractTypedVariable;}}}} namespace alinous {namespace remote {namespace socket { class ICommandData;}}} namespace alinous {namespace system { class AlinousException;}} namespace alinous { class ThreadContext; } namespace alinous {namespace runtime {namespace dom {namespace typed { using namespace ::alinous; using namespace ::java::lang; using ::java::util::Iterator; using ::java::sql::Timestamp; using ::alinous::html::Attribute; using ::alinous::html::DomNode; using ::alinous::html::xpath::IVariableValue; using ::alinous::numeric::BigDecimal; using ::alinous::numeric::TimeOnlyTimestamp; using ::alinous::remote::socket::ICommandData; using ::alinous::remote::socket::NetworkBinaryBuffer; using ::alinous::runtime::dom::DomVariable; using ::alinous::runtime::dom::IAlinousVariable; using ::alinous::runtime::dom::IDomVariable; using ::alinous::runtime::dom::VariableException; using ::alinous::runtime::variant::VariantValue; using ::alinous::system::AlinousException; class ShortVariable final : public AbstractTypedVariable { public: ShortVariable(const ShortVariable& base) = default; public: ShortVariable(ThreadContext* ctx) throw() ; void __construct_impl(ThreadContext* ctx) throw() ; ShortVariable(short value, ThreadContext* ctx) throw() ; void __construct_impl(short value, ThreadContext* ctx) throw() ; virtual ~ShortVariable() throw(); virtual void __releaseRegerences(bool prepare, ThreadContext* ctx) throw(); private: short value; public: static String* VAL_TYPE; public: void outDebugXml(DomNode* parentNode, String* name, ThreadContext* ctx) throw() final; int getVariableClass(ThreadContext* ctx) throw() final; int getTypedType(ThreadContext* ctx) throw() final; short getValue(ThreadContext* ctx) throw() ; void setValue(short value, ThreadContext* ctx) throw() ; VariantValue* toVariantValue(ThreadContext* ctx) final; int getIntValue(ThreadContext* ctx) final; String* getStringValue(ThreadContext* ctx) final; IAlinousVariable* copy(ThreadContext* ctx) final; IDomVariable* toDomVariable(ThreadContext* ctx) throw() final; IAlinousVariable* add(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* add(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* add(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* add(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* add(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* add(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* add(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* add(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* add(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* add(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* add(StringVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* minus(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(StringVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(StringVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* div(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(StringVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitReverse(ThreadContext* ctx) final; bool isNull(ThreadContext* ctx) throw() final; bool isArray(ThreadContext* ctx) throw() final; IAlinousVariable* shiftLeft(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(StringVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(StringVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(StringVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(StringVariable* variable, ThreadContext* ctx) final; int compareTo(VariantValue* variable, ThreadContext* ctx) final; int compareTo(DomVariable* variable, ThreadContext* ctx) final; int compareTo(BoolVariable* variable, ThreadContext* ctx) final; int compareTo(ByteVariable* variable, ThreadContext* ctx) final; int compareTo(CharVariable* variable, ThreadContext* ctx) final; int compareTo(DoubleVariable* variable, ThreadContext* ctx) final; int compareTo(FloatVariable* variable, ThreadContext* ctx) final; int compareTo(IntegerVariable* variable, ThreadContext* ctx) final; int compareTo(LongVariable* variable, ThreadContext* ctx) final; int compareTo(ShortVariable* variable, ThreadContext* ctx) final; int compareTo(StringVariable* variable, ThreadContext* ctx) final; bool isTrue(ThreadContext* ctx) final; IAlinousVariable* bitOr(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(StringVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(StringVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(StringVariable* variable, ThreadContext* ctx) final; IAlinousVariable* add(BigDecimalVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(BigDecimalVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(BigDecimalVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(BigDecimalVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(BigDecimalVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(BigDecimalVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(BigDecimalVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(BigDecimalVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(BigDecimalVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(BigDecimalVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(BigDecimalVariable* variable, ThreadContext* ctx) final; int compareTo(BigDecimalVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(VariantValue* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(DomVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(BoolVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(ByteVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(CharVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(DoubleVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(FloatVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(IntegerVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(LongVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(ShortVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(StringVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(BigDecimalVariable* variable, ThreadContext* ctx) final; BoolVariable* toBoolVariable(ThreadContext* ctx) final; ByteVariable* toByteVariable(ThreadContext* ctx) final; CharVariable* toCharVariable(ThreadContext* ctx) final; ShortVariable* toShortVariable(ThreadContext* ctx) final; IntegerVariable* toIntVariable(ThreadContext* ctx) final; LongVariable* toLongVariable(ThreadContext* ctx) final; StringVariable* toStringVariable(ThreadContext* ctx) final; BigDecimalVariable* toBigDecimalVariable(ThreadContext* ctx) final; long long getLongValue(ThreadContext* ctx) final; FloatVariable* toFloatVariable(ThreadContext* ctx) final; DoubleVariable* toDoubleVariable(ThreadContext* ctx) final; TimeVariable* toTimeVariable(ThreadContext* ctx) final; TimestampVariable* toTimestampVariable(ThreadContext* ctx) final; IAlinousVariable* add(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* add(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* minus(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* multiply(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* div(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftLeft(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRight(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* shiftRightUnsigned(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* modulo(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitOr(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitAnd(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* bitExor(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(TimeVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(TimestampVariable* variable, ThreadContext* ctx) final; int compareTo(TimeVariable* variable, ThreadContext* ctx) final; int compareTo(TimestampVariable* variable, ThreadContext* ctx) final; IAlinousVariable* substitute(TypedVariableArray* variable, ThreadContext* ctx) final; void readData(NetworkBinaryBuffer* buff, ThreadContext* ctx) throw() final; void writeData(NetworkBinaryBuffer* buff, ThreadContext* ctx) throw() final; public: static ShortVariable* fromDebugXml(DomNode* node, ThreadContext* ctx) throw() ; public: static bool __init_done; static bool __init_static_variables(); public: static void __cleanUp(ThreadContext* ctx); class ValueCompare { public: int operator() (VariantValue* _this, VariantValue* variable, ThreadContext* ctx) const throw(); }; }; }}}} #endif /* end of ALINOUS_RUNTIME_DOM_TYPED_SHORTVARIABLE_H_ */
{ "content_hash": "917cb962b0f271280f5947100469cfab", "timestamp": "", "source": "github", "line_count": 364, "max_line_length": 97, "avg_line_length": 56.46978021978022, "alnum_prop": 0.8110921916808562, "repo_name": "alinous-core/alinous-elastic-db", "id": "734be24caa61a155f2be7cf0bc8b96a700e34acc", "size": "20555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/src_java/alinous.runtime.dom.typed/ShortVariable.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7447" }, { "name": "C++", "bytes": "14486500" }, { "name": "CMake", "bytes": "223064" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p>hello</p> </body> </html>
{ "content_hash": "1ecc52925a9f6a424d431dfbd92c1a7c", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 72, "avg_line_length": 19, "alnum_prop": 0.6411483253588517, "repo_name": "rossedfort/rossedfort.github.io", "id": "9656ecbdfcf0e490ff92da14291570794ff9be9e", "size": "209", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1944" }, { "name": "HTML", "bytes": "8553" }, { "name": "JavaScript", "bytes": "105" } ], "symlink_target": "" }
/*global Backbone Store _ $ alert console Eulagy*/ Eulagy.Company = Backbone.Model.extend({ EMPTY: "empty company...", url: "/api/company" }); Eulagy.CompanyList = Backbone.Collection.extend({ model: Eulagy.Company, url: "/api/companies" }); Eulagy.Companies = new Eulagy.CompanyList(); Eulagy.CompanyView = Backbone.View.extend({ tagName: "li", template: _.template($('#company-template').html()), events: {}, initialize: function(){ _.bindAll(this, 'render'); }, render: function(){ $(this.el).html(this.template(this.model.toJSON())); $(this.el).find("a").attr("href", "#company/" + this.model.id); return this; } }); Eulagy.CompanyDetailView = Backbone.View.extend({ tagName: "div", template: _.template($('#company-detail-template').html()), events: {}, initialize: function(){ _.bindAll(this, 'render'); }, render: function(){ $(this.el).html(this.template(this.model.toJSON())); return this; } }); Eulagy.CompanyListView = Backbone.View.extend({ el: "#company_pane", events: {}, initialize: function(){ _.bindAll(this, 'render'); console.log("blars2", this); Eulagy.Companies.each(function(company, i, j, k){ var view_ = new Eulagy.CompanyView({ model: company }); this.$("#company_list").append(view_.render().el); }); }, render: function(){ Eulagy.Companies.each(function(){ console.log("blars"); }); } });
{ "content_hash": "760b58757d949bae7c929f93e8dbddaa", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 67, "avg_line_length": 18.444444444444443, "alnum_prop": 0.6010709504685409, "repo_name": "buttreygoodness/eulagy", "id": "89e518353509da9559d174e98a3c1a625b0fc8a9", "size": "1494", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/javascripts/app/company.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "143494" }, { "name": "Ruby", "bytes": "6019" } ], "symlink_target": "" }
<?php namespace Propel\Tests\Generator\Builder\Om; use Propel\Runtime\ActiveQuery\Criteria; use Propel\Runtime\ActiveQuery\ModelCriteria; use Propel\Runtime\ActiveQuery\ModelJoin; use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Map\TableMap; use Propel\Runtime\Propel; use Propel\Tests\Bookstore\AuthorQuery; use Propel\Tests\Bookstore\Map\AuthorTableMap; use Propel\Tests\Bookstore\Book; use Propel\Tests\Bookstore\BookQuery; use Propel\Tests\Bookstore\Map\BookTableMap; use Propel\Tests\Bookstore\BookstoreEmployeeAccountQuery; use Propel\Tests\Bookstore\Map\BookstoreEmployeeAccountTableMap; use Propel\Tests\Bookstore\BookClubListQuery; use Propel\Tests\Bookstore\BookOpinionQuery; use Propel\Tests\Bookstore\BookListRelQuery; use Propel\Tests\Bookstore\Map\BookListRelTableMap; use Propel\Tests\Bookstore\BookSummaryQuery; use Propel\Tests\Bookstore\EssayQuery; use Propel\Tests\Bookstore\ReviewQuery; use Propel\Tests\Bookstore\Map\ReviewTableMap; use Propel\Tests\Bookstore\ReaderFavoriteQuery; use Propel\Tests\Bookstore\Map\PublisherTableMap; use Propel\Tests\Bookstore\RecordLabelQuery; use Propel\Tests\Bookstore\Map\RecordLabelTableMap; use Propel\Tests\Bookstore\ReleasePoolQuery; use Propel\Tests\Bookstore\Map\ReleasePoolTableMap; use Propel\Tests\Helpers\Bookstore\BookstoreTestBase; use Propel\Tests\Helpers\Bookstore\BookstoreDataPopulator; use \ReflectionMethod; /** * Test class for QueryBuilder. * * @author François Zaninotto * * @group database */ class QueryBuilderTest extends BookstoreTestBase { protected function setUp() { parent::setUp(); include_once(__DIR__.'/QueryBuilderTestClasses.php'); } public function testExtends() { $q = new BookQuery(); $this->assertTrue($q instanceof ModelCriteria, 'Model query extends ModelCriteria'); } public function testConstructor() { $query = new BookQuery(); $this->assertEquals('bookstore', $query->getDbName(), 'Constructor sets dabatase name'); $this->assertEquals('Propel\Tests\Bookstore\Book', $query->getModelName(), 'Constructor sets model name'); } public function testCreate() { $query = BookQuery::create(); $this->assertTrue($query instanceof BookQuery, 'create() returns an object of its class'); $this->assertEquals('bookstore', $query->getDbName(), 'create() sets dabatase name'); $this->assertEquals('Propel\Tests\Bookstore\Book', $query->getModelName(), 'create() sets model name'); $query = BookQuery::create('foo'); $this->assertTrue($query instanceof BookQuery, 'create() returns an object of its class'); $this->assertEquals($query->getDbName(), 'bookstore', 'create() sets dabatase name'); $this->assertEquals('Propel\Tests\Bookstore\Book', $query->getModelName(), 'create() sets model name'); $this->assertEquals('foo', $query->getModelAlias(), 'create() can set the model alias'); } public function testCreateCustom() { // see the myBookQuery class definition at the end of this file $query = myCustomBookQuery::create(); $this->assertTrue($query instanceof myCustomBookQuery, 'create() returns an object of its class'); $this->assertTrue($query instanceof BookQuery, 'create() returns an object of its class'); $this->assertEquals('bookstore', $query->getDbName(), 'create() sets dabatase name'); $this->assertEquals('Propel\Tests\Bookstore\Book', $query->getModelName(), 'create() sets model name'); $query = myCustomBookQuery::create('foo'); $this->assertTrue($query instanceof myCustomBookQuery, 'create() returns an object of its class'); $this->assertEquals('bookstore', $query->getDbName(), 'create() sets dabatase name'); $this->assertEquals('Propel\Tests\Bookstore\Book', $query->getModelName(), 'create() sets model name'); $this->assertEquals('foo', $query->getModelAlias(), 'create() can set the model alias'); } public function testBasePreSelect() { $method = new ReflectionMethod('\Propel\Tests\Bookstore\Behavior\Table2Query', 'basePreSelect'); $this->assertEquals('Propel\Runtime\ActiveQuery\ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePreSelect() by default'); $method = new ReflectionMethod('\Propel\Tests\Bookstore\Behavior\Table3Query', 'basePreSelect'); $this->assertEquals('Propel\Tests\Bookstore\Behavior\Base\Table3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePreSelect() when a behavior is registered'); } public function testBasePreDelete() { $method = new ReflectionMethod('\Propel\Tests\Bookstore\Behavior\Table2Query', 'basePreDelete'); $this->assertEquals('Propel\Runtime\ActiveQuery\ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePreDelete() by default'); $method = new ReflectionMethod('\Propel\Tests\Bookstore\Behavior\Table3Query', 'basePreDelete'); $this->assertEquals('Propel\Tests\Bookstore\Behavior\Base\Table3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePreDelete() when a behavior is registered'); } public function testBasePostDelete() { $method = new ReflectionMethod('\Propel\Tests\Bookstore\Behavior\Table2Query', 'basePostDelete'); $this->assertEquals('Propel\Runtime\ActiveQuery\ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePostDelete() by default'); $method = new ReflectionMethod('\Propel\Tests\Bookstore\Behavior\Table3Query', 'basePostDelete'); $this->assertEquals('Propel\Tests\Bookstore\Behavior\Base\Table3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePostDelete() when a behavior is registered'); } public function testBasePreUpdate() { $method = new ReflectionMethod('\Propel\Tests\Bookstore\Behavior\Table2Query', 'basePreUpdate'); $this->assertEquals('Propel\Runtime\ActiveQuery\ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePreUpdate() by default'); $method = new ReflectionMethod('\Propel\Tests\Bookstore\Behavior\Table3Query', 'basePreUpdate'); $this->assertEquals('Propel\Tests\Bookstore\Behavior\Base\Table3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePreUpdate() when a behavior is registered'); } public function testBasePostUpdate() { $method = new ReflectionMethod('\Propel\Tests\Bookstore\Behavior\Table2Query', 'basePostUpdate'); $this->assertEquals('Propel\Runtime\ActiveQuery\ModelCriteria', $method->getDeclaringClass()->getName(), 'BaseQuery does not override basePostUpdate() by default'); $method = new ReflectionMethod('\Propel\Tests\Bookstore\Behavior\Table3Query', 'basePostUpdate'); $this->assertEquals('Propel\Tests\Bookstore\Behavior\Base\Table3Query', $method->getDeclaringClass()->getName(), 'BaseQuery overrides basePostUpdate() when a behavior is registered'); } public function testQuery() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); $q = new BookQuery(); $book = $q ->setModelAlias('b') ->where('b.Title like ?', 'Don%') ->orderBy('b.ISBN', 'desc') ->findOne(); $this->assertTrue($book instanceof Book); $this->assertEquals('Don Juan', $book->getTitle()); } public function testFindPk() { $method = new ReflectionMethod('\Propel\Tests\Bookstore\BookQuery', 'findPk'); $this->assertEquals('Propel\Tests\Bookstore\Base\BookQuery', $method->getDeclaringClass()->getName(), 'BaseQuery overrides findPk()'); } public function testFindPkReturnsCorrectObjectForSimplePrimaryKey() { $b = new Book(); $b->setTitle('bar'); $b->setISBN('FA404'); $b->save($this->con); $count = $this->con->getQueryCount(); BookTableMap::clearInstancePool(); $book = BookQuery::create()->findPk($b->getId(), $this->con); $this->assertEquals($b, $book); $this->assertEquals($count+1, $this->con->getQueryCount(), 'findPk() issues a database query when instance is not in pool'); } public function testFindPkUsesInstancePoolingForSimplePrimaryKey() { $b = new Book(); $b->setTitle('foo'); $b->setISBN('FA404'); $b->save($this->con); $count = $this->con->getQueryCount(); $book = BookQuery::create()->findPk($b->getId(), $this->con); $this->assertSame($b, $book); $this->assertEquals($count, $this->con->getQueryCount(), 'findPk() does not issue a database query when instance is in pool'); } public function testFindPkReturnsCorrectObjectForCompositePrimaryKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved $c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\Book'); $books = $c->find(); foreach ($books as $book) { $book->save(); } BookTableMap::clearInstancePool(); // retrieve the test data $c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\BookListRel'); $bookListRelTest = $c->findOne(); $pk = $bookListRelTest->getPrimaryKey(); $q = new BookListRelQuery(); $bookListRel = $q->findPk($pk); $this->assertEquals($bookListRelTest, $bookListRel, 'BaseQuery overrides findPk() for composite primary keysto make it faster'); } public function testFindPkUsesFindPkSimpleOnEmptyQueries() { BookQuery::create()->findPk(123, $this->con); $expected = 'SELECT id, title, isbn, price, publisher_id, author_id FROM book WHERE id = 123'; $this->assertEquals($expected, $this->con->getLastExecutedQuery()); } public function testFindPkSimpleAddsObjectToInstancePool() { $b = new Book(); $b->setTitle('foo'); $b->setISBN('FA404'); $b->save($this->con); BookTableMap::clearInstancePool(); BookQuery::create()->findPk($b->getId(), $this->con); $count = $this->con->getQueryCount(); $book = BookQuery::create()->findPk($b->getId(), $this->con); $this->assertEquals($b, $book); $this->assertEquals($count, $this->con->getQueryCount()); } public function testFindPkUsesFindPkComplexOnNonEmptyQueries() { BookQuery::create('b')->findPk(123, $this->con); $expected = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.id=123'); $this->assertEquals($expected, $this->con->getLastExecutedQuery()); } public function testFindPkNotUsesInstancePoolingForNonEmptyQueries() { $b = new Book(); $b->setTitle('foo'); $b->setISBN('FA404'); $b->save($this->con); $book = BookQuery::create()->select(['Book.Title', 'Book.ISBN'])->findPk($b->getId(), $this->con); $this->assertInternalType('array', $book); $book = BookQuery::create()->filterByTitle('bar')->findPk($b->getId(), $this->con); $this->assertNull($book); } public function testFindPkComplexAddsObjectToInstancePool() { $b = new Book(); $b->setTitle('foo'); $b->setISBN('FA404'); $b->save($this->con); BookTableMap::clearInstancePool(); BookQuery::create('b')->findPk($b->getId(), $this->con); $count = $this->con->getQueryCount(); $book = BookQuery::create()->findPk($b->getId(), $this->con); $this->assertEquals($b, $book); $this->assertEquals($count, $this->con->getQueryCount()); } public function testFindPkCallsPreSelect() { $q = new mySecondBookQuery(); $this->assertFalse($q::$preSelectWasCalled); $q->findPk(123); $this->assertTrue($q::$preSelectWasCalled); } public function testFindPks() { $method = new ReflectionMethod('\Propel\Tests\Bookstore\BookQuery', 'findPks'); $this->assertEquals('Propel\Tests\Bookstore\Base\BookQuery', $method->getDeclaringClass()->getName(), 'BaseQuery overrides findPks()'); } public function testFindPksSimpleKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); BookTableMap::clearInstancePool(); // prepare the test data $c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\Book'); $c->orderBy('Book.Id', 'desc'); $testBooks = $c->find(); $testBook1 = $testBooks->pop(); $testBook2 = $testBooks->pop(); $q = new BookQuery(); $books = $q->findPks([$testBook1->getId(), $testBook2->getId()]); $this->assertEquals([$testBook1, $testBook2], $books->getData(), 'BaseQuery overrides findPks() to make it faster'); } public function testFindPksCompositeKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved $c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\Book'); $books = $c->find(); foreach ($books as $book) { $book->save(); } BookTableMap::clearInstancePool(); // retrieve the test data $c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\BookListRel'); $bookListRelTest = $c->find(); $search = []; foreach ($bookListRelTest as $obj) { $search[]= $obj->getPrimaryKey(); } $q = new BookListRelQuery(); $objs = $q->findPks($search); $this->assertEquals($bookListRelTest->getArrayCopy(), $objs->getArrayCopy(), 'BaseQuery overrides findPks() for composite primary keys to make it work'); } public function testFilterBy() { foreach (BookTableMap::getFieldNames(TableMap::TYPE_PHPNAME) as $colName) { $filterMethod = 'filterBy' . $colName; $this->assertTrue(method_exists('\Propel\Tests\Bookstore\BookQuery', $filterMethod), 'QueryBuilder adds filterByColumn() methods for every column'); $q = BookQuery::create()->$filterMethod(1); $this->assertTrue($q instanceof BookQuery, 'filterByColumn() returns the current query instance'); } } public function testFilterByPrimaryKeySimpleKey() { $q = BookQuery::create()->filterByPrimaryKey(12); $q1 = BookQuery::create()->add(BookTableMap::COL_ID, 12, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByPrimaryKey() translates to a Criteria::EQUAL in the PK column'); $q = BookQuery::create()->setModelAlias('b', true)->filterByPrimaryKey(12); $q1 = BookQuery::create()->setModelAlias('b', true)->add('b.id', 12, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByPrimaryKey() uses true table alias if set'); } public function testFilterByPrimaryKeyCompositeKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved $c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\Book'); $books = $c->find(); foreach ($books as $book) { $book->save(); } BookTableMap::clearInstancePool(); // retrieve the test data $c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\BookListRel'); $bookListRelTest = $c->findOne(); $pk = $bookListRelTest->getPrimaryKey(); $q = new BookListRelQuery(); $q->filterByPrimaryKey($pk); $q1 = BookListRelQuery::create() ->add(BookListRelTableMap::COL_BOOK_ID, $pk[0], Criteria::EQUAL) ->add(BookListRelTableMap::COL_BOOK_CLUB_LIST_ID, $pk[1], Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByPrimaryKey() translates to a Criteria::EQUAL in the PK columns'); } public function testFilterByPrimaryKeysSimpleKey() { $q = BookQuery::create()->filterByPrimaryKeys([10, 11, 12]); $q1 = BookQuery::create()->add(BookTableMap::COL_ID, [10, 11, 12], Criteria::IN); $this->assertEquals($q1, $q, 'filterByPrimaryKeys() translates to a Criteria::IN on the PK column'); $q = BookQuery::create()->setModelAlias('b', true)->filterByPrimaryKeys([10, 11, 12]); $q1 = BookQuery::create()->setModelAlias('b', true)->add('b.id', [10, 11, 12], Criteria::IN); $this->assertEquals($q1, $q, 'filterByPrimaryKeys() uses true table alias if set'); } public function testFilterByPrimaryKeysCompositeKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved $c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\Book'); $books = $c->find(); foreach ($books as $book) { $book->save(); } BookTableMap::clearInstancePool(); // retrieve the test data $c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\BookListRel'); $bookListRelTest = $c->find(); $search = []; foreach ($bookListRelTest as $obj) { $search[]= $obj->getPrimaryKey(); } $q = new BookListRelQuery(); $q->filterByPrimaryKeys($search); $q1 = BookListRelQuery::create(); foreach ($search as $key) { $cton0 = $q1->getNewCriterion(BookListRelTableMap::COL_BOOK_ID, $key[0], Criteria::EQUAL); $cton1 = $q1->getNewCriterion(BookListRelTableMap::COL_BOOK_CLUB_LIST_ID, $key[1], Criteria::EQUAL); $cton0->addAnd($cton1); $q1->addOr($cton0); } $this->assertEquals($q1, $q, 'filterByPrimaryKeys() translates to a series of Criteria::EQUAL in the PK columns'); $q = new BookListRelQuery(); $q->filterByPrimaryKeys([]); $q1 = BookListRelQuery::create(); $q1->add(null, '1<>1', Criteria::CUSTOM); $this->assertEquals($q1, $q, 'filterByPrimaryKeys() translates to an always failing test on empty arrays'); } public function testFilterByIntegerPk() { $q = BookQuery::create()->filterById(12); $q1 = BookQuery::create()->add(BookTableMap::COL_ID, 12, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByPkColumn() translates to a Criteria::EQUAL by default'); $q = BookQuery::create()->filterById(12, Criteria::NOT_EQUAL); $q1 = BookQuery::create()->add(BookTableMap::COL_ID, 12, Criteria::NOT_EQUAL); $this->assertEquals($q1, $q, 'filterByPkColumn() accepts an optional comparison operator'); $q = BookQuery::create()->setModelAlias('b', true)->filterById(12); $q1 = BookQuery::create()->setModelAlias('b', true)->add('b.id', 12, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByPkColumn() uses true table alias if set'); $q = BookQuery::create()->filterById([10, 11, 12]); $q1 = BookQuery::create()->add(BookTableMap::COL_ID, [10, 11, 12], Criteria::IN); $this->assertEquals($q1, $q, 'filterByPkColumn() translates to a Criteria::IN when passed a simple array key'); $q = BookQuery::create()->filterById([10, 11, 12], Criteria::NOT_IN); $q1 = BookQuery::create()->add(BookTableMap::COL_ID, [10, 11, 12], Criteria::NOT_IN); $this->assertEquals($q1, $q, 'filterByPkColumn() accepts a comparison when passed a simple array key'); } public function testFilterByNumber() { $q = BookQuery::create()->filterByPrice(12); $q1 = BookQuery::create()->add(BookTableMap::COL_PRICE, 12, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::EQUAL by default'); $q = BookQuery::create()->filterByPrice(12, Criteria::NOT_EQUAL); $q1 = BookQuery::create()->add(BookTableMap::COL_PRICE, 12, Criteria::NOT_EQUAL); $this->assertEquals($q1, $q, 'filterByNumColumn() accepts an optional comparison operator'); $q = BookQuery::create()->setModelAlias('b', true)->filterByPrice(12); $q1 = BookQuery::create()->setModelAlias('b', true)->add('b.price', 12, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByNumColumn() uses true table alias if set'); $q = BookQuery::create()->filterByPrice([10, 11, 12]); $q1 = BookQuery::create()->add(BookTableMap::COL_PRICE, [10, 11, 12], Criteria::IN); $this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::IN when passed a simple array key'); $q = BookQuery::create()->filterByPrice([10, 11, 12], Criteria::NOT_IN); $q1 = BookQuery::create()->add(BookTableMap::COL_PRICE, [10, 11, 12], Criteria::NOT_IN); $this->assertEquals($q1, $q, 'filterByNumColumn() accepts a comparison when passed a simple array key'); $q = BookQuery::create()->filterByPrice(['min' => 10]); $q1 = BookQuery::create()->add(BookTableMap::COL_PRICE, 10, Criteria::GREATER_EQUAL); $this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::GREATER_EQUAL when passed a \'min\' key'); $q = BookQuery::create()->filterByPrice(['max' => 12]); $q1 = BookQuery::create()->add(BookTableMap::COL_PRICE, 12, Criteria::LESS_EQUAL); $this->assertEquals($q1, $q, 'filterByNumColumn() translates to a Criteria::LESS_EQUAL when passed a \'max\' key'); $q = BookQuery::create()->filterByPrice(['min' => 10, 'max' => 12]); $q1 = BookQuery::create() ->add(BookTableMap::COL_PRICE, 10, Criteria::GREATER_EQUAL) ->addAnd(BookTableMap::COL_PRICE, 12, Criteria::LESS_EQUAL); $this->assertEquals($q1, $q, 'filterByNumColumn() translates to a between when passed both a \'min\' and a \'max\' key'); } public function testFilterByTimestamp() { $q = BookstoreEmployeeAccountQuery::create()->filterByCreated(12); $q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountTableMap::COL_CREATED, 12, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByDateColumn() translates to a Criteria::EQUAL by default'); $q = BookstoreEmployeeAccountQuery::create()->filterByCreated(12, Criteria::NOT_EQUAL); $q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountTableMap::COL_CREATED, 12, Criteria::NOT_EQUAL); $this->assertEquals($q1, $q, 'filterByDateColumn() accepts an optional comparison operator'); $q = BookstoreEmployeeAccountQuery::create()->setModelAlias('b', true)->filterByCreated(12); $q1 = BookstoreEmployeeAccountQuery::create()->setModelAlias('b', true)->add('b.created', 12, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByDateColumn() uses true table alias if set'); $q = BookstoreEmployeeAccountQuery::create()->filterByCreated(['min' => 10]); $q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountTableMap::COL_CREATED, 10, Criteria::GREATER_EQUAL); $this->assertEquals($q1, $q, 'filterByDateColumn() translates to a Criteria::GREATER_EQUAL when passed a \'min\' key'); $q = BookstoreEmployeeAccountQuery::create()->filterByCreated(['max' => 12]); $q1 = BookstoreEmployeeAccountQuery::create()->add(BookstoreEmployeeAccountTableMap::COL_CREATED, 12, Criteria::LESS_EQUAL); $this->assertEquals($q1, $q, 'filterByDateColumn() translates to a Criteria::LESS_EQUAL when passed a \'max\' key'); $q = BookstoreEmployeeAccountQuery::create()->filterByCreated(['min' => 10, 'max' => 12]); $q1 = BookstoreEmployeeAccountQuery::create() ->add(BookstoreEmployeeAccountTableMap::COL_CREATED, 10, Criteria::GREATER_EQUAL) ->addAnd(BookstoreEmployeeAccountTableMap::COL_CREATED, 12, Criteria::LESS_EQUAL); $this->assertEquals($q1, $q, 'filterByDateColumn() translates to a between when passed both a \'min\' and a \'max\' key'); } public function testFilterByString() { $q = BookQuery::create()->filterByTitle('foo'); $q1 = BookQuery::create()->add(BookTableMap::COL_TITLE, 'foo', Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::EQUAL by default'); $q = BookQuery::create()->filterByTitle('foo', Criteria::NOT_EQUAL); $q1 = BookQuery::create()->add(BookTableMap::COL_TITLE, 'foo', Criteria::NOT_EQUAL); $this->assertEquals($q1, $q, 'filterByStringColumn() accepts an optional comparison operator'); $q = BookQuery::create()->setModelAlias('b', true)->filterByTitle('foo'); $q1 = BookQuery::create()->setModelAlias('b', true)->add('b.title', 'foo', Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByStringColumn() uses true table alias if set'); $q = BookQuery::create()->filterByTitle(['foo', 'bar']); $q1 = BookQuery::create()->add(BookTableMap::COL_TITLE, ['foo', 'bar'], Criteria::IN); $this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::IN when passed an array'); $q = BookQuery::create()->filterByTitle(['foo', 'bar'], Criteria::NOT_IN); $q1 = BookQuery::create()->add(BookTableMap::COL_TITLE, ['foo', 'bar'], Criteria::NOT_IN); $this->assertEquals($q1, $q, 'filterByStringColumn() accepts a comparison when passed an array'); $q = BookQuery::create()->filterByTitle('foo%'); $q1 = BookQuery::create()->add(BookTableMap::COL_TITLE, 'foo%', Criteria::LIKE); $this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::LIKE when passed a string with a % wildcard'); $q = BookQuery::create()->filterByTitle('foo%', Criteria::NOT_LIKE); $q1 = BookQuery::create()->add(BookTableMap::COL_TITLE, 'foo%', Criteria::NOT_LIKE); $this->assertEquals($q1, $q, 'filterByStringColumn() accepts a comparison when passed a string with a % wildcard'); $q = BookQuery::create()->filterByTitle('foo%', Criteria::EQUAL); $q1 = BookQuery::create()->add(BookTableMap::COL_TITLE, 'foo%', Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByStringColumn() accepts a comparison when passed a string with a % wildcard'); $q = BookQuery::create()->filterByTitle('*foo'); $q1 = BookQuery::create()->add(BookTableMap::COL_TITLE, '%foo', Criteria::LIKE); $this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::LIKE when passed a string with a * wildcard, and turns * into %'); $q = BookQuery::create()->filterByTitle('*f%o*o%'); $q1 = BookQuery::create()->add(BookTableMap::COL_TITLE, '%f%o%o%', Criteria::LIKE); $this->assertEquals($q1, $q, 'filterByStringColumn() translates to a Criteria::LIKE when passed a string with mixed wildcards, and turns *s into %s'); } public function testFilterByBoolean() { $q = ReviewQuery::create()->filterByRecommended(true); $q1 = ReviewQuery::create()->add(ReviewTableMap::COL_RECOMMENDED, true, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a Criteria::EQUAL by default'); $q = ReviewQuery::create()->filterByRecommended(true, Criteria::NOT_EQUAL); $q1 = ReviewQuery::create()->add(ReviewTableMap::COL_RECOMMENDED, true, Criteria::NOT_EQUAL); $this->assertEquals($q1, $q, 'filterByBooleanColumn() accepts an optional comparison operator'); $q = ReviewQuery::create()->filterByRecommended(false); $q1 = ReviewQuery::create()->add(ReviewTableMap::COL_RECOMMENDED, false, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a Criteria::EQUAL by default'); $q = ReviewQuery::create()->setModelAlias('b', true)->filterByRecommended(true); $q1 = ReviewQuery::create()->setModelAlias('b', true)->add('b.recommended', true, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByBooleanColumn() uses true table alias if set'); $q = ReviewQuery::create()->filterByRecommended('true'); $q1 = ReviewQuery::create()->add(ReviewTableMap::COL_RECOMMENDED, true, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = true when passed a true string'); $q = ReviewQuery::create()->filterByRecommended('yes'); $q1 = ReviewQuery::create()->add(ReviewTableMap::COL_RECOMMENDED, true, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = true when passed a true string'); $q = ReviewQuery::create()->filterByRecommended('1'); $q1 = ReviewQuery::create()->add(ReviewTableMap::COL_RECOMMENDED, true, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = true when passed a true string'); $q = ReviewQuery::create()->filterByRecommended('false'); $q1 = ReviewQuery::create()->add(ReviewTableMap::COL_RECOMMENDED, false, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = false when passed a false string'); $q = ReviewQuery::create()->filterByRecommended('no'); $q1 = ReviewQuery::create()->add(ReviewTableMap::COL_RECOMMENDED, false, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = false when passed a false string'); $q = ReviewQuery::create()->filterByRecommended('0'); $q1 = ReviewQuery::create()->add(ReviewTableMap::COL_RECOMMENDED, false, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = false when passed a false string'); $q = ReviewQuery::create()->filterByRecommended(''); $q1 = ReviewQuery::create()->add(ReviewTableMap::COL_RECOMMENDED, false, Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByBooleanColumn() translates to a = false when passed an empty string'); } public function testFilterByFk() { $this->assertTrue(method_exists('\Propel\Tests\Bookstore\BookQuery', 'filterByAuthor'), 'QueryBuilder adds filterByFk() methods'); $this->assertTrue(method_exists('\Propel\Tests\Bookstore\BookQuery', 'filterByPublisher'), 'QueryBuilder adds filterByFk() methods for all fkeys'); $this->assertTrue(method_exists('\Propel\Tests\Bookstore\EssayQuery', 'filterByFirstAuthor'), 'QueryBuilder adds filterByFk() methods for several fkeys on the same table'); $this->assertTrue(method_exists('\Propel\Tests\Bookstore\EssayQuery', 'filterBySecondAuthor'), 'QueryBuilder adds filterByFk() methods for several fkeys on the same table'); } public function testFilterByFkSimpleKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); // prepare the test data $testBook = BookQuery::create() ->innerJoin('Book.Author') // just in case there are books with no author ->findOne(); $testAuthor = $testBook->getAuthor(); $book = BookQuery::create() ->filterByAuthor($testAuthor) ->findOne(); $this->assertEquals($testBook, $book, 'Generated query handles filterByFk() methods correctly for simple fkeys'); $q = BookQuery::create()->filterByAuthor($testAuthor); $q1 = BookQuery::create()->add(BookTableMap::COL_AUTHOR_ID, $testAuthor->getId(), Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByFk() translates to a Criteria::EQUAL by default'); $q = BookQuery::create()->filterByAuthor($testAuthor, Criteria::NOT_EQUAL); $q1 = BookQuery::create()->add(BookTableMap::COL_AUTHOR_ID, $testAuthor->getId(), Criteria::NOT_EQUAL); $this->assertEquals($q1, $q, 'filterByFk() accepts an optional comparison operator'); } public function testFilterByFkCompositeKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); BookstoreDataPopulator::populateOpinionFavorite(); // prepare the test data $testOpinion = BookOpinionQuery::create() ->innerJoin('BookOpinion.ReaderFavorite') // just in case there are books with no author ->findOne(); $testFavorite = $testOpinion->getReaderFavorite(); $favorite = ReaderFavoriteQuery::create() ->filterByBookOpinion($testOpinion) ->findOne(); $this->assertEquals($testFavorite, $favorite, 'Generated query handles filterByFk() methods correctly for composite fkeys'); } public function testFilterByFkObjectCollection() { BookstoreDataPopulator::depopulate($this->con); BookstoreDataPopulator::populate($this->con); $authors = AuthorQuery::create() ->orderByFirstName() ->limit(2) ->find($this->con); $books = BookQuery::create() ->filterByAuthor($authors) ->find($this->con); $q1 = $this->con->getLastExecutedQuery(); $books = BookQuery::create() ->add(BookTableMap::COL_AUTHOR_ID, $authors->getPrimaryKeys(), Criteria::IN) ->find($this->con); $q2 = $this->con->getLastExecutedQuery(); $this->assertEquals($q2, $q1, 'filterByFk() accepts a collection and results to an IN query'); } public function testFilterByRefFk() { $this->assertTrue(method_exists('\Propel\Tests\Bookstore\BookQuery', 'filterByReview'), 'QueryBuilder adds filterByRefFk() methods'); $this->assertTrue(method_exists('\Propel\Tests\Bookstore\BookQuery', 'filterByMedia'), 'QueryBuilder adds filterByRefFk() methods for all fkeys'); $this->assertTrue(method_exists('\Propel\Tests\Bookstore\AuthorQuery', 'filterByEssayRelatedByFirstAuthorId'), 'QueryBuilder adds filterByRefFk() methods for several fkeys on the same table'); $this->assertTrue(method_exists('\Propel\Tests\Bookstore\AuthorQuery', 'filterByEssayRelatedBySecondAuthorId'), 'QueryBuilder adds filterByRefFk() methods for several fkeys on the same table'); } public function testFilterByRefFkSimpleKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); // prepare the test data $testBook = BookQuery::create() ->innerJoin('Book.Author') // just in case there are books with no author ->findOne(); $testAuthor = $testBook->getAuthor(); $author = AuthorQuery::create() ->filterByBook($testBook) ->findOne(); $this->assertEquals($testAuthor, $author, 'Generated query handles filterByRefFk() methods correctly for simple fkeys'); $q = AuthorQuery::create()->filterByBook($testBook); $q1 = AuthorQuery::create()->add(AuthorTableMap::COL_ID, $testBook->getAuthorId(), Criteria::EQUAL); $this->assertEquals($q1, $q, 'filterByRefFk() translates to a Criteria::EQUAL by default'); $q = AuthorQuery::create()->filterByBook($testBook, Criteria::NOT_EQUAL); $q1 = AuthorQuery::create()->add(AuthorTableMap::COL_ID, $testBook->getAuthorId(), Criteria::NOT_EQUAL); $this->assertEquals($q1, $q, 'filterByRefFk() accepts an optional comparison operator'); } public function testFilterByRelationNameCompositePk() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); $testLabel = RecordLabelQuery::create() ->limit(2) ->find($this->con); $testRelease = ReleasePoolQuery::create() ->addJoin(ReleasePoolTableMap::COL_RECORD_LABEL_ID, RecordLabelTableMap::COL_ID) ->filterByRecordLabel($testLabel) ->find($this->con); $q1 = $this->con->getLastExecutedQuery(); $releasePool = ReleasePoolQuery::create() ->addJoin(ReleasePoolTableMap::COL_RECORD_LABEL_ID, RecordLabelTableMap::COL_ID) ->add(ReleasePoolTableMap::COL_RECORD_LABEL_ID, $testLabel->toKeyValue('Id', 'Id'), Criteria::IN) ->find($this->con); $q2 = $this->con->getLastExecutedQuery(); $this->assertEquals($q2, $q1, 'filterBy{RelationName}() only accepts arguments of type {RelationName} or PropelCollection'); $this->assertEquals($releasePool, $testRelease); } public function testFilterByRefFkCompositeKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); BookstoreDataPopulator::populateOpinionFavorite(); // prepare the test data $testOpinion = BookOpinionQuery::create() ->innerJoin('BookOpinion.ReaderFavorite') // just in case there are books with no author ->findOne(); $testFavorite = $testOpinion->getReaderFavorite(); $opinion = BookOpinionQuery::create() ->filterByReaderFavorite($testFavorite) ->findOne(); $this->assertEquals($testOpinion, $opinion, 'Generated query handles filterByRefFk() methods correctly for composite fkeys'); } public function testFilterByRefFkObjectCollection() { BookstoreDataPopulator::depopulate($this->con); BookstoreDataPopulator::populate($this->con); $books = BookQuery::create() ->orderByTitle() ->limit(2) ->find($this->con); $authors = AuthorQuery::create() ->filterByBook($books) ->find($this->con); $q1 = $this->con->getLastExecutedQuery(); $authors = AuthorQuery::create() ->addJoin(AuthorTableMap::COL_ID, BookTableMap::COL_AUTHOR_ID, Criteria::LEFT_JOIN) ->add(BookTableMap::COL_ID, $books->getPrimaryKeys(), Criteria::IN) ->find($this->con); $q2 = $this->con->getLastExecutedQuery(); $this->assertEquals($q2, $q1, 'filterByRefFk() accepts a collection and results to an IN query in the joined table'); } public function testFilterByCrossFK() { $this->assertTrue(method_exists('\Propel\Tests\Bookstore\BookQuery', 'filterByBookClubList'), 'Generated query handles filterByCrossRefFK() for many-to-many relationships'); $this->assertFalse(method_exists('\Propel\Tests\Bookstore\BookQuery', 'filterByBook'), 'Generated query handles filterByCrossRefFK() for many-to-many relationships'); BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); $blc1 = BookClubListQuery::create()->findOneByGroupLeader('Crazyleggs'); $nbBooks = BookQuery::create() ->filterByBookClubList($blc1) ->count(); $this->assertEquals(2, $nbBooks, 'Generated query handles filterByCrossRefFK() methods correctly'); } public function testJoinFk() { $q = BookQuery::create() ->joinAuthor(); $q1 = BookQuery::create() ->join('Book.Author', Criteria::LEFT_JOIN); $this->assertTrue($q->equals($q1), 'joinFk() translates to a left join on non-required columns'); $q = BookSummaryQuery::create() ->joinSummarizedBook(); $q1 = BookSummaryQuery::create() ->join('BookSummary.SummarizedBook', Criteria::INNER_JOIN); $this->assertTrue($q->equals($q1), 'joinFk() translates to an inner join on required columns'); $q = BookQuery::create() ->joinAuthor('a'); $q1 = BookQuery::create() ->join('Book.Author a', Criteria::LEFT_JOIN); $this->assertTrue($q->equals($q1), 'joinFk() accepts a relation alias as first parameter'); $q = BookQuery::create() ->joinAuthor('', Criteria::INNER_JOIN); $q1 = BookQuery::create() ->join('Book.Author', Criteria::INNER_JOIN); $this->assertTrue($q->equals($q1), 'joinFk() accepts a join type as second parameter'); $q = EssayQuery::create() ->innerJoinSecondAuthor(); $q1 = EssayQuery::create() ->join('Essay.SecondAuthor', "INNER JOIN"); $this->assertTrue($q->equals($q1), 'joinFk() translates to a "INNER JOIN" when this is defined as defaultJoin in the schema'); } public function testJoinFkAlias() { $q = BookQuery::create('b') ->joinAuthor('a'); $q1 = BookQuery::create('b') ->join('b.Author a', Criteria::LEFT_JOIN); $this->assertTrue($q->equals($q1), 'joinFk() works fine with table aliases'); $q = BookQuery::create() ->setModelAlias('b', true) ->joinAuthor('a'); $q1 = BookQuery::create() ->setModelAlias('b', true) ->join('b.Author a', Criteria::LEFT_JOIN); $this->assertTrue($q->equals($q1), 'joinFk() works fine with true table aliases'); } public function testJoinRefFk() { $q = AuthorQuery::create() ->joinBook(); $q1 = AuthorQuery::create() ->join('Author.Book', Criteria::LEFT_JOIN); $this->assertTrue($q->equals($q1), 'joinRefFk() translates to a left join on non-required columns'); $q = BookQuery::create() ->joinBookSummary(); $q1 = BookQuery::create() ->join('Book.BookSummary', Criteria::INNER_JOIN); $this->assertTrue($q->equals($q1), 'joinRefFk() translates to an inner join on required columns'); $q = AuthorQuery::create() ->joinBook('b'); $q1 = AuthorQuery::create() ->join('Author.Book b', Criteria::LEFT_JOIN); $this->assertTrue($q->equals($q1), 'joinRefFk() accepts a relation alias as first parameter'); $q = AuthorQuery::create() ->joinBook('', Criteria::INNER_JOIN); $q1 = AuthorQuery::create() ->join('Author.Book', Criteria::INNER_JOIN); $this->assertTrue($q->equals($q1), 'joinRefFk() accepts a join type as second parameter'); $q = AuthorQuery::create() ->joinEssayRelatedBySecondAuthorId(); $q1 = AuthorQuery::create() ->join('Author.EssayRelatedBySecondAuthorId', Criteria::INNER_JOIN); $this->assertTrue($q->equals($q1), 'joinRefFk() translates to a "INNER JOIN" when this is defined as defaultJoin in the schema'); } public function testUseFkQuerySimple() { $q = BookQuery::create() ->useAuthorQuery() ->filterByFirstName('Leo') ->endUse(); $q1 = BookQuery::create() ->join('Book.Author', Criteria::LEFT_JOIN) ->add(AuthorTableMap::COL_FIRST_NAME, 'Leo', Criteria::EQUAL); $this->assertTrue($q->equals($q1), 'useFkQuery() translates to a condition on a left join on non-required columns'); $q = BookSummaryQuery::create() ->useSummarizedBookQuery() ->filterByTitle('War And Peace') ->endUse(); $q1 = BookSummaryQuery::create() ->join('BookSummary.SummarizedBook', Criteria::INNER_JOIN) ->add(BookTableMap::COL_TITLE, 'War And Peace', Criteria::EQUAL); $this->assertTrue($q->equals($q1), 'useFkQuery() translates to a condition on an inner join on required columns'); } public function testUseFkQueryJoinType() { $q = BookQuery::create() ->useAuthorQuery(null, Criteria::LEFT_JOIN) ->filterByFirstName('Leo') ->endUse(); $q1 = BookQuery::create() ->join('Book.Author', Criteria::LEFT_JOIN) ->add(AuthorTableMap::COL_FIRST_NAME, 'Leo', Criteria::EQUAL); $this->assertTrue($q->equals($q1), 'useFkQuery() accepts a join type as second parameter'); } public function testUseFkQueryAlias() { $q = BookQuery::create() ->useAuthorQuery('a') ->filterByFirstName('Leo') ->endUse(); $join = new ModelJoin(); $join->setJoinType(Criteria::LEFT_JOIN); $join->setTableMap(AuthorTableMap::getTableMap()); $join->setRelationMap(BookTableMap::getTableMap()->getRelation('Author'), null, 'a'); $join->setRelationAlias('a'); $q1 = BookQuery::create() ->addAlias('a', AuthorTableMap::TABLE_NAME) ->addJoinObject($join, 'a') ->add('a.first_name', 'Leo', Criteria::EQUAL); $this->assertTrue($q->equals($q1), 'useFkQuery() uses the first argument as a table alias'); } public function testUseFkQueryMixed() { $q = BookQuery::create() ->useAuthorQuery() ->filterByFirstName('Leo') ->endUse() ->filterByTitle('War And Peace'); $q1 = BookQuery::create() ->join('Book.Author', Criteria::LEFT_JOIN) ->add(AuthorTableMap::COL_FIRST_NAME, 'Leo', Criteria::EQUAL) ->add(BookTableMap::COL_TITLE, 'War And Peace', Criteria::EQUAL); $this->assertTrue($q->equals($q1), 'useFkQuery() allows combining conditions on main and related query'); } public function testUseFkQueryTwice() { $q = BookQuery::create() ->useAuthorQuery() ->filterByFirstName('Leo') ->endUse() ->useAuthorQuery() ->filterByLastName('Tolstoi') ->endUse(); $q1 = BookQuery::create() ->join('Book.Author', Criteria::LEFT_JOIN) ->add(AuthorTableMap::COL_FIRST_NAME, 'Leo', Criteria::EQUAL) ->add(AuthorTableMap::COL_LAST_NAME, 'Tolstoi', Criteria::EQUAL); $this->assertTrue($q->equals($q1), 'useFkQuery() called twice on the same relation does not create two joins'); } public function testUseFkQueryTwiceTwoAliases() { $q = BookQuery::create() ->useAuthorQuery('a') ->filterByFirstName('Leo') ->endUse() ->useAuthorQuery('b') ->filterByLastName('Tolstoi') ->endUse(); $join1 = new ModelJoin(); $join1->setJoinType(Criteria::LEFT_JOIN); $join1->setTableMap(AuthorTableMap::getTableMap()); $join1->setRelationMap(BookTableMap::getTableMap()->getRelation('Author'), null, 'a'); $join1->setRelationAlias('a'); $join2 = new ModelJoin(); $join2->setJoinType(Criteria::LEFT_JOIN); $join2->setTableMap(AuthorTableMap::getTableMap()); $join2->setRelationMap(BookTableMap::getTableMap()->getRelation('Author'), null, 'b'); $join2->setRelationAlias('b'); $q1 = BookQuery::create() ->addAlias('a', AuthorTableMap::TABLE_NAME) ->addJoinObject($join1, 'a') ->add('a.first_name', 'Leo', Criteria::EQUAL) ->addAlias('b', AuthorTableMap::TABLE_NAME) ->addJoinObject($join2, 'b') ->add('b.last_name', 'Tolstoi', Criteria::EQUAL); $this->assertTrue($q->equals($q1), 'useFkQuery() called twice on the same relation with two aliases creates two joins'); } public function testUseFkQueryNested() { $q = ReviewQuery::create() ->useBookQuery() ->useAuthorQuery() ->filterByFirstName('Leo') ->endUse() ->endUse(); $q1 = ReviewQuery::create() ->join('Review.Book', Criteria::LEFT_JOIN) ->join('Book.Author', Criteria::LEFT_JOIN) ->add(AuthorTableMap::COL_FIRST_NAME, 'Leo', Criteria::EQUAL); // embedded queries create joins that keep a relation to the parent // as this is not testable, we need to use another testing technique $params = []; $result = $q->createSelectSql($params); $expectedParams = []; $expectedResult = $q1->createSelectSql($expectedParams); $this->assertEquals($expectedParams, $params, 'useFkQuery() called nested creates two joins'); $this->assertEquals($expectedResult, $result, 'useFkQuery() called nested creates two joins'); } public function testUseFkQueryTwoRelations() { $q = BookQuery::create() ->useAuthorQuery() ->filterByFirstName('Leo') ->endUse() ->usePublisherQuery() ->filterByName('Penguin') ->endUse(); $q1 = BookQuery::create() ->join('\Propel\Tests\Bookstore\Book.Author', Criteria::LEFT_JOIN) ->add(AuthorTableMap::COL_FIRST_NAME, 'Leo', Criteria::EQUAL) ->join('\Propel\Tests\Bookstore\Book.Publisher', Criteria::LEFT_JOIN) ->add(PublisherTableMap::COL_NAME, 'Penguin', Criteria::EQUAL); $this->assertTrue($q->equals($q1), 'useFkQuery() called twice on two relations creates two joins'); } public function testUseFkQueryNoAliasThenWith() { $con = Propel::getServiceContainer()->getReadConnection(BookTableMap::DATABASE_NAME); $books = BookQuery::create() ->useAuthorQuery() ->filterByFirstName('Leo') ->endUse() ->with('Author') ->find($con); $q1 = $con->getLastExecutedQuery(); $books = BookQuery::create() ->leftJoinWithAuthor() ->add(AuthorTableMap::COL_FIRST_NAME, 'Leo', Criteria::EQUAL) ->find($con); $q2 = $con->getLastExecutedQuery(); $this->assertEquals($q1, $q2, 'with() can be used after a call to useFkQuery() with no alias'); } public function testPrune() { $q = BookQuery::create()->prune(); $this->assertTrue($q instanceof BookQuery, 'prune() returns the current Query object'); } public function testPruneSimpleKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); $nbBooks = BookQuery::create()->prune()->count(); $this->assertEquals(4, $nbBooks, 'prune() does nothing when passed a null object'); $testBook = BookQuery::create()->findOne(); $nbBooks = BookQuery::create()->prune($testBook)->count(); $this->assertEquals(3, $nbBooks, 'prune() removes an object from the result'); } public function testPruneCompositeKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved $c = new ModelCriteria('bookstore', '\Propel\Tests\Bookstore\Book'); $books = $c->find(); foreach ($books as $book) { $book->save(); } BookTableMap::clearInstancePool(); $nbBookListRel = BookListRelQuery::create()->prune()->count(); $this->assertEquals(2, $nbBookListRel, 'prune() does nothing when passed a null object'); $testBookListRel = BookListRelQuery::create()->findOne(); $nbBookListRel = BookListRelQuery::create()->prune($testBookListRel)->count(); $this->assertEquals(1, $nbBookListRel, 'prune() removes an object from the result'); } }
{ "content_hash": "fc3539626693a396e5bc1839fd105b3d", "timestamp": "", "source": "github", "line_count": 1096, "max_line_length": 201, "avg_line_length": 47.23448905109489, "alnum_prop": 0.6349166489598022, "repo_name": "jeremydenoun/Propel2", "id": "599eb71ddd193b8074bb84b66b073764cd2ac9ba", "size": "51975", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tests/Propel/Tests/Generator/Builder/Om/QueryBuilderTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2909" }, { "name": "Gherkin", "bytes": "450" }, { "name": "PHP", "bytes": "4625210" }, { "name": "Shell", "bytes": "2835" }, { "name": "XSLT", "bytes": "74572" } ], "symlink_target": "" }
export default class MockNativeSensorModule { addListener = jest.fn(async () => {}); removeListeners = jest.fn(async () => {}); startObserving = jest.fn(async () => {}); stopObserving = jest.fn(async () => {}); setUpdateInterval = jest.fn(async () => {}); }
{ "content_hash": "2cc818bdb350f369e13aa8b001c3f4cb", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 46, "avg_line_length": 38.285714285714285, "alnum_prop": 0.6156716417910447, "repo_name": "exponent/exponent", "id": "baed66501ff2cd74aad8bb33526634a51bff8335", "size": "268", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/expo-sensors/src/__tests__/mocks/MockNativeSensorModule.ts", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "113276" }, { "name": "Batchfile", "bytes": "127" }, { "name": "C", "bytes": "1744836" }, { "name": "C++", "bytes": "1801159" }, { "name": "CSS", "bytes": "7854" }, { "name": "HTML", "bytes": "176329" }, { "name": "IDL", "bytes": "897" }, { "name": "Java", "bytes": "6251130" }, { "name": "JavaScript", "bytes": "4416558" }, { "name": "Makefile", "bytes": "18061" }, { "name": "Objective-C", "bytes": "13971362" }, { "name": "Objective-C++", "bytes": "725480" }, { "name": "Perl", "bytes": "5860" }, { "name": "Prolog", "bytes": "287" }, { "name": "Python", "bytes": "125673" }, { "name": "Ruby", "bytes": "61190" }, { "name": "Shell", "bytes": "4441" } ], "symlink_target": "" }
import json import re import defusedxml.ElementTree as et from geowatchutil.base import GeoWatchError from geowatchutil.broker.base import GeoWatchBroker from geowatchutil.codec.geowatch_codec_slack import GeoWatchCodecSlack from slackbotosm.enumerations import URL_PROJECT_VIEW, URL_PROJECT_EDIT, URL_PROJECT_TASKS, URL_CHANGESET_API from slackbotosm.mapping.base import GeoWatchMappingProject, GeoWatchMappingChangeset from slackbotosm.utils import load_patterns class SlackBotOSMBroker(GeoWatchBroker): """ Broker for Slack Bot for OpenStreetMap """ _user_id = None # Dervied from consumer authtoken _user_name = None # Dervied from consumer authtoken patterns = None def _make_request(self, url, params=None, data=None, cookie=None, contentType=None): """ Prepares a request from a url, params, and optionally authentication. """ import urllib import urllib2 if params: url = url + '?' + urllib.urlencode(params) req = urllib2.Request(url, data=data) if cookie: req.add_header('Cookie', cookie) if contentType: req.add_header('Content-type', contentType) else: if data: req.add_header('Content-type', 'text/xml') return urllib2.urlopen(req) def _pre(self): pass def _post(self, messages=None): for m in messages: msgtype = m[u'type'] if msgtype == u'hello': # slack always open up connection with hello message pass elif msgtype == u'message': msgsubtype = m.get(u'subtype', None) if msgsubtype == u'bot_message': username = m[u'username'] text = m[u'text'] pass elif msgsubtype == u'message_deleted': pass else: user = m[u'user'] text = m[u'text'] channel = m[u'channel'] #print "testing Message", m match_question = None match_value = None for question in self.patterns: for pattern in self.patterns[question]: match_value = re.search(pattern, text, re.M|re.I) if match_value: match_question = question break if match_value: break if match_value: outgoing = None print "Match Question: ", match_question print "Match Value: ", match_value if match_question == "project": try: ctx = self._request_project(match_value.group("project"), URL_PROJECT_TASKS) t = self.templates.get('SLACK_MESSAGE_TEMPLATE_PROJECT', None) if t: outgoing = self.codec_slack.render(ctx, t=t) except: print "Error processing match for original text: ", text elif match_question == "changeset": try: ctx = self._request_changeset(match_value.group("changeset"), URL_CHANGESET_API) t = self.templates.get('SLACK_MESSAGE_TEMPLATE_CHANGESET', None) if t: outgoing = self.codec_slack.render(ctx, t=t) except: print "Error processing match for original text: ", text raise if outgoing: print "Sending message ..." print "+ Data = ", outgoing self.duplex[0]._channel.send_message(outgoing, topic=channel) def _request_project(self, project, baseurl): url = baseurl.format(project=project) request = self._make_request(url, contentType="application/json") if request.getcode () != 200: raise Exception("Could not fetch json for project "+project+".") response = request.read() data = json.loads(response) counter = { "0": 0, "1": 0, "2": 0, "3": 0, "-1": 0 } for f in data[u'features']: p = f[u'properties'] state = str(p.get(u'state', None)) counter[state] = counter[state] + 1 return GeoWatchMappingProject().forward(project=int(project), counter=counter) def _request_changeset(self, changesetID, baseurl): url = baseurl.format(changeset=changesetID) request = self._make_request(url, contentType="text/xml") if request.getcode () != 200: raise Exception("Could not fetch xml for changeset "+changesetID+".") response = request.read() root = et.fromstring(response) kwargs = { 'id': changesetID } for changeset in root.findall('changeset'): kwargs['user'] = changeset.get('user') kwargs['closed_at'] = changeset.get('closed_at') for tag in changeset.findall('tag'): kwargs[tag.get('k')] = tag.get('v', '') return GeoWatchMappingChangeset().forward(**kwargs) def _req_user(self, messages): passs def __init__(self, name, description, templates=None, duplex=None, consumers=None, producers=None, stores_out=None, filter_metadata=None, sleep_period=5, count=1, timeout=5, deduplicate=False, verbose=False): # noqa super(SlackBotOSMBroker, self).__init__( name, description, duplex=duplex, consumers=consumers, producers=producers, stores_out=stores_out, count=count, threads=1, sleep_period=sleep_period, timeout=timeout, deduplicate=deduplicate, filter_metadata=filter_metadata, verbose=verbose) self.templates = templates # loaded from templates.yml self._user_id = self.duplex[0]._client._user_id self._user_name = self.duplex[0]._client._user_name self.codec_slack = GeoWatchCodecSlack() self.patterns = load_patterns()
{ "content_hash": "07596c550d50323d693de6933e95e7a3", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 220, "avg_line_length": 36.93333333333333, "alnum_prop": 0.5186522262334536, "repo_name": "pjdufour/slackbot-osm", "id": "4f71e3a34fe2637063effee238ceb816b004ee70", "size": "6648", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "slackbotosm/broker/base.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "11550" }, { "name": "Shell", "bytes": "1106" } ], "symlink_target": "" }
These settings apply only when `--go` is specified on the command line. ``` yaml $(go) go: license-header: MICROSOFT_APACHE_NO_VERSION namespace: keyvault clear-output-folder: true ``` ### Go multi-api ``` yaml $(go) && $(multiapi) batch: - tag: package-7.2-preview - tag: package-7.1-preview - tag: package-7.0 - tag: package-2016-10 - tag: package-2015-06 ``` ### Tag: package-7.2-preview and go These settings apply only when `--tag=package-7.2-preview --go` is specified on the command line. Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`. ``` yaml $(tag) == 'package-7.2-preview' && $(go) output-folder: $(go-sdk-folder)/services/preview/$(namespace)/v7.2-preview/$(namespace) ``` ### Tag: package-7.1-preview and go These settings apply only when `--tag=package-7.1-preview --go` is specified on the command line. Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`. ``` yaml $(tag) == 'package-7.1-preview' && $(go) output-folder: $(go-sdk-folder)/services/preview/$(namespace)/v7.1-preview/$(namespace) ``` ### Tag: package-7.0 and go These settings apply only when `--tag=package-7.0 --go` is specified on the command line. Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`. ``` yaml $(tag) == 'package-7.0' && $(go) output-folder: $(go-sdk-folder)/services/$(namespace)/v7.0/$(namespace) ``` ### Tag: package-2016-10 and go These settings apply only when `--tag=package-2016-10 --go` is specified on the command line. Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`. ``` yaml $(tag) == 'package-2016-10' && $(go) output-folder: $(go-sdk-folder)/services/$(namespace)/2016-10-01/$(namespace) ``` ### Tag: package-2015-06 and go These settings apply only when `--tag=package-2015-06 --go` is specified on the command line. Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`. ``` yaml $(tag) == 'package-2015-06' && $(go) output-folder: $(go-sdk-folder)/services/$(namespace)/2015-06-01/$(namespace) ```
{ "content_hash": "f0a4fc1447f2376c9608a41e5356b85b", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 98, "avg_line_length": 34.15625, "alnum_prop": 0.6829826166514181, "repo_name": "hyonholee/azure-rest-api-specs", "id": "cb56a1deb4dc4131a1e178fb66b40aea34e9852d", "size": "2193", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "specification/keyvault/data-plane/readme.go.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1418" }, { "name": "Shell", "bytes": "621" }, { "name": "TypeScript", "bytes": "25948" } ], "symlink_target": "" }
@echo off rem configs/z8f64200100kit/scripts/setenv.bat rem rem Copyright (C) 2012 Gregory Nutt. All rights reserved. rem Author: Gregory Nutt <gnutt@nuttx.org> rem rem Redistribution and use in source and binary forms, with or without rem modification, are permitted provided that the following conditions rem are met: rem rem 1. Redistributions of source code must retain the above copyright rem notice, this list of conditions and the following disclaimer. rem 2. Redistributions in binary form must reproduce the above copyright rem notice, this list of conditions and the following disclaimer in rem the documentation and/or other materials provided with the rem distribution. rem 3. Neither the name NuttX nor the names of its contributors may be rem used to endorse or promote products derived from this software rem without specific prior written permission. rem rem THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS rem "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT rem LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS rem FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE rem COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, rem INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, rem BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS rem OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED rem AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT rem LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN rem ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE rem POSSIBILITY OF SUCH DAMAGE. rem This is the location where I installed in the MinGW compiler. With rem this configuration, it is recommended that you do NOT install the rem MSYS tools; they conflict with the GNUWin32 tools. See rem http://www.mingw.org/ for further info. set PATH=C:\MinGW\bin;%PATH% rem This is the location where I installed the ZDS-II toolchain. set PATH=C:\Program Files (x86)\ZiLOG\ZDSII_Z8Encore!_5.0.0\bin;%PATH% rem This is the location where I installed the GNUWin32 tools. See rem http://gnuwin32.sourceforge.net/. set PATH=C:\gnuwin32\bin;%PATH% echo %PATH%
{ "content_hash": "8c854c3c78b30767c020cbb3186c6271", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 73, "avg_line_length": 46.26, "alnum_prop": 0.7751837440553394, "repo_name": "IUTInfoAix/terrarium_2015", "id": "e0526d988a8aa273acde25ccc756eed8f05bdc90", "size": "2313", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "nuttx/configs/z8f64200100kit/scripts/setenv.bat", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "1031371" }, { "name": "Bison", "bytes": "30076" }, { "name": "C", "bytes": "64458265" }, { "name": "C++", "bytes": "1383737" }, { "name": "CSS", "bytes": "1959" }, { "name": "Groff", "bytes": "60038" }, { "name": "HTML", "bytes": "1910" }, { "name": "JavaScript", "bytes": "2355" }, { "name": "Makefile", "bytes": "1243982" }, { "name": "Objective-C", "bytes": "1888974" }, { "name": "PHP", "bytes": "471" }, { "name": "Pascal", "bytes": "253088" }, { "name": "Perl", "bytes": "606911" }, { "name": "Python", "bytes": "13656" }, { "name": "R", "bytes": "40046" }, { "name": "Shell", "bytes": "1511569" }, { "name": "Tcl", "bytes": "126857" }, { "name": "Visual Basic", "bytes": "8382" } ], "symlink_target": "" }
<!doctype html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="gb2312"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content="Kanban Board"> <meta name="viewport" content="width=device-width"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="styles/4198d9ac.main.css"> <link rel="stylesheet" href="styles/themes/default-bright.css" id="themeStylesheet"> </head> <body ng-app="mpk" ng-controller="ApplicationController" ui-keyup="{'ctrl-shift-72':'openHelpShortcut($event)'}"> <!--[if lt IE 7]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <!--[if lt IE 9]> <script src="bower_components/es5-shim/es5-shim.js" charset="gbk"></script> <script src="bower_components/json3/lib/json3.min.js" charset="gbk"></script> <![endif]--> <!-- Add your site or application content here --> <header class="navbar navbar-fixed-top" role="navigation" id="headerMenu"> <div class="navbar-inner"> <div class="container"> <div class="navbar-header col-md-3"> <span id="kanbanName" class="navbar-brand" ng-model="kanban" ng-hide="editingName"><a href="#" class="renameKanban" ng-click="editingKanbanName()">{{kanban.name}}</a></span> <div ng-show="editingName" class="pull-left"> <form ng-submit="rename()"> <div class="input-group"> <span class="input-group-addon"> <a href="#cancel" ng-click="editingName=false"><i class="glyphicon glyphicon-tasks"></i></a> </span> <input type="text" name="kanbanName" ng-model="newName" class="form-control"> </div> </form> </div> </div> <div class="col-md-4"> <div id="info" class="nav pull-right" ng-show="showInfo"> <span id="error" class="error" ng-show="showError"><a href="#close" ng-click="showInfo=false;showError=false;errorMessage=''">{{errorMessage}}</a></span> <span id="message" class="">{{infoMessage}}</span> <span id="spinner" class="pull-right" spin="spinConfig" spin-if="showSpinner"></span> </div> <div id="quickSwitch" class="pull-right form-group"> <form> <select ng-model="switchTo" ng-options="name for name in switchToList" ng-change="switchToKanban(switchTo)"> <option>Çл»ÊÔÑéÊÒ ...</option> </select> </form> </div> </div> <div class="col-md-4"> <div id="info" class="nav pull-right" ng-show="showInfo"> <span id="spinner" class="pull-right" spin="spinConfig" spin-if="showSpinner"></span> </div> <div id="historytask" class="pull-right form-group"> <span >ÀúÊ·ÈÎÎñ</span> </div> </div> </div> </div> </header> <div class="container-fluid" id="kanban" ng-controller="KanbanController"> </div> <footer> </footer> <script src="bower_components/jquery/jquery.min.js"></script> <script src="bower_components/angular/angular.min.js"></script> <script src="bower_components/angular-sanitize/angular-sanitize.min.js"></script> <script src="bower_components/angular-ui-bootstrap-bower/ui-bootstrap.min.js"></script> <script src="bower_components/angular-ui-bootstrap-bower/ui-bootstrap-tpls.min.js"></script> <script src="bower_components/jquery-ui/ui/minified/jquery-ui.min.js"></script> <script src="bower_components/angular-ui-utils/ui-utils.min.js"></script> <script src="bower_components/spinjs/spin.js"></script> <script src="bower_components/FileSaver/FileSaver.js"></script> <script src="scripts/5ebce75f.themes.js"></script> <script src="../My97DatePickerBeta/My97DatePicker/WdatePicker.js"></script> <script src="scripts/c7192975.scripts.js" charset="gbk"></script> </body> </html>
{ "content_hash": "ff5b96f19497d8ae123a280bc79e0f48", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 181, "avg_line_length": 48.13186813186813, "alnum_prop": 0.6082191780821918, "repo_name": "majj/tems", "id": "b37f839e57fe7acdb3bb36476366baee4c94289f", "size": "4380", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "html/kanban/historytask.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "270511" }, { "name": "JavaScript", "bytes": "2077838" }, { "name": "PHP", "bytes": "6763" }, { "name": "Python", "bytes": "1277" } ], "symlink_target": "" }
<Customer CustomerID="CACTU"> <CompanyName>Cactus Comidas para llevar</CompanyName> <ContactName>Patricio Simpson</ContactName> <ContactTitle>Sales Agent</ContactTitle> <Address>Cerrito 333</Address> <City>Buenos Aires</City> <Region/> <PostalCode>1010</PostalCode> <Country>Argentina</Country> <Phone>(1) 135-5555</Phone> <Fax>(1) 135-4892</Fax> </Customer>
{ "content_hash": "806099cdc0b180d5c501d2337365235c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 54, "avg_line_length": 28.46153846153846, "alnum_prop": 0.7432432432432432, "repo_name": "rashiatmarklogic/entity-services", "id": "708d6e1230c709b086a3d547d7d0701fc38c0d7b", "size": "370", "binary": false, "copies": "7", "ref": "refs/heads/develop", "path": "entity-services-functionaltests/src/main/resources/northwind/customers/CACTU.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "294019" }, { "name": "XQuery", "bytes": "551806" } ], "symlink_target": "" }
package yang // This file implements the functions relating to types and typedefs. import ( "errors" "fmt" "regexp/syntax" "sync" ) // A TypeDictionary is a dictonary of all Typedefs defined in all Typedefers. // A map of Nodes is used rather than a map of Typedefers to simplify usage // when traversing up a Node tree. type TypeDictionary struct { mu sync.Mutex dict map[Node]map[string]*Typedef } // TypeDict is a protected global dictionary of all typedefs. // TODO(borman): should this be made as part of some other structure, rather // than a singleton. That can be done later when we replumb everything to more // or less pass around an extra pointer. That is not needed until such time // that we plan for a single application to process completely independent YANG // modules where there may be conflicts between the modules or we plan to // process them completely independently of eachother. var TypeDict = TypeDictionary{dict: map[Node]map[string]*Typedef{}} // add adds an entry to the TypeDictionary d. func (d *TypeDictionary) add(n Node, name string, td *Typedef) { defer d.mu.Unlock() d.mu.Lock() if d.dict[n] == nil { d.dict[n] = map[string]*Typedef{} } d.dict[n][name] = td } // find returns the Typedef name define in node n, or nil. func (d *TypeDictionary) find(n Node, name string) *Typedef { defer d.mu.Unlock() d.mu.Lock() if d.dict[n] == nil { return nil } return d.dict[n][name] } // findExternal finds the externally defined typedef name in the module imported // by n's root with the specified prefix. func (d *TypeDictionary) findExternal(n Node, prefix, name string) (*Typedef, error) { root := FindModuleByPrefix(n, prefix) if root == nil { return nil, fmt.Errorf("%s: unknown prefix: %s for type %s", Source(n), prefix, name) } if td := d.find(root, name); td != nil { return td, nil } if prefix != "" { name = prefix + ":" + name } return nil, fmt.Errorf("%s: unknown type %s", Source(n), name) } // Typedefs returns a slice of all typedefs in d. func (d *TypeDictionary) Typedefs() []*Typedef { var tds []*Typedef defer d.mu.Unlock() d.mu.Lock() for _, dict := range d.dict { for _, td := range dict { tds = append(tds, td) } } return tds } // addTypedefs is called from BuildAST after each Typedefer is defined. There // are no error conditions in this process as it is simply used to build up the // typedef dictionary. func addTypedefs(t Typedefer) { for _, td := range t.Typedefs() { TypeDict.add(t, td.Name, td) } } // resolveTypedefs is called after all of modules and submodules have been read, // as well as their imports and includes. It resolves all typedefs found in all // modules and submodules read in. func resolveTypedefs() []error { var errs []error // When resolve typedefs, we may need to look up other typedefs. // We gather all typedefs into a slice so we don't deadlock on // TypeDict. for _, td := range TypeDict.Typedefs() { errs = append(errs, td.resolve()...) } return errs } // resolve creates a YangType for t, if not already done. Resolving t // requires resolving the Type that t is based on. func (t *Typedef) resolve() []error { // If we have no parent we are a base type and // are already resolved. if t.Parent == nil || t.YangType != nil { return nil } if errs := t.Type.resolve(); len(errs) != 0 { return errs } // Make a copy of the YangType we are based on and then // update it with local information. y := *t.Type.YangType y.Name = t.Name y.Base = t.Type if t.Units != nil { y.Units = t.Units.Name } if t.Default != nil { y.Default = t.Default.Name } if t.Type.IdentityBase != nil { // We need to copy over the IdentityBase statement if the type has one if idBase, err := RootNode(t).findIdentityBase(t.Type.IdentityBase.Name); err == nil { y.IdentityBase = idBase.Identity } else { return []error{fmt.Errorf("Could not resolve identity base for typedef: %s", t.Type.IdentityBase.Name)} } } // If we changed something, we are the new root. if y.Root == t.Type.YangType || !y.Equal(y.Root) { y.Root = &y } t.YangType = &y return nil } // resolve resolves Type t, as well as the underlying typedef for t. If t // cannot be resolved then one or more errors are returned. func (t *Type) resolve() (errs []error) { if t.YangType != nil { return nil } // If t.Name is a base type then td will not be nil, otherwise // td will be nil and of type *Typedef. td := BaseTypedefs[t.Name] prefix, name := getPrefix(t.Name) root := RootNode(t) rootPrefix := root.GetPrefix() source := "unknown" check: switch { case td != nil: source = "builtin" // This was a base type case prefix == "" || rootPrefix == prefix: source = "local" // If we have no prefix, or the prefix is what we call our own // root, then we look in our ancestors for a typedef of name. for n := Node(t); n != nil; n = n.ParentNode() { if td = TypeDict.find(n, name); td != nil { break check } } // We need to check our sub-modules as well for _, in := range root.Include { if td = TypeDict.find(in.Module, name); td != nil { break check } } var pname string switch { case prefix == "", prefix == root.Prefix.Name: pname = root.Prefix.Name + ":" + t.Name default: pname = fmt.Sprintf("%s[%s]:%s", prefix, root.Prefix.Name, t.Name) } return []error{fmt.Errorf("%s: unknown type: %s", Source(t), pname)} default: source = "imported" // prefix is not local to our module, so we have to go find // what module it is part of and if it is defined at the top // level of that module. var err error td, err = TypeDict.findExternal(t, prefix, name) if err != nil { return []error{err} } } if errs := td.resolve(); len(errs) > 0 { return errs } // Make a copy of the typedef we are based on so we can // augment it. if td.YangType == nil { return []error{fmt.Errorf("%s: no YangType defined for %s %s", Source(td), source, td.Name)} } y := *td.YangType y.Base = td.Type t.YangType = &y if v := t.RequireInstance; v != nil { b, err := v.asBool() if err != nil { errs = append(errs, err) } y.OptionalInstance = !b } if v := t.Path; v != nil { y.Path = v.asString() } // If we are directly of type decimal64 then we must specify // fraction-digits. switch { case y.Kind == Ydecimal64 && (t.Name == "decimal64" || t.FractionDigits != nil): i, err := t.FractionDigits.asRangeInt(1, 18) if err != nil { errs = append(errs, fmt.Errorf("%s: %v", Source(t), err)) } y.FractionDigits = int(i) case t.FractionDigits != nil: errs = append(errs, fmt.Errorf("%s: fraction-digits only allowed for decimal64 values", Source(t))) case y.Kind == Yidentityref: if source != "builtin" { // This is a typedef that refers to an identityref, so we want to simply // maintain the base that the typedef resolution provided break } if t.IdentityBase == nil { errs = append(errs, fmt.Errorf("%s: an identityref must specify a base", Source(t))) break } root := RootNode(t.Parent) resolvedBase, baseErr := root.findIdentityBase(t.IdentityBase.Name) if baseErr != nil { errs = append(errs, baseErr...) break } if resolvedBase.Identity == nil { errs = append(errs, fmt.Errorf("%s: identity has a null base", t.IdentityBase.Name)) break } y.IdentityBase = resolvedBase.Identity } if t.Range != nil { yr, err := ParseRanges(t.Range.Name) switch { case err != nil: errs = append(errs, fmt.Errorf("%s: bad range: %v", Source(t.Range), err)) case !y.Range.Contains(yr): errs = append(errs, fmt.Errorf("%s: bad range: %v not within %v", Source(t.Range), yr, y.Range)) case yr.Equal(y.Range): default: y.Range = yr } } if t.Length != nil { yr, err := ParseRanges(t.Length.Name) switch { case err != nil: errs = append(errs, fmt.Errorf("%s: bad length: %v", Source(t.Length), err)) case !y.Length.Contains(yr): errs = append(errs, fmt.Errorf("%s: bad length: %v not within %v", Source(t.Length), yr, y.Length)) case yr.Equal(y.Length): default: for _, r := range yr { if r.Min.Kind == Negative { errs = append(errs, fmt.Errorf("%s: negative length: %v", Source(t.Length), yr)) break } } y.Length = yr } } set := func(e *EnumType, name string, value *Value) error { if value == nil { return e.SetNext(name) } n, err := ParseNumber(value.Name) if err != nil { return err } i, err := n.Int() if err != nil { return err } return e.Set(name, i) } if len(t.Enum) > 0 { enum := NewEnumType() for _, e := range t.Enum { if err := set(enum, e.Name, e.Value); err != nil { errs = append(errs, fmt.Errorf("%s: %v", Source(e), err)) } } y.Enum = enum } if len(t.Bit) > 0 { bit := NewBitfield() for _, e := range t.Bit { if err := set(bit, e.Name, e.Position); err != nil { errs = append(errs, fmt.Errorf("%s: %v", Source(e), err)) } } y.Bit = bit } // Append any newly found patterns to the end of the list of patterns. // Patterns are ANDed according to section 9.4.6. If all the patterns // declared by t were also declared by the type t is based on, then // no patterns are added. patterns := map[string]bool{} for _, p := range y.Pattern { patterns[p] = true } for _, pv := range t.Pattern { p := pv.Name if _, err := syntax.Parse(p, syntax.Perl); err != nil { if re, ok := err.(*syntax.Error); ok { // Error adds "error parsing regexp" to // the error, re.Code is the real error. err = errors.New(re.Code.String()) } errs = append(errs, fmt.Errorf("%s: bad pattern: %v: %s", Source(pv), err, p)) } if !patterns[p] { patterns[p] = true y.Pattern = append(y.Pattern, p) } } // I don't know of an easy way to use a type as a key to a map, // so we have to check equality the hard way. looking: for _, ut := range t.Type { errs = append(errs, ut.resolve()...) if ut.YangType != nil { for _, yt := range y.Type { if ut.YangType.Equal(yt) { continue looking } } y.Type = append(y.Type, ut.YangType) } } // If we changed something, we are the new root. if !y.Equal(y.Root) { y.Root = &y } return errs }
{ "content_hash": "ee0e104543ecdca09e9d43e84426a2fa", "timestamp": "", "source": "github", "line_count": 375, "max_line_length": 106, "avg_line_length": 27.317333333333334, "alnum_prop": 0.6428153065208903, "repo_name": "paranpen/yangc", "id": "502f1783123faccd5f2aa52306d06a51969c788f", "size": "10833", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pkg/yang/types.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "359868" } ], "symlink_target": "" }
#include "test.h" __FBSDID("$FreeBSD: head/lib/libarchive/test/test_entry.c 201247 2009-12-30 05:59:21Z kientzle $"); #include <locale.h> #ifndef HAVE_WCSCPY static wchar_t * wcscpy(wchar_t *s1, const wchar_t *s2) { wchar_t *dest = s1; while ((*s1 = *s2) != L'\0') ++s1, ++s2; return dest; } #endif /* * Most of these tests are system-independent, though a few depend on * features of the local system. Such tests are conditionalized on * the platform name. On unsupported platforms, only the * system-independent features will be tested. * * No, I don't want to use config.h in the test files because I want * the tests to also serve as a check on the correctness of config.h. * A mis-configured library build should cause tests to fail. */ DEFINE_TEST(test_entry) { char buff[128]; wchar_t wbuff[128]; struct stat st; struct archive_entry *e, *e2; const struct stat *pst; unsigned long set, clear; /* For fflag testing. */ int type, permset, tag, qual; /* For ACL testing. */ const char *name; /* For ACL testing. */ const char *xname; /* For xattr tests. */ const void *xval; /* For xattr tests. */ size_t xsize; /* For xattr tests. */ wchar_t wc; long l; assert((e = archive_entry_new()) != NULL); /* * Verify that the AE_IF* defines match S_IF* defines * on this platform. See comments in archive_entry.h. */ #ifdef S_IFREG assertEqualInt(S_IFREG, AE_IFREG); #endif #ifdef S_IFLNK assertEqualInt(S_IFLNK, AE_IFLNK); #endif #ifdef S_IFSOCK assertEqualInt(S_IFSOCK, AE_IFSOCK); #endif #ifdef S_IFCHR assertEqualInt(S_IFCHR, AE_IFCHR); #endif /* Work around MinGW, which defines S_IFBLK wrong. */ /* sourceforge.net/tracker/?func=detail&atid=102435&aid=1942809&group_id=2435 */ #if defined(S_IFBLK) && !defined(_WIN32) assertEqualInt(S_IFBLK, AE_IFBLK); #endif #ifdef S_IFDIR assertEqualInt(S_IFDIR, AE_IFDIR); #endif #ifdef S_IFIFO assertEqualInt(S_IFIFO, AE_IFIFO); #endif /* * Basic set/read tests for all fields. * We should be able to set any field and read * back the same value. * * For methods that "copy" a string, we should be able * to overwrite the original passed-in string without * changing the value in the entry. * * The following tests are ordered alphabetically by the * name of the field. */ /* atime */ archive_entry_set_atime(e, 13579, 24680); assertEqualInt(archive_entry_atime(e), 13579); assertEqualInt(archive_entry_atime_nsec(e), 24680); archive_entry_unset_atime(e); assertEqualInt(archive_entry_atime(e), 0); assertEqualInt(archive_entry_atime_nsec(e), 0); assert(!archive_entry_atime_is_set(e)); /* birthtime */ archive_entry_set_birthtime(e, 17579, 24990); assertEqualInt(archive_entry_birthtime(e), 17579); assertEqualInt(archive_entry_birthtime_nsec(e), 24990); archive_entry_unset_birthtime(e); assertEqualInt(archive_entry_birthtime(e), 0); assertEqualInt(archive_entry_birthtime_nsec(e), 0); assert(!archive_entry_birthtime_is_set(e)); /* ctime */ archive_entry_set_ctime(e, 13580, 24681); assertEqualInt(archive_entry_ctime(e), 13580); assertEqualInt(archive_entry_ctime_nsec(e), 24681); archive_entry_unset_ctime(e); assertEqualInt(archive_entry_ctime(e), 0); assertEqualInt(archive_entry_ctime_nsec(e), 0); assert(!archive_entry_ctime_is_set(e)); #if ARCHIVE_VERSION_NUMBER >= 1009000 /* dev */ archive_entry_set_dev(e, 235); assertEqualInt(archive_entry_dev(e), 235); #else skipping("archive_entry_dev()"); #endif /* devmajor/devminor are tested specially below. */ #if ARCHIVE_VERSION_NUMBER >= 1009000 /* filetype */ archive_entry_set_filetype(e, AE_IFREG); assertEqualInt(archive_entry_filetype(e), AE_IFREG); #else skipping("archive_entry_filetype()"); #endif /* fflags are tested specially below */ /* gid */ archive_entry_set_gid(e, 204); assertEqualInt(archive_entry_gid(e), 204); /* gname */ archive_entry_set_gname(e, "group"); assertEqualString(archive_entry_gname(e), "group"); wcscpy(wbuff, L"wgroup"); archive_entry_copy_gname_w(e, wbuff); assertEqualWString(archive_entry_gname_w(e), L"wgroup"); memset(wbuff, 0, sizeof(wbuff)); assertEqualWString(archive_entry_gname_w(e), L"wgroup"); /* hardlink */ archive_entry_set_hardlink(e, "hardlinkname"); assertEqualString(archive_entry_hardlink(e), "hardlinkname"); strcpy(buff, "hardlinkname2"); archive_entry_copy_hardlink(e, buff); assertEqualString(archive_entry_hardlink(e), "hardlinkname2"); memset(buff, 0, sizeof(buff)); assertEqualString(archive_entry_hardlink(e), "hardlinkname2"); archive_entry_copy_hardlink(e, NULL); assertEqualString(archive_entry_hardlink(e), NULL); assertEqualWString(archive_entry_hardlink_w(e), NULL); wcscpy(wbuff, L"whardlink"); archive_entry_copy_hardlink_w(e, wbuff); assertEqualWString(archive_entry_hardlink_w(e), L"whardlink"); memset(wbuff, 0, sizeof(wbuff)); assertEqualWString(archive_entry_hardlink_w(e), L"whardlink"); archive_entry_copy_hardlink_w(e, NULL); assertEqualString(archive_entry_hardlink(e), NULL); assertEqualWString(archive_entry_hardlink_w(e), NULL); #if ARCHIVE_VERSION_NUMBER >= 1009000 /* ino */ archive_entry_set_ino(e, 8593); assertEqualInt(archive_entry_ino(e), 8593); #else skipping("archive_entry_ino()"); #endif /* link */ archive_entry_set_hardlink(e, "hardlinkname"); archive_entry_set_symlink(e, NULL); archive_entry_set_link(e, "link"); assertEqualString(archive_entry_hardlink(e), "link"); assertEqualString(archive_entry_symlink(e), NULL); archive_entry_copy_link(e, "link2"); assertEqualString(archive_entry_hardlink(e), "link2"); assertEqualString(archive_entry_symlink(e), NULL); archive_entry_copy_link_w(e, L"link3"); assertEqualString(archive_entry_hardlink(e), "link3"); assertEqualString(archive_entry_symlink(e), NULL); archive_entry_set_hardlink(e, NULL); archive_entry_set_symlink(e, "symlink"); archive_entry_set_link(e, "link"); assertEqualString(archive_entry_hardlink(e), NULL); assertEqualString(archive_entry_symlink(e), "link"); archive_entry_copy_link(e, "link2"); assertEqualString(archive_entry_hardlink(e), NULL); assertEqualString(archive_entry_symlink(e), "link2"); archive_entry_copy_link_w(e, L"link3"); assertEqualString(archive_entry_hardlink(e), NULL); assertEqualString(archive_entry_symlink(e), "link3"); /* Arbitrarily override symlink if both hardlink and symlink set. */ archive_entry_set_hardlink(e, "hardlink"); archive_entry_set_symlink(e, "symlink"); archive_entry_set_link(e, "link"); assertEqualString(archive_entry_hardlink(e), "hardlink"); assertEqualString(archive_entry_symlink(e), "link"); /* mode */ archive_entry_set_mode(e, 0123456); assertEqualInt(archive_entry_mode(e), 0123456); /* mtime */ archive_entry_set_mtime(e, 13581, 24682); assertEqualInt(archive_entry_mtime(e), 13581); assertEqualInt(archive_entry_mtime_nsec(e), 24682); archive_entry_unset_mtime(e); assertEqualInt(archive_entry_mtime(e), 0); assertEqualInt(archive_entry_mtime_nsec(e), 0); assert(!archive_entry_mtime_is_set(e)); #if ARCHIVE_VERSION_NUMBER >= 1009000 /* nlink */ archive_entry_set_nlink(e, 736); assertEqualInt(archive_entry_nlink(e), 736); #else skipping("archive_entry_nlink()"); #endif /* pathname */ archive_entry_set_pathname(e, "path"); assertEqualString(archive_entry_pathname(e), "path"); archive_entry_set_pathname(e, "path"); assertEqualString(archive_entry_pathname(e), "path"); strcpy(buff, "path2"); archive_entry_copy_pathname(e, buff); assertEqualString(archive_entry_pathname(e), "path2"); memset(buff, 0, sizeof(buff)); assertEqualString(archive_entry_pathname(e), "path2"); wcscpy(wbuff, L"wpath"); archive_entry_copy_pathname_w(e, wbuff); assertEqualWString(archive_entry_pathname_w(e), L"wpath"); memset(wbuff, 0, sizeof(wbuff)); assertEqualWString(archive_entry_pathname_w(e), L"wpath"); #if ARCHIVE_VERSION_NUMBER >= 1009000 /* rdev */ archive_entry_set_rdev(e, 532); assertEqualInt(archive_entry_rdev(e), 532); #else skipping("archive_entry_rdev()"); #endif /* rdevmajor/rdevminor are tested specially below. */ /* size */ archive_entry_set_size(e, 987654321); assertEqualInt(archive_entry_size(e), 987654321); archive_entry_unset_size(e); assertEqualInt(archive_entry_size(e), 0); assert(!archive_entry_size_is_set(e)); /* sourcepath */ archive_entry_copy_sourcepath(e, "path1"); assertEqualString(archive_entry_sourcepath(e), "path1"); /* symlink */ archive_entry_set_symlink(e, "symlinkname"); assertEqualString(archive_entry_symlink(e), "symlinkname"); #if ARCHIVE_VERSION_NUMBER >= 1009000 strcpy(buff, "symlinkname2"); archive_entry_copy_symlink(e, buff); assertEqualString(archive_entry_symlink(e), "symlinkname2"); memset(buff, 0, sizeof(buff)); assertEqualString(archive_entry_symlink(e), "symlinkname2"); #endif archive_entry_copy_symlink_w(e, NULL); assertEqualWString(archive_entry_symlink_w(e), NULL); assertEqualString(archive_entry_symlink(e), NULL); archive_entry_copy_symlink_w(e, L"wsymlink"); assertEqualWString(archive_entry_symlink_w(e), L"wsymlink"); archive_entry_copy_symlink(e, NULL); assertEqualWString(archive_entry_symlink_w(e), NULL); assertEqualString(archive_entry_symlink(e), NULL); /* uid */ archive_entry_set_uid(e, 83); assertEqualInt(archive_entry_uid(e), 83); /* uname */ archive_entry_set_uname(e, "user"); assertEqualString(archive_entry_uname(e), "user"); wcscpy(wbuff, L"wuser"); archive_entry_copy_gname_w(e, wbuff); assertEqualWString(archive_entry_gname_w(e), L"wuser"); memset(wbuff, 0, sizeof(wbuff)); assertEqualWString(archive_entry_gname_w(e), L"wuser"); /* Test fflags interface. */ archive_entry_set_fflags(e, 0x55, 0xAA); archive_entry_fflags(e, &set, &clear); failure("Testing set/get of fflags data."); assertEqualInt(set, 0x55); failure("Testing set/get of fflags data."); assertEqualInt(clear, 0xAA); #ifdef __FreeBSD__ /* Converting fflags bitmap to string is currently system-dependent. */ /* TODO: Make this system-independent. */ assertEqualString(archive_entry_fflags_text(e), "uappnd,nouchg,nodump,noopaque,uunlnk"); /* Test archive_entry_copy_fflags_text_w() */ archive_entry_copy_fflags_text_w(e, L" ,nouappnd, nouchg, dump,uunlnk"); archive_entry_fflags(e, &set, &clear); assertEqualInt(16, set); assertEqualInt(7, clear); /* Test archive_entry_copy_fflags_text() */ archive_entry_copy_fflags_text(e, " ,nouappnd, nouchg, dump,uunlnk"); archive_entry_fflags(e, &set, &clear); assertEqualInt(16, set); assertEqualInt(7, clear); #endif /* See test_acl_basic.c for tests of ACL set/get consistency. */ /* Test xattrs set/get consistency. */ archive_entry_xattr_add_entry(e, "xattr1", "xattrvalue1", 12); assertEqualInt(1, archive_entry_xattr_reset(e)); assertEqualInt(0, archive_entry_xattr_next(e, &xname, &xval, &xsize)); assertEqualString(xname, "xattr1"); assertEqualString(xval, "xattrvalue1"); assertEqualInt((int)xsize, 12); assertEqualInt(1, archive_entry_xattr_count(e)); assertEqualInt(ARCHIVE_WARN, archive_entry_xattr_next(e, &xname, &xval, &xsize)); assertEqualString(xname, NULL); assertEqualString(xval, NULL); assertEqualInt((int)xsize, 0); archive_entry_xattr_clear(e); assertEqualInt(0, archive_entry_xattr_reset(e)); assertEqualInt(ARCHIVE_WARN, archive_entry_xattr_next(e, &xname, &xval, &xsize)); assertEqualString(xname, NULL); assertEqualString(xval, NULL); assertEqualInt((int)xsize, 0); archive_entry_xattr_add_entry(e, "xattr1", "xattrvalue1", 12); assertEqualInt(1, archive_entry_xattr_reset(e)); archive_entry_xattr_add_entry(e, "xattr2", "xattrvalue2", 12); assertEqualInt(2, archive_entry_xattr_reset(e)); assertEqualInt(0, archive_entry_xattr_next(e, &xname, &xval, &xsize)); assertEqualInt(0, archive_entry_xattr_next(e, &xname, &xval, &xsize)); assertEqualInt(ARCHIVE_WARN, archive_entry_xattr_next(e, &xname, &xval, &xsize)); assertEqualString(xname, NULL); assertEqualString(xval, NULL); assertEqualInt((int)xsize, 0); /* * Test clone() implementation. */ /* Set values in 'e' */ archive_entry_clear(e); archive_entry_set_atime(e, 13579, 24680); archive_entry_set_birthtime(e, 13779, 24990); archive_entry_set_ctime(e, 13580, 24681); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_dev(e, 235); #endif archive_entry_set_fflags(e, 0x55, 0xAA); archive_entry_set_gid(e, 204); archive_entry_set_gname(e, "group"); archive_entry_set_hardlink(e, "hardlinkname"); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_ino(e, 8593); #endif archive_entry_set_mode(e, 0123456); archive_entry_set_mtime(e, 13581, 24682); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_nlink(e, 736); #endif archive_entry_set_pathname(e, "path"); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_rdev(e, 532); #endif archive_entry_set_size(e, 987654321); archive_entry_copy_sourcepath(e, "source"); archive_entry_set_symlink(e, "symlinkname"); archive_entry_set_uid(e, 83); archive_entry_set_uname(e, "user"); /* Add an ACL entry. */ archive_entry_acl_add_entry(e, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, ARCHIVE_ENTRY_ACL_READ, ARCHIVE_ENTRY_ACL_USER, 77, "user77"); /* Add an extended attribute. */ archive_entry_xattr_add_entry(e, "xattr1", "xattrvalue", 11); /* Make a clone. */ e2 = archive_entry_clone(e); /* Clone should have same contents. */ assertEqualInt(archive_entry_atime(e2), 13579); assertEqualInt(archive_entry_atime_nsec(e2), 24680); assertEqualInt(archive_entry_birthtime(e2), 13779); assertEqualInt(archive_entry_birthtime_nsec(e2), 24990); assertEqualInt(archive_entry_ctime(e2), 13580); assertEqualInt(archive_entry_ctime_nsec(e2), 24681); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(archive_entry_dev(e2), 235); #endif archive_entry_fflags(e, &set, &clear); assertEqualInt(clear, 0xAA); assertEqualInt(set, 0x55); assertEqualInt(archive_entry_gid(e2), 204); assertEqualString(archive_entry_gname(e2), "group"); assertEqualString(archive_entry_hardlink(e2), "hardlinkname"); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(archive_entry_ino(e2), 8593); #endif assertEqualInt(archive_entry_mode(e2), 0123456); assertEqualInt(archive_entry_mtime(e2), 13581); assertEqualInt(archive_entry_mtime_nsec(e2), 24682); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(archive_entry_nlink(e2), 736); #endif assertEqualString(archive_entry_pathname(e2), "path"); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(archive_entry_rdev(e2), 532); #endif assertEqualInt(archive_entry_size(e2), 987654321); assertEqualString(archive_entry_sourcepath(e2), "source"); assertEqualString(archive_entry_symlink(e2), "symlinkname"); assertEqualInt(archive_entry_uid(e2), 83); assertEqualString(archive_entry_uname(e2), "user"); #if ARCHIVE_VERSION_NUMBER < 1009000 skipping("ACL preserved by archive_entry_clone()"); #else /* Verify ACL was copied. */ assertEqualInt(4, archive_entry_acl_reset(e2, ARCHIVE_ENTRY_ACL_TYPE_ACCESS)); /* First three are standard permission bits. */ assertEqualInt(0, archive_entry_acl_next(e2, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, &type, &permset, &tag, &qual, &name)); assertEqualInt(type, ARCHIVE_ENTRY_ACL_TYPE_ACCESS); assertEqualInt(permset, 4); assertEqualInt(tag, ARCHIVE_ENTRY_ACL_USER_OBJ); assertEqualInt(qual, -1); assertEqualString(name, NULL); assertEqualInt(0, archive_entry_acl_next(e2, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, &type, &permset, &tag, &qual, &name)); assertEqualInt(type, ARCHIVE_ENTRY_ACL_TYPE_ACCESS); assertEqualInt(permset, 5); assertEqualInt(tag, ARCHIVE_ENTRY_ACL_GROUP_OBJ); assertEqualInt(qual, -1); assertEqualString(name, NULL); assertEqualInt(0, archive_entry_acl_next(e2, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, &type, &permset, &tag, &qual, &name)); assertEqualInt(type, ARCHIVE_ENTRY_ACL_TYPE_ACCESS); assertEqualInt(permset, 6); assertEqualInt(tag, ARCHIVE_ENTRY_ACL_OTHER); assertEqualInt(qual, -1); assertEqualString(name, NULL); /* Fourth is custom one. */ assertEqualInt(0, archive_entry_acl_next(e2, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, &type, &permset, &tag, &qual, &name)); assertEqualInt(type, ARCHIVE_ENTRY_ACL_TYPE_ACCESS); assertEqualInt(permset, ARCHIVE_ENTRY_ACL_READ); assertEqualInt(tag, ARCHIVE_ENTRY_ACL_USER); assertEqualInt(qual, 77); assertEqualString(name, "user77"); #endif #if ARCHIVE_VERSION_NUMBER < 1009000 skipping("xattr data preserved by archive_entry_clone"); #else /* Verify xattr was copied. */ assertEqualInt(1, archive_entry_xattr_reset(e2)); assertEqualInt(0, archive_entry_xattr_next(e2, &xname, &xval, &xsize)); assertEqualString(xname, "xattr1"); assertEqualString(xval, "xattrvalue"); assertEqualInt((int)xsize, 11); assertEqualInt(ARCHIVE_WARN, archive_entry_xattr_next(e2, &xname, &xval, &xsize)); assertEqualString(xname, NULL); assertEqualString(xval, NULL); assertEqualInt((int)xsize, 0); #endif /* Change the original */ archive_entry_set_atime(e, 13580, 24690); archive_entry_set_birthtime(e, 13980, 24999); archive_entry_set_ctime(e, 13590, 24691); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_dev(e, 245); #endif archive_entry_set_fflags(e, 0x85, 0xDA); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_filetype(e, AE_IFLNK); #endif archive_entry_set_gid(e, 214); archive_entry_set_gname(e, "grouper"); archive_entry_set_hardlink(e, "hardlinkpath"); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_ino(e, 8763); #endif archive_entry_set_mode(e, 0123654); archive_entry_set_mtime(e, 18351, 28642); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_nlink(e, 73); #endif archive_entry_set_pathname(e, "pathest"); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_rdev(e, 132); #endif archive_entry_set_size(e, 987456321); archive_entry_copy_sourcepath(e, "source2"); archive_entry_set_symlink(e, "symlinkpath"); archive_entry_set_uid(e, 93); archive_entry_set_uname(e, "username"); archive_entry_acl_clear(e); archive_entry_xattr_clear(e); /* Clone should still have same contents. */ assertEqualInt(archive_entry_atime(e2), 13579); assertEqualInt(archive_entry_atime_nsec(e2), 24680); assertEqualInt(archive_entry_birthtime(e2), 13779); assertEqualInt(archive_entry_birthtime_nsec(e2), 24990); assertEqualInt(archive_entry_ctime(e2), 13580); assertEqualInt(archive_entry_ctime_nsec(e2), 24681); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(archive_entry_dev(e2), 235); #endif archive_entry_fflags(e2, &set, &clear); assertEqualInt(clear, 0xAA); assertEqualInt(set, 0x55); assertEqualInt(archive_entry_gid(e2), 204); assertEqualString(archive_entry_gname(e2), "group"); assertEqualString(archive_entry_hardlink(e2), "hardlinkname"); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(archive_entry_ino(e2), 8593); #endif assertEqualInt(archive_entry_mode(e2), 0123456); assertEqualInt(archive_entry_mtime(e2), 13581); assertEqualInt(archive_entry_mtime_nsec(e2), 24682); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(archive_entry_nlink(e2), 736); #endif assertEqualString(archive_entry_pathname(e2), "path"); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(archive_entry_rdev(e2), 532); #endif assertEqualInt(archive_entry_size(e2), 987654321); assertEqualString(archive_entry_sourcepath(e2), "source"); assertEqualString(archive_entry_symlink(e2), "symlinkname"); assertEqualInt(archive_entry_uid(e2), 83); assertEqualString(archive_entry_uname(e2), "user"); #if ARCHIVE_VERSION_NUMBER < 1009000 skipping("ACL held by clone of archive_entry"); #else /* Verify ACL was unchanged. */ assertEqualInt(4, archive_entry_acl_reset(e2, ARCHIVE_ENTRY_ACL_TYPE_ACCESS)); /* First three are standard permission bits. */ assertEqualInt(0, archive_entry_acl_next(e2, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, &type, &permset, &tag, &qual, &name)); assertEqualInt(type, ARCHIVE_ENTRY_ACL_TYPE_ACCESS); assertEqualInt(permset, 4); assertEqualInt(tag, ARCHIVE_ENTRY_ACL_USER_OBJ); assertEqualInt(qual, -1); assertEqualString(name, NULL); assertEqualInt(0, archive_entry_acl_next(e2, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, &type, &permset, &tag, &qual, &name)); assertEqualInt(type, ARCHIVE_ENTRY_ACL_TYPE_ACCESS); assertEqualInt(permset, 5); assertEqualInt(tag, ARCHIVE_ENTRY_ACL_GROUP_OBJ); assertEqualInt(qual, -1); assertEqualString(name, NULL); assertEqualInt(0, archive_entry_acl_next(e2, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, &type, &permset, &tag, &qual, &name)); assertEqualInt(type, ARCHIVE_ENTRY_ACL_TYPE_ACCESS); assertEqualInt(permset, 6); assertEqualInt(tag, ARCHIVE_ENTRY_ACL_OTHER); assertEqualInt(qual, -1); assertEqualString(name, NULL); /* Fourth is custom one. */ assertEqualInt(0, archive_entry_acl_next(e2, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, &type, &permset, &tag, &qual, &name)); assertEqualInt(type, ARCHIVE_ENTRY_ACL_TYPE_ACCESS); assertEqualInt(permset, ARCHIVE_ENTRY_ACL_READ); assertEqualInt(tag, ARCHIVE_ENTRY_ACL_USER); assertEqualInt(qual, 77); assertEqualString(name, "user77"); assertEqualInt(1, archive_entry_acl_next(e2, ARCHIVE_ENTRY_ACL_TYPE_ACCESS, &type, &permset, &tag, &qual, &name)); assertEqualInt(type, 0); assertEqualInt(permset, 0); assertEqualInt(tag, 0); assertEqualInt(qual, -1); assertEqualString(name, NULL); #endif #if ARCHIVE_VERSION_NUMBER < 1009000 skipping("xattr preserved in archive_entry copy"); #else /* Verify xattr was unchanged. */ assertEqualInt(1, archive_entry_xattr_reset(e2)); #endif /* Release clone. */ archive_entry_free(e2); /* * Test clear() implementation. */ archive_entry_clear(e); assertEqualInt(archive_entry_atime(e), 0); assertEqualInt(archive_entry_atime_nsec(e), 0); assertEqualInt(archive_entry_birthtime(e), 0); assertEqualInt(archive_entry_birthtime_nsec(e), 0); assertEqualInt(archive_entry_ctime(e), 0); assertEqualInt(archive_entry_ctime_nsec(e), 0); assertEqualInt(archive_entry_dev(e), 0); archive_entry_fflags(e, &set, &clear); assertEqualInt(clear, 0); assertEqualInt(set, 0); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(archive_entry_filetype(e), 0); #endif assertEqualInt(archive_entry_gid(e), 0); assertEqualString(archive_entry_gname(e), NULL); assertEqualString(archive_entry_hardlink(e), NULL); assertEqualInt(archive_entry_ino(e), 0); assertEqualInt(archive_entry_mode(e), 0); assertEqualInt(archive_entry_mtime(e), 0); assertEqualInt(archive_entry_mtime_nsec(e), 0); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(archive_entry_nlink(e), 0); #endif assertEqualString(archive_entry_pathname(e), NULL); assertEqualInt(archive_entry_rdev(e), 0); assertEqualInt(archive_entry_size(e), 0); assertEqualString(archive_entry_symlink(e), NULL); assertEqualInt(archive_entry_uid(e), 0); assertEqualString(archive_entry_uname(e), NULL); /* ACLs should be cleared. */ assertEqualInt(archive_entry_acl_count(e, ARCHIVE_ENTRY_ACL_TYPE_ACCESS), 0); assertEqualInt(archive_entry_acl_count(e, ARCHIVE_ENTRY_ACL_TYPE_DEFAULT), 0); /* Extended attributes should be cleared. */ assertEqualInt(archive_entry_xattr_count(e), 0); /* * Test archive_entry_copy_stat(). */ memset(&st, 0, sizeof(st)); /* Set all of the standard 'struct stat' fields. */ st.st_atime = 456789; st.st_ctime = 345678; st.st_dev = 123; st.st_gid = 34; st.st_ino = 234; st.st_mode = 077777; st.st_mtime = 234567; st.st_nlink = 345; st.st_size = 123456789; st.st_uid = 23; #ifdef __FreeBSD__ /* On FreeBSD, high-res timestamp data should come through. */ st.st_atimespec.tv_nsec = 6543210; st.st_ctimespec.tv_nsec = 5432109; st.st_mtimespec.tv_nsec = 3210987; st.st_birthtimespec.tv_nsec = 7459386; #endif /* Copy them into the entry. */ archive_entry_copy_stat(e, &st); /* Read each one back separately and compare. */ assertEqualInt(archive_entry_atime(e), 456789); assertEqualInt(archive_entry_ctime(e), 345678); assertEqualInt(archive_entry_dev(e), 123); assertEqualInt(archive_entry_gid(e), 34); assertEqualInt(archive_entry_ino(e), 234); assertEqualInt(archive_entry_mode(e), 077777); assertEqualInt(archive_entry_mtime(e), 234567); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(archive_entry_nlink(e), 345); #endif assertEqualInt(archive_entry_size(e), 123456789); assertEqualInt(archive_entry_uid(e), 23); #if __FreeBSD__ /* On FreeBSD, high-res timestamp data should come through. */ assertEqualInt(archive_entry_atime_nsec(e), 6543210); assertEqualInt(archive_entry_ctime_nsec(e), 5432109); assertEqualInt(archive_entry_mtime_nsec(e), 3210987); assertEqualInt(archive_entry_birthtime_nsec(e), 7459386); #endif /* * Test archive_entry_stat(). */ /* First, clear out any existing stat data. */ memset(&st, 0, sizeof(st)); archive_entry_copy_stat(e, &st); /* Set a bunch of fields individually. */ archive_entry_set_atime(e, 456789, 321); archive_entry_set_ctime(e, 345678, 432); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_dev(e, 123); #endif archive_entry_set_gid(e, 34); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_ino(e, 234); #endif archive_entry_set_mode(e, 012345); archive_entry_set_mode(e, 012345); archive_entry_set_mtime(e, 234567, 543); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_nlink(e, 345); #endif archive_entry_set_size(e, 123456789); archive_entry_set_uid(e, 23); /* Retrieve a stat structure. */ assert((pst = archive_entry_stat(e)) != NULL); /* Check that the values match. */ assertEqualInt(pst->st_atime, 456789); assertEqualInt(pst->st_ctime, 345678); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(pst->st_dev, 123); #endif assertEqualInt(pst->st_gid, 34); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(pst->st_ino, 234); #endif assertEqualInt(pst->st_mode, 012345); assertEqualInt(pst->st_mtime, 234567); #if ARCHIVE_VERSION_NUMBER >= 1009000 assertEqualInt(pst->st_nlink, 345); #endif assertEqualInt(pst->st_size, 123456789); assertEqualInt(pst->st_uid, 23); #ifdef __FreeBSD__ /* On FreeBSD, high-res timestamp data should come through. */ assertEqualInt(pst->st_atimespec.tv_nsec, 321); assertEqualInt(pst->st_ctimespec.tv_nsec, 432); assertEqualInt(pst->st_mtimespec.tv_nsec, 543); #endif /* Changing any one value should update struct stat. */ archive_entry_set_atime(e, 456788, 0); assert((pst = archive_entry_stat(e)) != NULL); assertEqualInt(pst->st_atime, 456788); archive_entry_set_ctime(e, 345677, 431); assert((pst = archive_entry_stat(e)) != NULL); assertEqualInt(pst->st_ctime, 345677); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_dev(e, 122); assert((pst = archive_entry_stat(e)) != NULL); assertEqualInt(pst->st_dev, 122); #endif archive_entry_set_gid(e, 33); assert((pst = archive_entry_stat(e)) != NULL); assertEqualInt(pst->st_gid, 33); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_ino(e, 233); assert((pst = archive_entry_stat(e)) != NULL); assertEqualInt(pst->st_ino, 233); #endif archive_entry_set_mode(e, 012344); assert((pst = archive_entry_stat(e)) != NULL); assertEqualInt(pst->st_mode, 012344); archive_entry_set_mtime(e, 234566, 542); assert((pst = archive_entry_stat(e)) != NULL); assertEqualInt(pst->st_mtime, 234566); #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_nlink(e, 344); assert((pst = archive_entry_stat(e)) != NULL); assertEqualInt(pst->st_nlink, 344); #endif archive_entry_set_size(e, 123456788); assert((pst = archive_entry_stat(e)) != NULL); assertEqualInt(pst->st_size, 123456788); archive_entry_set_uid(e, 22); assert((pst = archive_entry_stat(e)) != NULL); assertEqualInt(pst->st_uid, 22); /* We don't need to check high-res fields here. */ /* * Test dev/major/minor interfaces. Setting 'dev' or 'rdev' * should change the corresponding major/minor values, and * vice versa. * * The test here is system-specific because it assumes that * makedev(), major(), and minor() are defined in sys/stat.h. * I'm not too worried about it, though, because the code is * simple. If it works on FreeBSD, it's unlikely to be broken * anywhere else. Note: The functionality is present on every * platform even if these tests only run some places; * libarchive's more extensive configuration logic should find * the necessary definitions on every platform. */ #if __FreeBSD__ #if ARCHIVE_VERSION_NUMBER >= 1009000 archive_entry_set_dev(e, 0x12345678); assertEqualInt(archive_entry_devmajor(e), major(0x12345678)); assertEqualInt(archive_entry_devminor(e), minor(0x12345678)); assertEqualInt(archive_entry_dev(e), 0x12345678); archive_entry_set_devmajor(e, 0xfe); archive_entry_set_devminor(e, 0xdcba98); assertEqualInt(archive_entry_devmajor(e), 0xfe); assertEqualInt(archive_entry_devminor(e), 0xdcba98); assertEqualInt(archive_entry_dev(e), makedev(0xfe, 0xdcba98)); archive_entry_set_rdev(e, 0x12345678); assertEqualInt(archive_entry_rdevmajor(e), major(0x12345678)); assertEqualInt(archive_entry_rdevminor(e), minor(0x12345678)); assertEqualInt(archive_entry_rdev(e), 0x12345678); archive_entry_set_rdevmajor(e, 0xfe); archive_entry_set_rdevminor(e, 0xdcba98); assertEqualInt(archive_entry_rdevmajor(e), 0xfe); assertEqualInt(archive_entry_rdevminor(e), 0xdcba98); assertEqualInt(archive_entry_rdev(e), makedev(0xfe, 0xdcba98)); #endif #endif /* * Exercise the character-conversion logic, if we can. */ if (NULL == LOCALE_UTF8 || NULL == setlocale(LC_ALL, LOCALE_UTF8)) { skipping("Can't exercise charset-conversion logic without" " a suitable locale."); } else { /* A filename that cannot be converted to wide characters. */ archive_entry_copy_pathname(e, "abc\314\214mno\374xyz"); failure("Converting invalid chars to Unicode should fail."); assert(NULL == archive_entry_pathname_w(e)); //failure("Converting invalid chars to UTF-8 should fail."); //assert(NULL == archive_entry_pathname_utf8(e)); /* A group name that cannot be converted. */ archive_entry_copy_gname(e, "abc\314\214mno\374xyz"); failure("Converting invalid chars to Unicode should fail."); assert(NULL == archive_entry_gname_w(e)); /* A user name that cannot be converted. */ archive_entry_copy_uname(e, "abc\314\214mno\374xyz"); failure("Converting invalid chars to Unicode should fail."); assert(NULL == archive_entry_uname_w(e)); /* A hardlink target that cannot be converted. */ archive_entry_copy_hardlink(e, "abc\314\214mno\374xyz"); failure("Converting invalid chars to Unicode should fail."); assert(NULL == archive_entry_hardlink_w(e)); /* A symlink target that cannot be converted. */ archive_entry_copy_symlink(e, "abc\314\214mno\374xyz"); failure("Converting invalid chars to Unicode should fail."); assert(NULL == archive_entry_symlink_w(e)); } #if HAVE_WCSCPY l = 0x12345678L; wc = (wchar_t)l; /* Wide character too big for UTF-8. */ if (NULL == setlocale(LC_ALL, "C") || (long)wc != l) { skipping("Testing charset conversion failure requires 32-bit wchar_t and support for \"C\" locale."); } else { /* * Build the string L"xxx\U12345678yyy\u5678zzz" without * using C99 \u#### syntax, which isn't uniformly * supported. (GCC 3.4.6, for instance, defaults to * "c89 plus GNU extensions.") */ wcscpy(wbuff, L"xxxAyyyBzzz"); wbuff[3] = (wchar_t)0x12345678; wbuff[7] = (wchar_t)0x5678; /* A wide filename that cannot be converted to narrow. */ archive_entry_copy_pathname_w(e, wbuff); failure("Converting wide characters from Unicode should fail."); assertEqualString(NULL, archive_entry_pathname(e)); } #endif /* Release the experimental entry. */ archive_entry_free(e); }
{ "content_hash": "2c1a6d7f024f39c2a29f51d5b3d16261", "timestamp": "", "source": "github", "line_count": 880, "max_line_length": 103, "avg_line_length": 36.00113636363636, "alnum_prop": 0.7226097661058679, "repo_name": "veritas-shine/minix3-rpi", "id": "bf36cbe3f37b8ad3dc3762a87c7b8aaeff8da66a", "size": "33008", "binary": false, "copies": "30", "ref": "refs/heads/master", "path": "external/bsd/libarchive/dist/libarchive/test/test_entry.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89060" }, { "name": "Arc", "bytes": "2839" }, { "name": "Assembly", "bytes": "2791293" }, { "name": "Awk", "bytes": "39398" }, { "name": "Bison", "bytes": "137952" }, { "name": "C", "bytes": "45473316" }, { "name": "C#", "bytes": "55726" }, { "name": "C++", "bytes": "577647" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CSS", "bytes": "254" }, { "name": "Emacs Lisp", "bytes": "4528" }, { "name": "IGOR Pro", "bytes": "2975" }, { "name": "JavaScript", "bytes": "25168" }, { "name": "Logos", "bytes": "14672" }, { "name": "Lua", "bytes": "4385" }, { "name": "Makefile", "bytes": "669790" }, { "name": "Max", "bytes": "3667" }, { "name": "Objective-C", "bytes": "62068" }, { "name": "Pascal", "bytes": "40318" }, { "name": "Perl", "bytes": "100129" }, { "name": "Perl6", "bytes": "243" }, { "name": "Prolog", "bytes": "97" }, { "name": "R", "bytes": "764" }, { "name": "Rebol", "bytes": "738" }, { "name": "SAS", "bytes": "1711" }, { "name": "Shell", "bytes": "2207644" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>dblib: 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.9.0 / dblib - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> dblib <small> 8.8.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-08-18 22:12:38 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-18 22:12:38 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.12 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.9.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/dblib&quot; license: &quot;GPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Dblib&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: abstract syntax&quot; &quot;keyword: binders&quot; &quot;keyword: de Bruijn indices&quot; &quot;keyword: shift&quot; &quot;keyword: lift&quot; &quot;keyword: substitution&quot; &quot;category: Computer Science/Lambda Calculi&quot; ] authors: [ &quot;Francois Pottier &lt;francois.pottier@inria.fr&gt; [http://gallium.inria.fr/~fpottier/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/dblib/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/dblib.git&quot; synopsis: &quot;Dblib&quot; description: &quot;&quot;&quot; http://gallium.inria.fr/~fpottier/dblib/README The dblib library offers facilities for working with de Bruijn indices.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/dblib/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=f3801acc5eccb14676c5c27315c30ee2&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-dblib.8.8.0 coq.8.9.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.9.0). The following dependencies couldn&#39;t be met: - coq-dblib -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.03.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-dblib.8.8.0</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"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </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": "e70915211c95e1b3478d9f3c4cd9b533", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 255, "avg_line_length": 42.550898203592816, "alnum_prop": 0.5450323670137912, "repo_name": "coq-bench/coq-bench.github.io", "id": "d553716a2280b62780d312b0af77290535055652", "size": "7108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.6/released/8.9.0/dblib/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package examples.mobile; import jade.core.Agent; import jade.core.Location; import jade.core.behaviours.SimpleBehaviour; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import java.util.StringTokenizer; /** This behaviour of the Agent serves all the received messages. In particular, the following expressions are accepted as content of "request" messages: - (move <destination>) to move the Agent to another container. Example (move Front-End) or (move (:location (:name Container-1) (:transport-protocol JADE-IPMT) (:transport-address IOR:0000...) )) - (exit) to request the agent to exit - (stop) to stop the counter - (continue) to continue counting @author Giovanni Caire - CSELT S.p.A @version $Date: 2008-10-09 14:04:02 +0200 (gio, 09 ott 2008) $ $Revision: 6051 $ */ class ServeIncomingMessagesBehaviour extends SimpleBehaviour { ServeIncomingMessagesBehaviour(Agent a) { super(a); } public boolean done() { return false; } public void action() { ACLMessage msg; MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.REQUEST); // Get a message from the queue or wait for a new one if queue is empty msg = myAgent.receive(mt); if (msg == null) { block(); return; } else { String replySentence = ""; // Get action to perform //String s = msg.getContent(). StringTokenizer st = new StringTokenizer(msg.getContent(), " ()\t\n\r\f"); String action = (st.nextToken()).toLowerCase(); // EXIT if (action.equals("exit")) { System.out.println("They requested me to exit (Sob!)"); // Set reply sentence replySentence = "\"OK exiting\""; myAgent.doDelete(); } // STOP COUNTING else if (action.equals("stop")) { System.out.println("They requested me to stop counting"); ((MobileAgent) myAgent).stopCounter(); // Set reply sentence replySentence = "\"OK stopping\""; } // CONTINUE COUNTING else if (action.equals("continue")) { System.out.println("They requested me to continue counting"); ((MobileAgent) myAgent).continueCounter(); // Set reply sentence replySentence = "\"OK continuing\""; } // MOVE TO ANOTHER LOCATION else if (action.equals("move")) { String destination = st.nextToken(); System.out.println(); Location dest = new jade.core.ContainerID(destination, null); System.out.println("They requested me to go to " + destination); // Set reply sentence replySentence = "\"OK moving to " + destination+" \""; // Prepare to move ((MobileAgent)myAgent).nextSite = dest; myAgent.doMove(dest); } // CLONE TO ANOTHER LOCATION else if (action.equals("clone")) { String destination = st.nextToken(); System.out.println(); Location dest = new jade.core.ContainerID(destination, null); System.out.println("They requested me to clone myself to " + destination); // Set reply sentence replySentence = "\"OK cloning to " + destination+" \""; // Prepare to move ((MobileAgent)myAgent).nextSite = dest; myAgent.doClone(dest, "clone"+((MobileAgent)myAgent).cnt+"of"+myAgent.getName()); } // SAY THE CURRENT LOCATION else if (action.equals("where-are-you")) { System.out.println(); Location current = myAgent.here(); System.out.println("Currently I am running on "+current.getName()); // Set reply sentence replySentence = current.getName(); } // Reply ACLMessage replyMsg = msg.createReply(); replyMsg.setPerformative(ACLMessage.INFORM); replyMsg.setContent(replySentence); myAgent.send(replyMsg); } return; } }
{ "content_hash": "f1a2ecd28b4b33aec84a02be468ee185", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 104, "avg_line_length": 30.238095238095237, "alnum_prop": 0.6446194225721785, "repo_name": "shookees/SmartFood_old", "id": "b04339c12efe5ef6501a8c431df36bbd89d42a34", "size": "4821", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "lib/JADE/src/examples/mobile/ServeIncomingMessagesBehaviour.java", "mode": "33188", "license": "mit", "language": [ { "name": "CLIPS", "bytes": "8093" }, { "name": "CSS", "bytes": "20703" }, { "name": "Java", "bytes": "7455756" }, { "name": "Shell", "bytes": "2707" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>DOREMUS dataset</title> <meta name="description" content="The access point to the data of the DOREMUS project"> <meta name="keywords" content="music, linked data, sparql endpoint, doremus"> <link rel='stylesheet' href='//fonts.googleapis.com/css?family=Roboto|Roboto+Condensed' type='text/css'> <link rel="stylesheet" href="style/style.css" type="text/css"> <link rel="apple-touch-icon" sizes="180x180" href="/img/icons/apple-touch-icon.png"> <link rel="icon" type="image/png" href="/img/icons/favicon-32x32.png" sizes="32x32"> <link rel="icon" type="image/png" href="/img/icons/favicon-16x16.png" sizes="16x16"> <link rel="manifest" href="/img/icons/manifest.json"> <link rel="mask-icon" href="/img/icons/safari-pinned-tab.svg" color="#c62c24"> <link rel="shortcut icon" href="/img/icons/favicon.ico"> <meta name="apple-mobile-web-app-title" content="DOREMUS | SPARQL endpoint"> <meta name="application-name" content="DOREMUS | SPARQL endpoint"> <meta name="msapplication-config" content="/img/icons/browserconfig.xml"> <meta name="theme-color" content="#ffffff"> </head> <body> <section class="cover"> <h1>data.doremus.org</h1> <h2>The access point to the data of the DOREMUS project</h2> </section> <section class="content"> <h1 id="data">Musical data</h1> <p> The metadata about works, performances, publications, recordings ... </p> <div class="link-blocks"> <a class="green" href="http://data.doremus.org/sparql">SPARQL Endpoint</a> <a class="purple" href="http://data.doremus.org/fct">Facet Browser</a> <a class="red" href="http://overture.doremus.org">OVERTURE</a> </div> <h1 id="model">The model</h1> <p> The DOREMUS Ontology and the Vocabularies. </p> <div class="link-blocks"> <a href="http://data.doremus.org/ontology">Ontology</a> <a class="blue" href="http://data.doremus.org/vocabularies">Controlled Vocabularies</a> </div> <h1 id="model">Documentation</h1> <p> How to use the model and useful queries. </p> <div class="link-blocks"> <!-- <a href="http://data.doremus.org/ontology">Ontology</a> --> <a class="blue" href="./queries.html">Example queries</a> </div> </section> <footer id="appFooter"> <div class="footerCont"> <div> <p class="descr">The <strong>DOREMUS dataset</strong> lives inside the <a href="http://www.doremus.org" rel="external" target="_blank">DOREMUS project</a>, for describing, publishing, connecting and contextualizing music catalogues on the web of data. </p> <br> <a class="licenseBadge" href="http://virtuoso.openlinksw.com/"><img src="http://virtuoso.openlinksw.com/skin/images/PoweredByVirtuoso.png" alt="Powered by OpenLink Virtuoso"></a> <a class="licenseBadge" rel="license" href="http://creativecommons.org/licenses/by/4.0/"><img alt="Licenza Creative Commons" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png"></a>This work is licensed under <a rel="license" href="http://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International License</a>. </div> <div class="projLogoCont"> <a href="http://www.doremus.org" rel="external" target="_blank"><img src="/img/doremus.logo.png"></a> </div> </div> </footer> </body> </html>
{ "content_hash": "a81a878d6952bb506be6714da1ad4f4d", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 242, "avg_line_length": 42.88095238095238, "alnum_prop": 0.6640755136035535, "repo_name": "DOREMUS-ANR/knowledge-base", "id": "3d62bfe3f6de613e2865a2d8dcddd1cc24f75c58", "size": "3602", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "static/home/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12859" }, { "name": "HTML", "bytes": "37743" }, { "name": "Java", "bytes": "11109" }, { "name": "JavaScript", "bytes": "93324" }, { "name": "Python", "bytes": "43201" }, { "name": "Roff", "bytes": "3006080" }, { "name": "Shell", "bytes": "150" }, { "name": "TSQL", "bytes": "26079" } ], "symlink_target": "" }
Simple ruby script to pull feeds from Gimlet Media podcasts and post new episodes to the r/gimlet subreddit. ## Installation 1. Clone the git repo 2. Run `bundle install` 3. Enter your reddit credentials into credentials.yml 4. Run `ruby bot.rb`
{ "content_hash": "0aa8b48292c550ce24a0d2e9c13ad1b1", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 109, "avg_line_length": 31.125, "alnum_prop": 0.7710843373493976, "repo_name": "andykelk/goldenpeasant", "id": "4692997991b35553bf6c480ec3e798a7cd8d73b1", "size": "266", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "12380" } ], "symlink_target": "" }
require('electron').ipcRenderer.send('argv', process.argv);
{ "content_hash": "00085e7033cc7ff08a34ac68c6db28c7", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 59, "avg_line_length": 60, "alnum_prop": 0.75, "repo_name": "gerhardberger/electron", "id": "fb2d6a30bcf3defa21b122828d4463261d54c462", "size": "60", "binary": false, "copies": "4", "ref": "refs/heads/main", "path": "spec/fixtures/api/mixed-sandbox-app/electron-app-mixed-sandbox-preload.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1255" }, { "name": "C++", "bytes": "2635598" }, { "name": "CSS", "bytes": "2379" }, { "name": "Dockerfile", "bytes": "1395" }, { "name": "HTML", "bytes": "17594" }, { "name": "JavaScript", "bytes": "628036" }, { "name": "Objective-C", "bytes": "40222" }, { "name": "Objective-C++", "bytes": "330226" }, { "name": "Python", "bytes": "100871" }, { "name": "Shell", "bytes": "22830" }, { "name": "TypeScript", "bytes": "755984" } ], "symlink_target": "" }
package org.apache.hadoop.mapreduce.jobhistory; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalFileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.mapreduce.CounterGroup; import org.apache.hadoop.mapreduce.Counters; import org.apache.hadoop.mapreduce.JobACL; import org.apache.hadoop.mapreduce.JobID; import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.TaskID; import org.apache.hadoop.mapreduce.TaskType; import org.apache.hadoop.mapreduce.TypeConverter; import org.apache.hadoop.mapreduce.util.JobHistoryEventUtils; import org.apache.hadoop.mapreduce.util.MRJobConfUtil; import org.apache.hadoop.mapreduce.v2.api.records.JobId; import org.apache.hadoop.mapreduce.v2.app.AppContext; import org.apache.hadoop.mapreduce.v2.app.MRAppMaster.RunningAppContext; import org.apache.hadoop.mapreduce.v2.app.job.Job; import org.apache.hadoop.mapreduce.v2.app.job.JobStateInternal; import org.apache.hadoop.mapreduce.v2.jobhistory.JHAdminConfig; import org.apache.hadoop.mapreduce.v2.jobhistory.JobHistoryUtils; import org.apache.hadoop.mapreduce.v2.util.MRBuilderUtils; import org.apache.hadoop.mapreduce.v2.util.MRWebAppUtil; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.timeline.TimelineEntities; import org.apache.hadoop.yarn.api.records.timeline.TimelineEntity; import org.apache.hadoop.yarn.client.api.TimelineClient; import org.apache.hadoop.yarn.client.api.TimelineV2Client; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.server.MiniYARNCluster; import org.apache.hadoop.yarn.server.timeline.TimelineStore; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestJobHistoryEventHandler { private static final Logger LOG = LoggerFactory .getLogger(TestJobHistoryEventHandler.class); private static MiniDFSCluster dfsCluster = null; private static String coreSitePath; @BeforeClass public static void setUpClass() throws Exception { coreSitePath = "." + File.separator + "target" + File.separator + "test-classes" + File.separator + "core-site.xml"; Configuration conf = new HdfsConfiguration(); dfsCluster = new MiniDFSCluster.Builder(conf).build(); } @AfterClass public static void cleanUpClass() throws Exception { dfsCluster.shutdown(); } @After public void cleanTest() throws Exception { new File(coreSitePath).delete(); } @Test (timeout=50000) public void testFirstFlushOnCompletionEvent() throws Exception { TestParams t = new TestParams(); Configuration conf = new Configuration(); conf.set(MRJobConfig.MR_AM_STAGING_DIR, t.workDir); conf.setLong(MRJobConfig.MR_AM_HISTORY_COMPLETE_EVENT_FLUSH_TIMEOUT_MS, 60 * 1000l); conf.setInt(MRJobConfig.MR_AM_HISTORY_JOB_COMPLETE_UNFLUSHED_MULTIPLIER, 10); conf.setInt(MRJobConfig.MR_AM_HISTORY_MAX_UNFLUSHED_COMPLETE_EVENTS, 10); conf.setInt( MRJobConfig.MR_AM_HISTORY_USE_BATCHED_FLUSH_QUEUE_SIZE_THRESHOLD, 200); JHEvenHandlerForTest realJheh = new JHEvenHandlerForTest(t.mockAppContext, 0); JHEvenHandlerForTest jheh = spy(realJheh); jheh.init(conf); EventWriter mockWriter = null; try { jheh.start(); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, -1))); mockWriter = jheh.getEventWriter(); verify(mockWriter).write(any(HistoryEvent.class)); for (int i = 0; i < 100; i++) { queueEvent(jheh, new JobHistoryEvent(t.jobId, new TaskStartedEvent( t.taskID, 0, TaskType.MAP, ""))); } handleNextNEvents(jheh, 100); verify(mockWriter, times(0)).flush(); // First completion event, but min-queue-size for batching flushes is 10 handleEvent(jheh, new JobHistoryEvent(t.jobId, new TaskFinishedEvent( t.taskID, t.taskAttemptID, 0, TaskType.MAP, "", null, 0))); verify(mockWriter).flush(); } finally { jheh.stop(); verify(mockWriter).close(); } } @Test (timeout=50000) public void testMaxUnflushedCompletionEvents() throws Exception { TestParams t = new TestParams(); Configuration conf = new Configuration(); conf.set(MRJobConfig.MR_AM_STAGING_DIR, t.workDir); conf.setLong(MRJobConfig.MR_AM_HISTORY_COMPLETE_EVENT_FLUSH_TIMEOUT_MS, 60 * 1000l); conf.setInt(MRJobConfig.MR_AM_HISTORY_JOB_COMPLETE_UNFLUSHED_MULTIPLIER, 10); conf.setInt(MRJobConfig.MR_AM_HISTORY_MAX_UNFLUSHED_COMPLETE_EVENTS, 10); conf.setInt( MRJobConfig.MR_AM_HISTORY_USE_BATCHED_FLUSH_QUEUE_SIZE_THRESHOLD, 5); JHEvenHandlerForTest realJheh = new JHEvenHandlerForTest(t.mockAppContext, 0); JHEvenHandlerForTest jheh = spy(realJheh); jheh.init(conf); EventWriter mockWriter = null; try { jheh.start(); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, -1))); mockWriter = jheh.getEventWriter(); verify(mockWriter).write(any(HistoryEvent.class)); for (int i = 0 ; i < 100 ; i++) { queueEvent(jheh, new JobHistoryEvent(t.jobId, new TaskFinishedEvent( t.taskID, t.taskAttemptID, 0, TaskType.MAP, "", null, 0))); } handleNextNEvents(jheh, 9); verify(mockWriter, times(0)).flush(); handleNextNEvents(jheh, 1); verify(mockWriter).flush(); handleNextNEvents(jheh, 50); verify(mockWriter, times(6)).flush(); } finally { jheh.stop(); verify(mockWriter).close(); } } @Test (timeout=50000) public void testUnflushedTimer() throws Exception { TestParams t = new TestParams(); Configuration conf = new Configuration(); conf.set(MRJobConfig.MR_AM_STAGING_DIR, t.workDir); conf.setLong(MRJobConfig.MR_AM_HISTORY_COMPLETE_EVENT_FLUSH_TIMEOUT_MS, 2 * 1000l); //2 seconds. conf.setInt(MRJobConfig.MR_AM_HISTORY_JOB_COMPLETE_UNFLUSHED_MULTIPLIER, 10); conf.setInt(MRJobConfig.MR_AM_HISTORY_MAX_UNFLUSHED_COMPLETE_EVENTS, 100); conf.setInt( MRJobConfig.MR_AM_HISTORY_USE_BATCHED_FLUSH_QUEUE_SIZE_THRESHOLD, 5); JHEvenHandlerForTest realJheh = new JHEvenHandlerForTest(t.mockAppContext, 0); JHEvenHandlerForTest jheh = spy(realJheh); jheh.init(conf); EventWriter mockWriter = null; try { jheh.start(); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, -1))); mockWriter = jheh.getEventWriter(); verify(mockWriter).write(any(HistoryEvent.class)); for (int i = 0 ; i < 100 ; i++) { queueEvent(jheh, new JobHistoryEvent(t.jobId, new TaskFinishedEvent( t.taskID, t.taskAttemptID, 0, TaskType.MAP, "", null, 0))); } handleNextNEvents(jheh, 9); Assert.assertTrue(jheh.getFlushTimerStatus()); verify(mockWriter, times(0)).flush(); Thread.sleep(2 * 4 * 1000l); // 4 seconds should be enough. Just be safe. verify(mockWriter).flush(); Assert.assertFalse(jheh.getFlushTimerStatus()); } finally { jheh.stop(); verify(mockWriter).close(); } } @Test (timeout=50000) public void testBatchedFlushJobEndMultiplier() throws Exception { TestParams t = new TestParams(); Configuration conf = new Configuration(); conf.set(MRJobConfig.MR_AM_STAGING_DIR, t.workDir); conf.setLong(MRJobConfig.MR_AM_HISTORY_COMPLETE_EVENT_FLUSH_TIMEOUT_MS, 60 * 1000l); //2 seconds. conf.setInt(MRJobConfig.MR_AM_HISTORY_JOB_COMPLETE_UNFLUSHED_MULTIPLIER, 3); conf.setInt(MRJobConfig.MR_AM_HISTORY_MAX_UNFLUSHED_COMPLETE_EVENTS, 10); conf.setInt( MRJobConfig.MR_AM_HISTORY_USE_BATCHED_FLUSH_QUEUE_SIZE_THRESHOLD, 0); JHEvenHandlerForTest realJheh = new JHEvenHandlerForTest(t.mockAppContext, 0); JHEvenHandlerForTest jheh = spy(realJheh); jheh.init(conf); EventWriter mockWriter = null; try { jheh.start(); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, -1))); mockWriter = jheh.getEventWriter(); verify(mockWriter).write(any(HistoryEvent.class)); for (int i = 0 ; i < 100 ; i++) { queueEvent(jheh, new JobHistoryEvent(t.jobId, new TaskFinishedEvent( t.taskID, t.taskAttemptID, 0, TaskType.MAP, "", null, 0))); } queueEvent(jheh, new JobHistoryEvent(t.jobId, new JobFinishedEvent( TypeConverter.fromYarn(t.jobId), 0, 10, 10, 0, 0, 0, 0, null, null, new Counters()))); handleNextNEvents(jheh, 29); verify(mockWriter, times(0)).flush(); handleNextNEvents(jheh, 72); verify(mockWriter, times(4)).flush(); //3 * 30 + 1 for JobFinished } finally { jheh.stop(); verify(mockWriter).close(); } } // In case of all types of events, process Done files if it's last AM retry @Test (timeout=50000) public void testProcessDoneFilesOnLastAMRetry() throws Exception { TestParams t = new TestParams(true); Configuration conf = new Configuration(); JHEvenHandlerForTest realJheh = new JHEvenHandlerForTest(t.mockAppContext, 0); JHEvenHandlerForTest jheh = spy(realJheh); jheh.init(conf); EventWriter mockWriter = null; try { jheh.start(); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, -1))); verify(jheh, times(0)).processDoneFiles(any(JobId.class)); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobUnsuccessfulCompletionEvent(TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, JobStateInternal.ERROR.toString()))); verify(jheh, times(1)).processDoneFiles(any(JobId.class)); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobFinishedEvent( TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, new Counters(), new Counters(), new Counters()))); verify(jheh, times(2)).processDoneFiles(any(JobId.class)); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobUnsuccessfulCompletionEvent(TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, JobStateInternal.FAILED.toString()))); verify(jheh, times(3)).processDoneFiles(any(JobId.class)); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobUnsuccessfulCompletionEvent(TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, JobStateInternal.KILLED.toString()))); verify(jheh, times(4)).processDoneFiles(any(JobId.class)); mockWriter = jheh.getEventWriter(); verify(mockWriter, times(5)).write(any(HistoryEvent.class)); } finally { jheh.stop(); verify(mockWriter).close(); } } // Skip processing Done files in case of ERROR, if it's not last AM retry @Test (timeout=50000) public void testProcessDoneFilesNotLastAMRetry() throws Exception { TestParams t = new TestParams(false); Configuration conf = new Configuration(); JHEvenHandlerForTest realJheh = new JHEvenHandlerForTest(t.mockAppContext, 0); JHEvenHandlerForTest jheh = spy(realJheh); jheh.init(conf); EventWriter mockWriter = null; try { jheh.start(); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, -1))); verify(jheh, times(0)).processDoneFiles(t.jobId); // skip processing done files handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobUnsuccessfulCompletionEvent(TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, JobStateInternal.ERROR.toString()))); verify(jheh, times(0)).processDoneFiles(t.jobId); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobFinishedEvent( TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, new Counters(), new Counters(), new Counters()))); verify(jheh, times(1)).processDoneFiles(t.jobId); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobUnsuccessfulCompletionEvent(TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, JobStateInternal.FAILED.toString()))); verify(jheh, times(2)).processDoneFiles(t.jobId); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobUnsuccessfulCompletionEvent(TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, JobStateInternal.KILLED.toString()))); verify(jheh, times(3)).processDoneFiles(t.jobId); mockWriter = jheh.getEventWriter(); verify(mockWriter, times(5)).write(any(HistoryEvent.class)); } finally { jheh.stop(); verify(mockWriter).close(); } } @Test public void testPropertyRedactionForJHS() throws Exception { final Configuration conf = new Configuration(); String sensitivePropertyName = "aws.fake.credentials.name"; String sensitivePropertyValue = "aws.fake.credentials.val"; conf.set(sensitivePropertyName, sensitivePropertyValue); conf.set(MRJobConfig.MR_JOB_REDACTED_PROPERTIES, sensitivePropertyName); conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, dfsCluster.getURI().toString()); final TestParams params = new TestParams(); conf.set(MRJobConfig.MR_AM_STAGING_DIR, params.dfsWorkDir); final JHEvenHandlerForTest jheh = new JHEvenHandlerForTest(params.mockAppContext, 0, false); try { jheh.init(conf); jheh.start(); handleEvent(jheh, new JobHistoryEvent(params.jobId, new AMStartedEvent(params.appAttemptId, 200, params.containerId, "nmhost", 3000, 4000, -1))); handleEvent(jheh, new JobHistoryEvent(params.jobId, new JobUnsuccessfulCompletionEvent(TypeConverter.fromYarn( params.jobId), 0, 0, 0, 0, 0, 0, 0, JobStateInternal.FAILED.toString()))); // verify the value of the sensitive property in job.xml is restored. Assert.assertEquals(sensitivePropertyName + " is modified.", conf.get(sensitivePropertyName), sensitivePropertyValue); // load the job_conf.xml in JHS directory and verify property redaction. Path jhsJobConfFile = getJobConfInIntermediateDoneDir(conf, params.jobId); Assert.assertTrue("The job_conf.xml file is not in the JHS directory", FileContext.getFileContext(conf).util().exists(jhsJobConfFile)); Configuration jhsJobConf = new Configuration(); try (InputStream input = FileSystem.get(conf).open(jhsJobConfFile)) { jhsJobConf.addResource(input); Assert.assertEquals( sensitivePropertyName + " is not redacted in HDFS.", MRJobConfUtil.REDACTION_REPLACEMENT_VAL, jhsJobConf.get(sensitivePropertyName)); } } finally { jheh.stop(); purgeHdfsHistoryIntermediateDoneDirectory(conf); } } private static Path getJobConfInIntermediateDoneDir(Configuration conf, JobId jobId) throws IOException { Path userDoneDir = new Path( JobHistoryUtils.getHistoryIntermediateDoneDirForUser(conf)); Path doneDirPrefix = FileContext.getFileContext(conf).makeQualified(userDoneDir); return new Path( doneDirPrefix, JobHistoryUtils.getIntermediateConfFileName(jobId)); } private void purgeHdfsHistoryIntermediateDoneDirectory(Configuration conf) throws IOException { FileSystem fs = FileSystem.get(dfsCluster.getConfiguration(0)); String intermDoneDirPrefix = JobHistoryUtils.getConfiguredHistoryIntermediateDoneDirPrefix(conf); fs.delete(new Path(intermDoneDirPrefix), true); } @Test (timeout=50000) public void testDefaultFsIsUsedForHistory() throws Exception { // Create default configuration pointing to the minicluster Configuration conf = new Configuration(); conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, dfsCluster.getURI().toString()); FileOutputStream os = new FileOutputStream(coreSitePath); conf.writeXml(os); os.close(); // simulate execution under a non-default namenode conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, "file:///"); TestParams t = new TestParams(); conf.set(MRJobConfig.MR_AM_STAGING_DIR, t.dfsWorkDir); JHEvenHandlerForTest realJheh = new JHEvenHandlerForTest(t.mockAppContext, 0, false); JHEvenHandlerForTest jheh = spy(realJheh); jheh.init(conf); try { jheh.start(); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, -1))); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobFinishedEvent( TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, new Counters(), new Counters(), new Counters()))); // If we got here then event handler worked but we don't know with which // file system. Now we check that history stuff was written to minicluster FileSystem dfsFileSystem = dfsCluster.getFileSystem(); assertTrue("Minicluster contains some history files", dfsFileSystem.globStatus(new Path(t.dfsWorkDir + "/*")).length != 0); FileSystem localFileSystem = LocalFileSystem.get(conf); assertFalse("No history directory on non-default file system", localFileSystem.exists(new Path(t.dfsWorkDir))); } finally { jheh.stop(); purgeHdfsHistoryIntermediateDoneDirectory(conf); } } @Test public void testGetHistoryIntermediateDoneDirForUser() throws IOException { // Test relative path Configuration conf = new Configuration(); conf.set(JHAdminConfig.MR_HISTORY_INTERMEDIATE_DONE_DIR, "/mapred/history/done_intermediate"); conf.set(MRJobConfig.USER_NAME, System.getProperty("user.name")); String pathStr = JobHistoryUtils.getHistoryIntermediateDoneDirForUser(conf); Assert.assertEquals("/mapred/history/done_intermediate/" + System.getProperty("user.name"), pathStr); // Test fully qualified path // Create default configuration pointing to the minicluster conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, dfsCluster.getURI().toString()); FileOutputStream os = new FileOutputStream(coreSitePath); conf.writeXml(os); os.close(); // Simulate execution under a non-default namenode conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, "file:///"); pathStr = JobHistoryUtils.getHistoryIntermediateDoneDirForUser(conf); Assert.assertEquals(dfsCluster.getURI().toString() + "/mapred/history/done_intermediate/" + System.getProperty("user.name"), pathStr); } // test AMStartedEvent for submitTime and startTime @Test (timeout=50000) public void testAMStartedEvent() throws Exception { TestParams t = new TestParams(); Configuration conf = new Configuration(); JHEvenHandlerForTest realJheh = new JHEvenHandlerForTest(t.mockAppContext, 0); JHEvenHandlerForTest jheh = spy(realJheh); jheh.init(conf); EventWriter mockWriter = null; try { jheh.start(); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, 100))); JobHistoryEventHandler.MetaInfo mi = JobHistoryEventHandler.fileMap.get(t.jobId); Assert.assertEquals(mi.getJobIndexInfo().getSubmitTime(), 100); Assert.assertEquals(mi.getJobIndexInfo().getJobStartTime(), 200); Assert.assertEquals(mi.getJobSummary().getJobSubmitTime(), 100); Assert.assertEquals(mi.getJobSummary().getJobLaunchTime(), 200); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobUnsuccessfulCompletionEvent(TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, JobStateInternal.FAILED.toString()))); Assert.assertEquals(mi.getJobIndexInfo().getSubmitTime(), 100); Assert.assertEquals(mi.getJobIndexInfo().getJobStartTime(), 200); Assert.assertEquals(mi.getJobSummary().getJobSubmitTime(), 100); Assert.assertEquals(mi.getJobSummary().getJobLaunchTime(), 200); verify(jheh, times(1)).processDoneFiles(t.jobId); mockWriter = jheh.getEventWriter(); verify(mockWriter, times(2)).write(any(HistoryEvent.class)); } finally { jheh.stop(); } } // Have JobHistoryEventHandler handle some events and make sure they get // stored to the Timeline store @Test (timeout=50000) public void testTimelineEventHandling() throws Exception { TestParams t = new TestParams(RunningAppContext.class, false); Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true); long currentTime = System.currentTimeMillis(); try (MiniYARNCluster yarnCluster = new MiniYARNCluster( TestJobHistoryEventHandler.class.getSimpleName(), 1, 1, 1, 1)) { yarnCluster.init(conf); yarnCluster.start(); Configuration confJHEH = new YarnConfiguration(conf); confJHEH.setBoolean(MRJobConfig.MAPREDUCE_JOB_EMIT_TIMELINE_DATA, true); confJHEH.set(YarnConfiguration.TIMELINE_SERVICE_WEBAPP_ADDRESS, MiniYARNCluster.getHostname() + ":" + yarnCluster.getApplicationHistoryServer().getPort()); JHEvenHandlerForTest jheh = new JHEvenHandlerForTest(t.mockAppContext, 0); jheh.init(confJHEH); jheh.start(); TimelineStore ts = yarnCluster.getApplicationHistoryServer() .getTimelineStore(); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, -1), currentTime - 10)); TimelineEntities entities = ts.getEntities("MAPREDUCE_JOB", null, null, null, null, null, null, null, null, null); Assert.assertEquals(1, entities.getEntities().size()); TimelineEntity tEntity = entities.getEntities().get(0); Assert.assertEquals(t.jobId.toString(), tEntity.getEntityId()); Assert.assertEquals(1, tEntity.getEvents().size()); Assert.assertEquals(EventType.AM_STARTED.toString(), tEntity.getEvents().get(0).getEventType()); Assert.assertEquals(currentTime - 10, tEntity.getEvents().get(0).getTimestamp()); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobSubmittedEvent(TypeConverter.fromYarn(t.jobId), "name", "user", 200, "/foo/job.xml", new HashMap<JobACL, AccessControlList>(), "default"), currentTime + 10)); entities = ts.getEntities("MAPREDUCE_JOB", null, null, null, null, null, null, null, null, null); Assert.assertEquals(1, entities.getEntities().size()); tEntity = entities.getEntities().get(0); Assert.assertEquals(t.jobId.toString(), tEntity.getEntityId()); Assert.assertEquals(2, tEntity.getEvents().size()); Assert.assertEquals(EventType.JOB_SUBMITTED.toString(), tEntity.getEvents().get(0).getEventType()); Assert.assertEquals(EventType.AM_STARTED.toString(), tEntity.getEvents().get(1).getEventType()); Assert.assertEquals(currentTime + 10, tEntity.getEvents().get(0).getTimestamp()); Assert.assertEquals(currentTime - 10, tEntity.getEvents().get(1).getTimestamp()); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobQueueChangeEvent(TypeConverter.fromYarn(t.jobId), "q2"), currentTime - 20)); entities = ts.getEntities("MAPREDUCE_JOB", null, null, null, null, null, null, null, null, null); Assert.assertEquals(1, entities.getEntities().size()); tEntity = entities.getEntities().get(0); Assert.assertEquals(t.jobId.toString(), tEntity.getEntityId()); Assert.assertEquals(3, tEntity.getEvents().size()); Assert.assertEquals(EventType.JOB_SUBMITTED.toString(), tEntity.getEvents().get(0).getEventType()); Assert.assertEquals(EventType.AM_STARTED.toString(), tEntity.getEvents().get(1).getEventType()); Assert.assertEquals(EventType.JOB_QUEUE_CHANGED.toString(), tEntity.getEvents().get(2).getEventType()); Assert.assertEquals(currentTime + 10, tEntity.getEvents().get(0).getTimestamp()); Assert.assertEquals(currentTime - 10, tEntity.getEvents().get(1).getTimestamp()); Assert.assertEquals(currentTime - 20, tEntity.getEvents().get(2).getTimestamp()); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobFinishedEvent(TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, new Counters(), new Counters(), new Counters()), currentTime)); entities = ts.getEntities("MAPREDUCE_JOB", null, null, null, null, null, null, null, null, null); Assert.assertEquals(1, entities.getEntities().size()); tEntity = entities.getEntities().get(0); Assert.assertEquals(t.jobId.toString(), tEntity.getEntityId()); Assert.assertEquals(4, tEntity.getEvents().size()); Assert.assertEquals(EventType.JOB_SUBMITTED.toString(), tEntity.getEvents().get(0).getEventType()); Assert.assertEquals(EventType.JOB_FINISHED.toString(), tEntity.getEvents().get(1).getEventType()); Assert.assertEquals(EventType.AM_STARTED.toString(), tEntity.getEvents().get(2).getEventType()); Assert.assertEquals(EventType.JOB_QUEUE_CHANGED.toString(), tEntity.getEvents().get(3).getEventType()); Assert.assertEquals(currentTime + 10, tEntity.getEvents().get(0).getTimestamp()); Assert.assertEquals(currentTime, tEntity.getEvents().get(1).getTimestamp()); Assert.assertEquals(currentTime - 10, tEntity.getEvents().get(2).getTimestamp()); Assert.assertEquals(currentTime - 20, tEntity.getEvents().get(3).getTimestamp()); handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobUnsuccessfulCompletionEvent(TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, JobStateInternal.KILLED.toString()), currentTime + 20)); entities = ts.getEntities("MAPREDUCE_JOB", null, null, null, null, null, null, null, null, null); Assert.assertEquals(1, entities.getEntities().size()); tEntity = entities.getEntities().get(0); Assert.assertEquals(t.jobId.toString(), tEntity.getEntityId()); Assert.assertEquals(5, tEntity.getEvents().size()); Assert.assertEquals(EventType.JOB_KILLED.toString(), tEntity.getEvents().get(0).getEventType()); Assert.assertEquals(EventType.JOB_SUBMITTED.toString(), tEntity.getEvents().get(1).getEventType()); Assert.assertEquals(EventType.JOB_FINISHED.toString(), tEntity.getEvents().get(2).getEventType()); Assert.assertEquals(EventType.AM_STARTED.toString(), tEntity.getEvents().get(3).getEventType()); Assert.assertEquals(EventType.JOB_QUEUE_CHANGED.toString(), tEntity.getEvents().get(4).getEventType()); Assert.assertEquals(currentTime + 20, tEntity.getEvents().get(0).getTimestamp()); Assert.assertEquals(currentTime + 10, tEntity.getEvents().get(1).getTimestamp()); Assert.assertEquals(currentTime, tEntity.getEvents().get(2).getTimestamp()); Assert.assertEquals(currentTime - 10, tEntity.getEvents().get(3).getTimestamp()); Assert.assertEquals(currentTime - 20, tEntity.getEvents().get(4).getTimestamp()); handleEvent(jheh, new JobHistoryEvent(t.jobId, new TaskStartedEvent(t.taskID, 0, TaskType.MAP, ""))); entities = ts.getEntities("MAPREDUCE_TASK", null, null, null, null, null, null, null, null, null); Assert.assertEquals(1, entities.getEntities().size()); tEntity = entities.getEntities().get(0); Assert.assertEquals(t.taskID.toString(), tEntity.getEntityId()); Assert.assertEquals(1, tEntity.getEvents().size()); Assert.assertEquals(EventType.TASK_STARTED.toString(), tEntity.getEvents().get(0).getEventType()); Assert.assertEquals(TaskType.MAP.toString(), tEntity.getEvents().get(0).getEventInfo().get("TASK_TYPE")); handleEvent(jheh, new JobHistoryEvent(t.jobId, new TaskStartedEvent(t.taskID, 0, TaskType.REDUCE, ""))); entities = ts.getEntities("MAPREDUCE_TASK", null, null, null, null, null, null, null, null, null); Assert.assertEquals(1, entities.getEntities().size()); tEntity = entities.getEntities().get(0); Assert.assertEquals(t.taskID.toString(), tEntity.getEntityId()); Assert.assertEquals(2, tEntity.getEvents().size()); Assert.assertEquals(EventType.TASK_STARTED.toString(), tEntity.getEvents().get(1).getEventType()); Assert.assertEquals(TaskType.REDUCE.toString(), tEntity.getEvents().get(0).getEventInfo().get("TASK_TYPE")); Assert.assertEquals(TaskType.MAP.toString(), tEntity.getEvents().get(1).getEventInfo().get("TASK_TYPE")); } } @Test (timeout=50000) public void testCountersToJSON() throws Exception { JobHistoryEventHandler jheh = new JobHistoryEventHandler(null, 0); Counters counters = new Counters(); CounterGroup group1 = counters.addGroup("DOCTORS", "Incarnations of the Doctor"); group1.addCounter("PETER_CAPALDI", "Peter Capaldi", 12); group1.addCounter("MATT_SMITH", "Matt Smith", 11); group1.addCounter("DAVID_TENNANT", "David Tennant", 10); CounterGroup group2 = counters.addGroup("COMPANIONS", "Companions of the Doctor"); group2.addCounter("CLARA_OSWALD", "Clara Oswald", 6); group2.addCounter("RORY_WILLIAMS", "Rory Williams", 5); group2.addCounter("AMY_POND", "Amy Pond", 4); group2.addCounter("MARTHA_JONES", "Martha Jones", 3); group2.addCounter("DONNA_NOBLE", "Donna Noble", 2); group2.addCounter("ROSE_TYLER", "Rose Tyler", 1); JsonNode jsonNode = JobHistoryEventUtils.countersToJSON(counters); String jsonStr = new ObjectMapper().writeValueAsString(jsonNode); String expected = "[{\"NAME\":\"COMPANIONS\",\"DISPLAY_NAME\":\"Companions " + "of the Doctor\",\"COUNTERS\":[{\"NAME\":\"AMY_POND\",\"DISPLAY_NAME\"" + ":\"Amy Pond\",\"VALUE\":4},{\"NAME\":\"CLARA_OSWALD\"," + "\"DISPLAY_NAME\":\"Clara Oswald\",\"VALUE\":6},{\"NAME\":" + "\"DONNA_NOBLE\",\"DISPLAY_NAME\":\"Donna Noble\",\"VALUE\":2}," + "{\"NAME\":\"MARTHA_JONES\",\"DISPLAY_NAME\":\"Martha Jones\"," + "\"VALUE\":3},{\"NAME\":\"RORY_WILLIAMS\",\"DISPLAY_NAME\":\"Rory " + "Williams\",\"VALUE\":5},{\"NAME\":\"ROSE_TYLER\",\"DISPLAY_NAME\":" + "\"Rose Tyler\",\"VALUE\":1}]},{\"NAME\":\"DOCTORS\",\"DISPLAY_NAME\"" + ":\"Incarnations of the Doctor\",\"COUNTERS\":[{\"NAME\":" + "\"DAVID_TENNANT\",\"DISPLAY_NAME\":\"David Tennant\",\"VALUE\":10}," + "{\"NAME\":\"MATT_SMITH\",\"DISPLAY_NAME\":\"Matt Smith\",\"VALUE\":" + "11},{\"NAME\":\"PETER_CAPALDI\",\"DISPLAY_NAME\":\"Peter Capaldi\"," + "\"VALUE\":12}]}]"; Assert.assertEquals(expected, jsonStr); } @Test (timeout=50000) public void testCountersToJSONEmpty() throws Exception { JobHistoryEventHandler jheh = new JobHistoryEventHandler(null, 0); Counters counters = null; JsonNode jsonNode = JobHistoryEventUtils.countersToJSON(counters); String jsonStr = new ObjectMapper().writeValueAsString(jsonNode); String expected = "[]"; Assert.assertEquals(expected, jsonStr); counters = new Counters(); jsonNode = JobHistoryEventUtils.countersToJSON(counters); jsonStr = new ObjectMapper().writeValueAsString(jsonNode); expected = "[]"; Assert.assertEquals(expected, jsonStr); counters.addGroup("DOCTORS", "Incarnations of the Doctor"); jsonNode = JobHistoryEventUtils.countersToJSON(counters); jsonStr = new ObjectMapper().writeValueAsString(jsonNode); expected = "[{\"NAME\":\"DOCTORS\",\"DISPLAY_NAME\":\"Incarnations of the " + "Doctor\",\"COUNTERS\":[]}]"; Assert.assertEquals(expected, jsonStr); } private void queueEvent(JHEvenHandlerForTest jheh, JobHistoryEvent event) { jheh.handle(event); } private void handleEvent(JHEvenHandlerForTest jheh, JobHistoryEvent event) throws InterruptedException { jheh.handle(event); jheh.handleEvent(jheh.eventQueue.take()); } private void handleNextNEvents(JHEvenHandlerForTest jheh, int numEvents) throws InterruptedException { for (int i = 0; i < numEvents; i++) { jheh.handleEvent(jheh.eventQueue.take()); } } private String setupTestWorkDir() { File testWorkDir = new File("target", this.getClass().getCanonicalName()); try { FileContext.getLocalFSFileContext().delete( new Path(testWorkDir.getAbsolutePath()), true); return testWorkDir.getAbsolutePath(); } catch (Exception e) { LOG.warn("Could not cleanup", e); throw new YarnRuntimeException("could not cleanup test dir", e); } } private Job mockJob() { Job mockJob = mock(Job.class); when(mockJob.getAllCounters()).thenReturn(new Counters()); when(mockJob.getTotalMaps()).thenReturn(10); when(mockJob.getTotalReduces()).thenReturn(10); when(mockJob.getName()).thenReturn("mockjob"); return mockJob; } private AppContext mockAppContext(Class<? extends AppContext> contextClass, ApplicationId appId, boolean isLastAMRetry) { JobId jobId = TypeConverter.toYarn(TypeConverter.fromYarn(appId)); AppContext mockContext = mock(contextClass); Job mockJob = mockJob(); when(mockContext.getJob(jobId)).thenReturn(mockJob); when(mockContext.getApplicationID()).thenReturn(appId); when(mockContext.isLastAMRetry()).thenReturn(isLastAMRetry); if (mockContext instanceof RunningAppContext) { when(((RunningAppContext)mockContext).getTimelineClient()). thenReturn(TimelineClient.createTimelineClient()); when(((RunningAppContext) mockContext).getTimelineV2Client()) .thenReturn(TimelineV2Client .createTimelineClient(ApplicationId.newInstance(0, 1))); } return mockContext; } private class TestParams { boolean isLastAMRetry; String workDir = setupTestWorkDir(); String dfsWorkDir = "/" + this.getClass().getCanonicalName(); ApplicationId appId = ApplicationId.newInstance(200, 1); ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(appId, 1); ContainerId containerId = ContainerId.newContainerId(appAttemptId, 1); TaskID taskID = TaskID.forName("task_200707121733_0003_m_000005"); TaskAttemptID taskAttemptID = new TaskAttemptID(taskID, 0); JobId jobId = MRBuilderUtils.newJobId(appId, 1); AppContext mockAppContext; public TestParams() { this(AppContext.class, false); } public TestParams(boolean isLastAMRetry) { this(AppContext.class, isLastAMRetry); } public TestParams(Class<? extends AppContext> contextClass, boolean isLastAMRetry) { this.isLastAMRetry = isLastAMRetry; mockAppContext = mockAppContext(contextClass, appId, this.isLastAMRetry); } } private JobHistoryEvent getEventToEnqueue(JobId jobId) { HistoryEvent toReturn = new JobStatusChangedEvent(new JobID(Integer.toString(jobId.getId()), jobId.getId()), "change status"); return new JobHistoryEvent(jobId, toReturn); } @Test /** * Tests that in case of SIGTERM, the JHEH stops without processing its event * queue (because we must stop quickly lest we get SIGKILLed) and processes * a JobUnsuccessfulEvent for jobs which were still running (so that they may * show up in the JobHistoryServer) */ public void testSigTermedFunctionality() throws IOException { AppContext mockedContext = Mockito.mock(AppContext.class); JHEventHandlerForSigtermTest jheh = new JHEventHandlerForSigtermTest(mockedContext, 0); JobId jobId = Mockito.mock(JobId.class); jheh.addToFileMap(jobId); //Submit 4 events and check that they're handled in the absence of a signal final int numEvents = 4; JobHistoryEvent events[] = new JobHistoryEvent[numEvents]; for(int i=0; i < numEvents; ++i) { events[i] = getEventToEnqueue(jobId); jheh.handle(events[i]); } jheh.stop(); //Make sure events were handled assertTrue("handleEvent should've been called only 4 times but was " + jheh.eventsHandled, jheh.eventsHandled == 4); //Create a new jheh because the last stop closed the eventWriter etc. jheh = new JHEventHandlerForSigtermTest(mockedContext, 0); // Make constructor of JobUnsuccessfulCompletionEvent pass Job job = Mockito.mock(Job.class); Mockito.when(mockedContext.getJob(jobId)).thenReturn(job); // Make TypeConverter(JobID) pass ApplicationId mockAppId = Mockito.mock(ApplicationId.class); Mockito.when(mockAppId.getClusterTimestamp()).thenReturn(1000l); Mockito.when(jobId.getAppId()).thenReturn(mockAppId); jheh.addToFileMap(jobId); jheh.setForcejobCompletion(true); for(int i=0; i < numEvents; ++i) { events[i] = getEventToEnqueue(jobId); jheh.handle(events[i]); } jheh.stop(); //Make sure events were handled, 4 + 1 finish event assertTrue("handleEvent should've been called only 5 times but was " + jheh.eventsHandled, jheh.eventsHandled == 5); assertTrue("Last event handled wasn't JobUnsuccessfulCompletionEvent", jheh.lastEventHandled.getHistoryEvent() instanceof JobUnsuccessfulCompletionEvent); } @Test (timeout=50000) public void testSetTrackingURLAfterHistoryIsWritten() throws Exception { TestParams t = new TestParams(true); Configuration conf = new Configuration(); JHEvenHandlerForTest realJheh = new JHEvenHandlerForTest(t.mockAppContext, 0, false); JHEvenHandlerForTest jheh = spy(realJheh); jheh.init(conf); try { jheh.start(); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, -1))); verify(jheh, times(0)).processDoneFiles(any(JobId.class)); verify(t.mockAppContext, times(0)).setHistoryUrl(any(String.class)); // Job finishes and successfully writes history handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobFinishedEvent( TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, new Counters(), new Counters(), new Counters()))); verify(jheh, times(1)).processDoneFiles(any(JobId.class)); String historyUrl = MRWebAppUtil.getApplicationWebURLOnJHSWithScheme( conf, t.mockAppContext.getApplicationID()); verify(t.mockAppContext, times(1)).setHistoryUrl(historyUrl); } finally { jheh.stop(); } } @Test (timeout=50000) public void testDontSetTrackingURLIfHistoryWriteFailed() throws Exception { TestParams t = new TestParams(true); Configuration conf = new Configuration(); JHEvenHandlerForTest realJheh = new JHEvenHandlerForTest(t.mockAppContext, 0, false); JHEvenHandlerForTest jheh = spy(realJheh); jheh.init(conf); try { jheh.start(); doReturn(false).when(jheh).moveToDoneNow(any(Path.class), any(Path.class)); doNothing().when(jheh).moveTmpToDone(any(Path.class)); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, -1))); verify(jheh, times(0)).processDoneFiles(any(JobId.class)); verify(t.mockAppContext, times(0)).setHistoryUrl(any(String.class)); // Job finishes, but doesn't successfully write history handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobFinishedEvent( TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, new Counters(), new Counters(), new Counters()))); verify(jheh, times(1)).processDoneFiles(any(JobId.class)); verify(t.mockAppContext, times(0)).setHistoryUrl(any(String.class)); } finally { jheh.stop(); } } @Test (timeout=50000) public void testDontSetTrackingURLIfHistoryWriteThrows() throws Exception { TestParams t = new TestParams(true); Configuration conf = new Configuration(); JHEvenHandlerForTest realJheh = new JHEvenHandlerForTest(t.mockAppContext, 0, false); JHEvenHandlerForTest jheh = spy(realJheh); jheh.init(conf); try { jheh.start(); doThrow(new YarnRuntimeException(new IOException())) .when(jheh).processDoneFiles(any(JobId.class)); handleEvent(jheh, new JobHistoryEvent(t.jobId, new AMStartedEvent( t.appAttemptId, 200, t.containerId, "nmhost", 3000, 4000, -1))); verify(jheh, times(0)).processDoneFiles(any(JobId.class)); verify(t.mockAppContext, times(0)).setHistoryUrl(any(String.class)); // Job finishes, but doesn't successfully write history try { handleEvent(jheh, new JobHistoryEvent(t.jobId, new JobFinishedEvent( TypeConverter.fromYarn(t.jobId), 0, 0, 0, 0, 0, 0, 0, new Counters(), new Counters(), new Counters()))); throw new RuntimeException( "processDoneFiles didn't throw, but should have"); } catch (YarnRuntimeException yre) { // Exception expected, do nothing } verify(jheh, times(1)).processDoneFiles(any(JobId.class)); verify(t.mockAppContext, times(0)).setHistoryUrl(any(String.class)); } finally { jheh.stop(); } } } class JHEvenHandlerForTest extends JobHistoryEventHandler { private EventWriter eventWriter; private boolean mockHistoryProcessing = true; public JHEvenHandlerForTest(AppContext context, int startCount) { super(context, startCount); JobHistoryEventHandler.fileMap.clear(); } public JHEvenHandlerForTest(AppContext context, int startCount, boolean mockHistoryProcessing) { super(context, startCount); this.mockHistoryProcessing = mockHistoryProcessing; JobHistoryEventHandler.fileMap.clear(); } @Override protected void serviceStart() { if (timelineClient != null) { timelineClient.start(); } else if (timelineV2Client != null) { timelineV2Client.start(); } } @Override protected EventWriter createEventWriter(Path historyFilePath) throws IOException { if (mockHistoryProcessing) { this.eventWriter = mock(EventWriter.class); } else { this.eventWriter = super.createEventWriter(historyFilePath); } return this.eventWriter; } @Override protected void closeEventWriter(JobId jobId) { } public EventWriter getEventWriter() { return this.eventWriter; } @Override protected void processDoneFiles(JobId jobId) throws IOException { if (!mockHistoryProcessing) { super.processDoneFiles(jobId); } else { // do nothing } } } /** * Class to help with testSigTermedFunctionality */ class JHEventHandlerForSigtermTest extends JobHistoryEventHandler { public JHEventHandlerForSigtermTest(AppContext context, int startCount) { super(context, startCount); } public void addToFileMap(JobId jobId) { MetaInfo metaInfo = Mockito.mock(MetaInfo.class); Mockito.when(metaInfo.isWriterActive()).thenReturn(true); fileMap.put(jobId, metaInfo); } JobHistoryEvent lastEventHandled; int eventsHandled = 0; @Override public void handleEvent(JobHistoryEvent event) { this.lastEventHandled = event; this.eventsHandled++; } }
{ "content_hash": "bd27a16777b2e8008024462ab5ac6e49", "timestamp": "", "source": "github", "line_count": 1090, "max_line_length": 130, "avg_line_length": 41.7605504587156, "alnum_prop": 0.6881741690283179, "repo_name": "979969786/hadoop", "id": "d951944df6626cc34bce1d3163a46a11a3cb080e", "size": "46325", "binary": false, "copies": "7", "ref": "refs/heads/trunk", "path": "hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/jobhistory/TestJobHistoryEventHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "29602" }, { "name": "Batchfile", "bytes": "67517" }, { "name": "C", "bytes": "1431136" }, { "name": "C++", "bytes": "1741547" }, { "name": "CMake", "bytes": "50732" }, { "name": "CSS", "bytes": "43072" }, { "name": "HTML", "bytes": "151850" }, { "name": "Java", "bytes": "52624472" }, { "name": "JavaScript", "bytes": "28573" }, { "name": "Protocol Buffer", "bytes": "240736" }, { "name": "Python", "bytes": "38263" }, { "name": "Shell", "bytes": "384206" }, { "name": "TeX", "bytes": "19322" }, { "name": "XSLT", "bytes": "15460" } ], "symlink_target": "" }
<?php $app = 'backend'; $fixtures = 'fixtures/fixtures.yml'; if (!include(dirname(__FILE__).'/../bootstrap/functional.php')) { return; } include(dirname(__FILE__).'/backendTestBrowser.class.php'); $b = new backendTestBrowser(); $b-> post('/article/edit/id/1', array('article' => array('end_date' => 'not a date')))-> isStatusCode(302)-> isRequestParameter('module', 'article')-> isRequestParameter('action', 'edit')-> isRedirected(true)-> followRedirect()-> checkResponseElement('input[name="article[end_date]"][value=""]') ; // non rich date (without time) $tomorrow = time() + 86400 + 3600; $b-> customizeGenerator(array('edit' => array('display' => array('title', 'end_date'), 'fields' => array('end_date' => array('params' => 'withtime=false rich=false')))))-> post('/article/edit/id/1', array('article' => array('end_date' => array('day' => date('d', $tomorrow), 'month' => date('m', $tomorrow), 'year' => date('Y', $tomorrow)))))-> isStatusCode(302)-> isRequestParameter('module', 'article')-> isRequestParameter('action', 'edit')-> isRedirected(true)-> followRedirect()-> checkResponseElement(sprintf('select[name="article[end_date][day]"] option[value="%s"][selected="selected"]', date('d', $tomorrow)))-> checkResponseElement(sprintf('select[name="article[end_date][month]"] option[value="%s"][selected="selected"]', date('m', $tomorrow)))-> checkResponseElement(sprintf('select[name="article[end_date][year]"] option[value="%s"][selected="selected"]', date('Y', $tomorrow)))-> checkResponseElement('select[name="article[end_date][hour]"]', false)-> checkResponseElement('select[name="article[end_date][minute]"]', false)-> checkResponseElement('script[src*="calendar"]', false)-> checkResponseElement('script[src]', false)-> checkResponseElement('link[href*="calendar"]', false)-> checkResponseElement('link[href][media]', 2) ; // non rich date (with time) $b-> customizeGenerator(array('edit' => array('fields' => array('end_date' => array('params' => 'withtime=true rich=false')))))-> post('/article/edit/id/1', array('article' => array('end_date' => array('day' => date('d', $tomorrow), 'month' => date('m', $tomorrow), 'year' => date('Y', $tomorrow), 'hour' => date('G', $tomorrow), 'minute' => date('i', $tomorrow)))))-> isStatusCode(302)-> isRequestParameter('module', 'article')-> isRequestParameter('action', 'edit')-> isRedirected(true)-> followRedirect()-> checkResponseElement(sprintf('select[name="article[end_date][day]"] option[value="%s"][selected="selected"]', date('d', $tomorrow)))-> checkResponseElement(sprintf('select[name="article[end_date][month]"] option[value="%s"][selected="selected"]', date('m', $tomorrow)))-> checkResponseElement(sprintf('select[name="article[end_date][year]"] option[value="%s"][selected="selected"]', date('Y', $tomorrow)))-> checkResponseElement(sprintf('select[name="article[end_date][hour]"] option[value="%s"][selected="selected"]', date('G', $tomorrow)))-> checkResponseElement(sprintf('select[name="article[end_date][minute]"] option[value="%s"][selected="selected"]', date('i', $tomorrow))) ;
{ "content_hash": "19c7871e977446d2311864c212e2d2fa", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 240, "avg_line_length": 46.940298507462686, "alnum_prop": 0.6610492845786964, "repo_name": "tedconf/symfony-unofficial", "id": "7e9d34759235a1c0f48c491eb885b22bc6d9e27b", "size": "3400", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "lib/plugins/sfPropelPlugin/test/functional/timeTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "186588" }, { "name": "PHP", "bytes": "5540850" }, { "name": "Shell", "bytes": "8305" } ], "symlink_target": "" }
import abc import json import os from typing import Dict import six from ...datastructures import JSONDict from ...git import git_show_file from ...utils import get_metadata_file, has_logs, is_metric_in_metadata_file, read_metadata_rows from ..constants import V1, V1_STRING, V2, V2_STRING class ValidationResult(object): def __init__(self): self.failed = False self.warning = False self.fixed = False self.messages = {'success': [], 'warning': [], 'failure': [], 'info': []} def __str__(self): return '\n'.join(['\n'.join(messages) for messages in self.messages.values()]) def __repr__(self): return str(self) @six.add_metaclass(abc.ABCMeta) class BaseManifestValidator(object): def __init__( self, is_extras=False, is_marketplace=False, check_in_extras=True, check_in_marketplace=True, ctx=None, version=V1, skip_if_errors=False, ): self.result = ValidationResult() self.is_extras = is_extras self.is_marketplace = is_marketplace self.check_in_extras = check_in_extras self.check_in_markeplace = check_in_marketplace self.ctx = ctx self.version = version self.skip_if_errors = skip_if_errors def should_validate(self): """Determine if validator applicable given the current repo. Logic will always validate integrations-core, but flags exist to selectively include extras and marketplace """ if not self.is_extras and not self.is_marketplace: return True if self.is_extras and self.check_in_extras: return True if self.is_marketplace and self.check_in_markeplace: return True return False def validate(self, check_name, manifest, should_fix): # type: (str, Dict, bool) -> None """Validates the decoded manifest. Will perform inline changes if fix is true""" raise NotImplementedError def fail(self, error_message): self.result.failed = True self.result.messages['failure'].append(error_message) def warning(self, warning_message): self.result.warning = True self.result.messages['warning'].append(warning_message) def fix(self, problem, solution): self.result.warning_msg = problem self.result.success_msg = solution self.result.fixed = True self.result.failed = False def __repr__(self): return str(self.result) class MaintainerValidator(BaseManifestValidator): MAINTAINER_PATH = {V1: '/maintainer', V2: '/author/support_email'} def validate(self, check_name, decoded, fix): if not self.should_validate(): return correct_maintainer = 'help@datadoghq.com' path = self.MAINTAINER_PATH[self.version] maintainer = decoded.get_path(path) if not maintainer.isascii(): self.fail(f' `maintainer` contains non-ascii character: {maintainer}') return if maintainer != correct_maintainer: output = f' incorrect `maintainer`: {maintainer}' if fix: decoded.set_path(path, correct_maintainer) self.fix(output, f' new `maintainer`: {correct_maintainer}') else: self.fail(output) class MetricsMetadataValidator(BaseManifestValidator): METADATA_PATH = {V1: "/assets/metrics_metadata", V2: "/assets/integration/metrics/metadata_path"} def validate(self, check_name, decoded, fix): # metrics_metadata path = self.METADATA_PATH[self.version] metadata_in_manifest = decoded.get_path(path) metadata_file = get_metadata_file(check_name) metadata_file_exists = os.path.isfile(metadata_file) if not metadata_in_manifest and metadata_file_exists: # There is a metadata.csv file but no entry in the manifest.json self.fail(' metadata.csv exists but not defined in the manifest.json of {}'.format(check_name)) elif metadata_in_manifest and not metadata_file_exists: # There is an entry in the manifest.json file but the referenced csv file does not exist. self.fail(' metrics_metadata in manifest.json references a non-existing file: {}.'.format(metadata_file)) class MetricToCheckValidator(BaseManifestValidator): CHECKS_EXCLUDE_LIST = { 'agent_metrics', # this (agent-internal) check doesn't guarantee a list of stable metrics for now 'moogsoft', 'snmp', } METRIC_TO_CHECK_EXCLUDE_LIST = { 'openstack.controller', # "Artificial" metric, shouldn't be listed in metadata file. 'riakcs.bucket_list_pool.workers', # RiakCS 2.1 metric, but metadata.csv lists RiakCS 2.0 metrics only. } METADATA_PATH = {V1: "/assets/metrics_metadata", V2: "/assets/integration/metrics/metadata_path"} METRIC_PATH = {V1: "/metric_to_check", V2: "/assets/integration/metrics/check"} PRICING_PATH = {V1: "/pricing", V2: "/pricing"} def validate(self, check_name, decoded, _): if not self.should_validate() or check_name in self.CHECKS_EXCLUDE_LIST: return metadata_path = self.METADATA_PATH[self.version] metadata_in_manifest = decoded.get_path(metadata_path) # metric_to_check metric_path = self.METRIC_PATH[self.version] metric_to_check = decoded.get_path(metric_path) pricing_path = self.PRICING_PATH[self.version] pricing = decoded.get_path(pricing_path) or [] if metric_to_check: metrics_to_check = metric_to_check if isinstance(metric_to_check, list) else [metric_to_check] for metric in metrics_to_check: # if metric found in pricing, skip and continue evaluating other metrics_to_check if any(p.get('metric') == metric for p in pricing): continue metric_integration_check_name = check_name # snmp vendor specific integrations define metric_to_check # with metrics from `snmp` integration if check_name.startswith('snmp_') and not metadata_in_manifest: metric_integration_check_name = 'snmp' if ( not is_metric_in_metadata_file(metric, metric_integration_check_name) and metric not in self.METRIC_TO_CHECK_EXCLUDE_LIST ): self.fail(f' metric_to_check not in metadata.csv: {metric!r}') elif metadata_in_manifest: # if we have a metadata.csv file but no `metric_to_check` raise an error metadata_file = get_metadata_file(check_name) if os.path.isfile(metadata_file): for _, row in read_metadata_rows(metadata_file): # there are cases of metadata.csv files with just a header but no metrics if row: self.fail(' metric_to_check not included in manifest.json') class ImmutableAttributesValidator(BaseManifestValidator): """ Ensure that immutable attributes haven't changed Skip if the manifest is a new file (i.e. new integration) or if the manifest is being upgraded to V2 """ MANIFEST_VERSION_PATH = "manifest_version" IMMUTABLE_FIELD_PATHS = { V1: ("integration_id", "display_name", "guid"), V2: ( "app_id", "app_uuid", "assets/integration/id", "assets/integration/source_type_name", ), } SHORT_NAME_PATHS = { V1: ( "assets/dashboards", "assets/monitors", "assets/saved_views", ), V2: ( "assets/dashboards", "assets/monitors", "assets/saved_views", ), } def validate(self, check_name, decoded, fix): # Check if previous version of manifest exists # If not, this is a new file so this validation is skipped try: previous = git_show_file(path=f"{check_name}/manifest.json", ref="origin/master") previous_manifest = JSONDict(json.loads(previous)) except Exception: self.result.messages['info'].append( " skipping check for changed fields: integration not on default branch" ) return # Skip this validation if the manifest is being updated from 1.0.0 -> 2.0.0 current_manifest = decoded if ( previous_manifest[self.MANIFEST_VERSION_PATH] == "1.0.0" and current_manifest[self.MANIFEST_VERSION_PATH] == "2.0.0" ): self.result.messages['info'].append(" skipping check for changed fields: manifest version was upgraded") return # Check for differences in immutable attributes for key_path in self.IMMUTABLE_FIELD_PATHS[self.version]: previous_value = previous_manifest.get_path(key_path) current_value = current_manifest.get_path(key_path) if previous_value != current_value: output = f'Attribute `{current_value}` at `{key_path}` is not allowed to be modified. Please revert it \ to the original value `{previous_value}`.' self.fail(output) # Check for differences in `short_name` keys for key_path in self.SHORT_NAME_PATHS[self.version]: previous_short_name_dict = previous_manifest.get_path(key_path) or {} current_short_name_dict = current_manifest.get_path(key_path) or {} # Every `short_name` in the prior manifest must be in the current manifest # The key cannot change and it cannot be removed previous_short_names = previous_short_name_dict.keys() current_short_names = set(current_short_name_dict.keys()) for short_name in previous_short_names: if short_name not in current_short_names: output = f'Short name `{short_name}` at `{key_path}` is not allowed to be modified. \ Please revert to original value.' self.fail(output) class LogsCategoryValidator(BaseManifestValidator): """If an integration defines logs it should have the log collection category""" LOG_COLLECTION_CATEGORY = {V1: "log collection", V2: "Category::Log Collection"} CATEGORY_PATH = {V1: "/categories", V2: "/tile/classifier_tags"} IGNORE_LIST = { 'databricks', # Logs are provided by Spark 'docker_daemon', 'ecs_fargate', # Logs are provided by FireLens or awslogs 'cassandra_nodetool', # Logs are provided by cassandra 'jmeter', 'kafka_consumer', # Logs are provided by kafka 'kubernetes', 'pan_firewall', 'altostra', 'hasura_cloud', 'sqreen', } def validate(self, check_name, decoded, fix): path = self.CATEGORY_PATH[self.version] categories = decoded.get_path(path) or [] check_has_logs = has_logs(check_name) log_collection_category = self.LOG_COLLECTION_CATEGORY[self.version] check_has_logs_category = log_collection_category in categories if check_has_logs == check_has_logs_category or check_name in self.IGNORE_LIST: return if check_has_logs: output = ' required category: ' + log_collection_category if fix: correct_categories = sorted(categories + [self.LOG_COLLECTION_CATEGORY]) decoded.set_path(path, correct_categories) self.fix(output, f' new `categories`: {correct_categories}') else: self.fail(output) else: output = ( ' This integration does not have logs, please remove the category: ' + log_collection_category + ' or define the logs properly' ) self.fail(output) class VersionValidator(BaseManifestValidator): def validate(self, check_name, decoded, fix): if decoded.get('manifest_version', V2_STRING) == V1_STRING: self.fail('Manifest version must be >= 2.0.0')
{ "content_hash": "51fc41cc3e5dc78eb2407c7400a6f847", "timestamp": "", "source": "github", "line_count": 315, "max_line_length": 120, "avg_line_length": 38.939682539682536, "alnum_prop": 0.6128322191423446, "repo_name": "DataDog/integrations-core", "id": "6a9aac2b2607b904ba8024f0c8402a43cfc2ae5c", "size": "12382", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "datadog_checks_dev/datadog_checks/dev/tooling/manifest_validator/common/validator.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "578" }, { "name": "COBOL", "bytes": "12312" }, { "name": "Dockerfile", "bytes": "22998" }, { "name": "Erlang", "bytes": "15518" }, { "name": "Go", "bytes": "6988" }, { "name": "HCL", "bytes": "4080" }, { "name": "HTML", "bytes": "1318" }, { "name": "JavaScript", "bytes": "1817" }, { "name": "Kotlin", "bytes": "430" }, { "name": "Lua", "bytes": "3489" }, { "name": "PHP", "bytes": "20" }, { "name": "PowerShell", "bytes": "2398" }, { "name": "Python", "bytes": "13020828" }, { "name": "Roff", "bytes": "359" }, { "name": "Ruby", "bytes": "241" }, { "name": "Scala", "bytes": "7000" }, { "name": "Shell", "bytes": "83227" }, { "name": "Swift", "bytes": "203" }, { "name": "TSQL", "bytes": "29972" }, { "name": "TypeScript", "bytes": "1019" } ], "symlink_target": "" }
// // MMTextParser.h // BQMM SDK // // Created by ceo on 12/28/15. // Copyright © 2015 siyanhui. All rights reserved. // #import <Foundation/Foundation.h> @interface MMTextParser : NSObject /** * 从text中解析所有MMEmoji,本地没有的emoji code会从服务器实时获取。completionHandler是表情消息解析完成后的回调,参数textImgArray类型可 * 能是MMEmoji或字符串。 * @param text mmtext * @param completionHandler 完成的回调,包含MMEmoji,text对象的集合或者error对象 */ + (void)parseMMText:(NSString *)text completionHandler:(void(^)(NSArray *textImgArray, NSError *error))completionHandler; /** * 从text中解析本地已下载的Emoji * * @param text mmtext * @param completionHandler 完成的回调,包含MMEmoji, text对象的集合或者error对象 */ + (void)localParseMMText:(NSString *)text completionHandler:(void(^)(NSArray *textImgArray))completionHandler; /** * 从mmText中检查出符合emojiCode格式的result数组 * * @param mmText mmText * * @return 符合emojiCode的格式result数组 */ + (NSArray<NSTextCheckingResult *> *)findEmojicodesResultFromMMText:(NSString *)mmText; @end
{ "content_hash": "94778b90cddd3b717f2df770f030dcb6", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 95, "avg_line_length": 25.3, "alnum_prop": 0.7193675889328063, "repo_name": "149393437/ZCXMPPManager", "id": "310788ed5bfaad479281ae8d5601edf0ba1a5ef6", "size": "1235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WeiChat最终版适配ipv6/WeiChat_1511/3rd/ZCFaceToolBar/BQMM/BQMM.framework/Headers/MMTextParser.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "252531" }, { "name": "C++", "bytes": "109360" }, { "name": "HTML", "bytes": "7938" }, { "name": "Objective-C", "bytes": "6297208" }, { "name": "Objective-C++", "bytes": "33049" } ], "symlink_target": "" }
#import "AppDelegate.h" #import "RCTBundleURLProvider.h" #import "RCTRootView.h" #import <FBSDKCoreKit/FBSDKCoreKit.h> @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions]; NSURL *jsCodeLocation; jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil]; RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"Este" initialProperties:nil launchOptions:launchOptions]; rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; return YES; } - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options { BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey] ]; // Add any custom logic here. return handled; } - (void)applicationDidBecomeActive:(UIApplication *)application { [FBSDKAppEvents activateApp]; } @end
{ "content_hash": "4cb7cbed910508ca7d0db5c4023f36d2", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 128, "avg_line_length": 39.333333333333336, "alnum_prop": 0.6430707876370887, "repo_name": "VigneshRavichandran02/3io", "id": "61ebe308266917856e70c63f1293fefebeed7ee2", "size": "2314", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "ios/Este/AppDelegate.m", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "416" }, { "name": "HTML", "bytes": "8353" }, { "name": "Java", "bytes": "2299" }, { "name": "JavaScript", "bytes": "1432146" }, { "name": "Objective-C", "bytes": "5329" }, { "name": "Python", "bytes": "1633" } ], "symlink_target": "" }
module FSelector # # Bi-Normal Separation (BNS) # # BNS = |F'(tpr) - F'(fpr)| # # where F'(x) is the normal inverse cumulative distribution function # R equivalent: qnorm # # ref: [An extensive empirical study of feature selection metrics for text classification](http://dl.acm.org/citation.cfm?id=944974) # class BiNormalSeparation < BaseDiscrete # this algo outputs weight for each feature @algo_type = :filter_by_feature_weighting private # calculate contribution of each feature (f) for each class (k) def calc_contribution(f) each_class do |k| a, b, c, d = get_A(f, k), get_B(f, k), get_C(f, k), get_D(f, k) s = 0.0 x, y = a+c, b+d if not x.zero? and not y.zero? tpr, fpr = a/x, b/y R.eval "rv <- qnorm(#{tpr}) - qnorm(#{fpr})" s = R.rv.abs end set_feature_score(f, k, s) end end # calc_contribution end # class # shortcut so that you can use FSelector::BNS instead of FSelector::BiNormalSeparation BNS = BiNormalSeparation end # module
{ "content_hash": "17f8f9f234dc8081b5445fabe571a356", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 132, "avg_line_length": 25.23913043478261, "alnum_prop": 0.570198105081826, "repo_name": "need47/fselector", "id": "a49b81e1d5ddb14d43066e20375520c6018a3e07", "size": "1223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/fselector/algo_discrete/BiNormalSeparation.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "11681" }, { "name": "Ruby", "bytes": "193408" } ], "symlink_target": "" }
<?php namespace Troiswa\PublicBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * Film * * @ORM\Table(name="film") * @ORM\Entity(repositoryClass="Troiswa\PublicBundle\Entity\FilmRepository") */ class Film { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="titre", type="string", length=255) * @Assert\NotBlank(message="vous n'avez pas rempli le champ titre") * @Assert\Length( * min = "2", * minMessage = "Votre nom doit faire au moins {{ 2 }} caractères", * * ) */ private $titre; /** * @var string * * @ORM\Column(name="synopsis", type="text") * @Assert\NotBlank(message="vous n'avez pas rempli le champ titre") * @Assert\Length( * min = "5", * maxMessage = "Votre nom doit faire maximum {{ 5 }} caractères", * * ) */ private $synopsis; /** * @var \DateTime * * @ORM\Column(name="dateCreation", type="date") * @Assert\NotBlank(message="vous n'avez pas rempli le champ titre") */ private $dateCreation; /** * @var string * * @ORM\Column(name="realisateur", type="string") * @Assert\NotBlank(message="vous n'avez pas rempli le champ realisateur") * @Assert\Length( * min = "2", * minMessage = "Votre nom doit faire au moins {{ 2 }} caractères", * * ) */ private $realisateur; /** * @var \int * * @ORM\Column(name="spectateur", type="integer") * @Assert\NotBlank(message="vous n'avez pas cocher le champ sexe") * @Assert\Choice(choices = {"0", "1","2","3","4", "5"}, message="Choisissez une note entre 0 et 5") */ private $spectateur; /** * @var string * * @ORM\Column(name="image", type="string") * * * */ private $image; /** * une variable qui n'est pas lié à la base de donnée sans les annotation qui va traiter les inforamation du fichier image */ private $fichier; /** * @var string * * @ORM\ManyToOne(targetEntity="Troiswa\PublicBundle\Entity\Categorie",inversedBy="films") * * */ private $categorie; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set titre * * @param string $titre * @return Film */ public function setTitre($titre) { $this->titre = $titre; return $this; } /** * Get titre * * @return string */ public function getTitre() { return $this->titre; } /** * Set synopsis * * @param string $synopsis * @return Film */ public function setSynopsis($synopsis) { $this->synopsis = $synopsis; return $this; } /** * Get synopsis * * @return string */ public function getSynopsis() { return $this->synopsis; } /** * Set dateCreation * * @param \DateTime $dateCreation * @return Film */ public function setDateCreation($dateCreation) { $this->dateCreation = $dateCreation; return $this; } /** * Get dateCreation * * @return \DateTime */ public function getDateCreation() { return $this->dateCreation; } /** * Set realisateur * * @param string $realisateur * @return Film */ public function setRealisateur($realisateur) { $this->realisateur = $realisateur; return $this; } /** * Get realisateur * * @return string */ public function getRealisateur() { return $this->realisateur; } /** * Set spectateur * * @param integer $spectateur * @return Film */ public function setSpectateur($spectateur) { $this->spectateur = $spectateur; return $this; } /** * Get spectateur * * @return integer */ public function getSpectateur() { return $this->spectateur; } /** * Set image * * @param string $image * @return Film */ public function setImage($image) { $this->image = $image; return $this; } /** * Get image * * @return string */ public function getImage() { return $this->image; } public function getFichier() { return $this->fichier; } public function setFichier($fichier) { return $this->fichier = $fichier; } public function upload() { //if si on veut un acteur sans image on a la possibilie de le faire avec cette condition if(null === $this->fichier) { return; } //la fonction getUploadRootDir()cree le chemain vers le dossier quon veut uploader //pour changer le nom de image $nameFile=$this->titre.'-'.uniqid().'.'.$this->fichier->guessExtension(); $this->fichier->move($this->getUploadRootDir(), $nameFile); //$this->fichier->getClientOriginalName()); //$this->image=$this->fichier->getClientOriginalName(); $this->image=$nameFile; } public function getUploadRootDir() { return __DIR__.'/../../../../web/'.$this->getuploadDir(); } public function getWebPath() { if(null === $this->image) { return null; } return $this->getuploadDir()."/".$this->image; } public function getuploadDir() { return "upload/Films"; } /** * Set categorie * * @param \Troiswa\PublicBundle\Entity\Categorie $categorie * @return Film */ //une variable par defaut null public function setCategorie(\Troiswa\PublicBundle\Entity\Categorie $categorie = null) { $this->categorie = $categorie; return $this; } /** * Get categorie * * @return \Troiswa\PublicBundle\Entity\Categorie */ public function getCategorie() { return $this->categorie; } }
{ "content_hash": "770bd9c58c0662412a698a060858ce1b", "timestamp": "", "source": "github", "line_count": 353, "max_line_length": 127, "avg_line_length": 18.577903682719548, "alnum_prop": 0.5161634644708752, "repo_name": "imenelbeji/mon-projet--symfony", "id": "887dfbf3cfabbd745edddee629e13bc2a4cae92a", "size": "6564", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Troiswa/PublicBundle/Entity/Film.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "110784" }, { "name": "JavaScript", "bytes": "131040" }, { "name": "PHP", "bytes": "119683" } ], "symlink_target": "" }
// MIT License // // Copyright (c) 2017 Peter Dennis Bartok // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // using System; namespace ReSignTool { static class Program { [STAThread] static int Main(string[] args) { ReSign rs; bool verbose; bool debug; string error; string config_file; verbose = false; debug = false; config_file = null; for (int i = 0; i < args.Length; i++) { if (args[i] == "-v") { verbose = true; } else if (args[i] == "-d") { debug = true; } else { config_file = args[i]; } } if ((args.Length == 0) || (config_file == null)) { Console.WriteLine("Usage: ReSignTool [-v] [-d] <xml-configuration-file>"); return 1; } rs = new ReSign(config_file); rs.Verbose = verbose; rs.Debug = debug; if (!rs.Process(out error)) { Console.WriteLine("Error: Re-signing failed with error: " + error); return 2; } return 0; } } }
{ "content_hash": "1087d24a360d0d5537fb34303e891147", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 81, "avg_line_length": 29.582089552238806, "alnum_prop": 0.6740665993945509, "repo_name": "pdb0102/ReSignTool", "id": "a798e5f927a3dcd8c6e182b10b0de210e969d824", "size": "1984", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ReSignTool/Program.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "24775" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>relation-algebra: 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.13.1 / relation-algebra - 1.7.2</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> relation-algebra <small> 1.7.2 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-22 14:17:30 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-22 14:17:30 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.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 zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-relation-algebra&quot; synopsis: &quot;Relation Algebra and KAT in Coq&quot; maintainer: &quot;Damien Pous &lt;Damien.Pous@ens-lyon.fr&gt;&quot; version: &quot;1.7.2&quot; homepage: &quot;http://perso.ens-lyon.fr/damien.pous/ra/&quot; license: &quot;LGPL&quot; depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} ] depopts: [ &quot;coq-mathcomp-ssreflect&quot; ] build: [ [&quot;sh&quot; &quot;-exc&quot; &quot;./configure --%{coq-mathcomp-ssreflect:enable}%-ssr&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [make &quot;install&quot;] tags: [ &quot;keyword:relation algebra&quot; &quot;keyword:Kleene algebra with tests&quot; &quot;keyword:KAT&quot; &quot;keyword:allegories&quot; &quot;keyword:residuated structures&quot; &quot;keyword:automata&quot; &quot;keyword:regular expressions&quot; &quot;keyword:matrices&quot; &quot;category:Mathematics/Algebra&quot; &quot;logpath:RelationAlgebra&quot; ] authors: [ &quot;Damien Pous &lt;Damien.Pous@ens-lyon.fr&gt;&quot; &quot;Christian Doczkal &lt;christian.doczkal@ens-lyon.fr&gt;&quot; ] url { src: &quot;https://github.com/damien-pous/relation-algebra/archive/v1.7.2.tar.gz&quot; checksum: &quot;md5=2f7d9a91892145dc373121bd2b176690&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-relation-algebra.1.7.2 coq.8.13.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.13.1). The following dependencies couldn&#39;t be met: - coq-relation-algebra -&gt; coq &lt; 8.11~ -&gt; ocaml &lt; 4.06.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-relation-algebra.1.7.2</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": "7a76ededaf4fbb3b490bf922d488502a", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 159, "avg_line_length": 40.00555555555555, "alnum_prop": 0.5481183169004304, "repo_name": "coq-bench/coq-bench.github.io", "id": "85fd5f702b5e6466202d59d691ee63995636513d", "size": "7226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.13.1/relation-algebra/1.7.2.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import * as React from "react"; import { Camera } from "babylonjs/Cameras/camera"; import { Observable } from "babylonjs/Misc/observable"; import { PropertyChangedEvent } from "../../../../propertyChangedEvent"; import { SliderLineComponent } from "../../../lines/sliderLineComponent"; import { LineContainerComponent } from "../../../lineContainerComponent"; import { FloatLineComponent } from "../../../lines/floatLineComponent"; import { TextLineComponent } from "../../../lines/textLineComponent"; import { OptionsLineComponent } from "../../../lines/optionsLineComponent"; import { LockObject } from "../lockObject"; import { GlobalState } from '../../../../globalState'; import { CustomPropertyGridComponent } from '../customPropertyGridComponent'; import { ButtonLineComponent } from '../../../lines/buttonLineComponent'; import { TextInputLineComponent } from '../../../lines/textInputLineComponent'; import { AnimationGridComponent } from '../animations/animationPropertyGridComponent'; import { HexLineComponent } from '../../../lines/hexLineComponent'; interface ICommonCameraPropertyGridComponentProps { globalState: GlobalState; camera: Camera; lockObject: LockObject; onPropertyChangedObservable?: Observable<PropertyChangedEvent>; } export class CommonCameraPropertyGridComponent extends React.Component<ICommonCameraPropertyGridComponentProps, { mode: number }> { constructor(props: ICommonCameraPropertyGridComponentProps) { super(props); this.state = { mode: this.props.camera.mode }; } render() { const camera = this.props.camera; var modeOptions = [ { label: "Perspective", value: Camera.PERSPECTIVE_CAMERA }, { label: "Orthographic", value: Camera.ORTHOGRAPHIC_CAMERA } ]; return ( <div> <CustomPropertyGridComponent globalState={this.props.globalState} target={camera} lockObject={this.props.lockObject} onPropertyChangedObservable={this.props.onPropertyChangedObservable} /> <LineContainerComponent globalState={this.props.globalState} title="GENERAL"> <TextLineComponent label="ID" value={camera.id} /> <TextInputLineComponent lockObject={this.props.lockObject} label="Name" target={camera} propertyName="name" onPropertyChangedObservable={this.props.onPropertyChangedObservable}/> <TextLineComponent label="Unique ID" value={camera.uniqueId.toString()} /> <TextLineComponent label="Class" value={camera.getClassName()} /> <FloatLineComponent lockObject={this.props.lockObject} label="Near plane" target={camera} propertyName="minZ" onPropertyChangedObservable={this.props.onPropertyChangedObservable} /> <FloatLineComponent lockObject={this.props.lockObject} label="Far plane" target={camera} propertyName="maxZ" onPropertyChangedObservable={this.props.onPropertyChangedObservable} /> <SliderLineComponent label="Inertia" target={camera} propertyName="inertia" minimum={0} maximum={1} step={0.01} onPropertyChangedObservable={this.props.onPropertyChangedObservable} /> <HexLineComponent isInteger lockObject={this.props.lockObject} label="Layer mask" target={camera} propertyName="layerMask" onPropertyChangedObservable={this.props.onPropertyChangedObservable} /> <OptionsLineComponent label="Mode" options={modeOptions} target={camera} propertyName="mode" onPropertyChangedObservable={this.props.onPropertyChangedObservable} onSelect={(value) => this.setState({ mode: value })} /> { camera.mode === Camera.PERSPECTIVE_CAMERA && <SliderLineComponent label="Field of view" target={camera} useEuler={this.props.globalState.onlyUseEulers} propertyName="fov" minimum={0.1} maximum={Math.PI} step={0.1} onPropertyChangedObservable={this.props.onPropertyChangedObservable} /> } { camera.mode === Camera.ORTHOGRAPHIC_CAMERA && <FloatLineComponent lockObject={this.props.lockObject} label="Left" target={camera} propertyName="orthoLeft" onPropertyChangedObservable={this.props.onPropertyChangedObservable} /> } { camera.mode === Camera.ORTHOGRAPHIC_CAMERA && <FloatLineComponent lockObject={this.props.lockObject} label="Top" target={camera} propertyName="orthoTop" onPropertyChangedObservable={this.props.onPropertyChangedObservable} /> } { camera.mode === Camera.ORTHOGRAPHIC_CAMERA && <FloatLineComponent lockObject={this.props.lockObject} label="Right" target={camera} propertyName="orthoRight" onPropertyChangedObservable={this.props.onPropertyChangedObservable} /> } { camera.mode === Camera.ORTHOGRAPHIC_CAMERA && <FloatLineComponent lockObject={this.props.lockObject} label="Bottom" target={camera} propertyName="orthoBottom" onPropertyChangedObservable={this.props.onPropertyChangedObservable} /> } <ButtonLineComponent label="Dispose" onClick={() => { camera.dispose(); this.props.globalState.onSelectionChangedObservable.notifyObservers(null); }} /> </LineContainerComponent> <AnimationGridComponent globalState={this.props.globalState} animatable={camera} scene={camera.getScene()} lockObject={this.props.lockObject} /> </div> ); } }
{ "content_hash": "4eedd29572d223834d25ee1865e5e793", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 264, "avg_line_length": 70.5, "alnum_prop": 0.6469098277608916, "repo_name": "Kesshi/Babylon.js", "id": "9e35b1f84696e9b28c87f10caef0070fd8ffab5a", "size": "5922", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "inspector/src/components/actionTabs/tabs/propertyGrids/cameras/commonCameraPropertyGridComponent.tsx", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2834" }, { "name": "CSS", "bytes": "75968" }, { "name": "HLSL", "bytes": "430883" }, { "name": "HTML", "bytes": "225776" }, { "name": "JavaScript", "bytes": "572332" }, { "name": "TypeScript", "bytes": "8573884" } ], "symlink_target": "" }
 #pragma once #include <aws/kinesisanalyticsv2/KinesisAnalyticsV2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/kinesisanalyticsv2/model/ReferenceDataSourceDescription.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace KinesisAnalyticsV2 { namespace Model { class AWS_KINESISANALYTICSV2_API AddApplicationReferenceDataSourceResult { public: AddApplicationReferenceDataSourceResult(); AddApplicationReferenceDataSourceResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); AddApplicationReferenceDataSourceResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The application Amazon Resource Name (ARN).</p> */ inline const Aws::String& GetApplicationARN() const{ return m_applicationARN; } /** * <p>The application Amazon Resource Name (ARN).</p> */ inline void SetApplicationARN(const Aws::String& value) { m_applicationARN = value; } /** * <p>The application Amazon Resource Name (ARN).</p> */ inline void SetApplicationARN(Aws::String&& value) { m_applicationARN = std::move(value); } /** * <p>The application Amazon Resource Name (ARN).</p> */ inline void SetApplicationARN(const char* value) { m_applicationARN.assign(value); } /** * <p>The application Amazon Resource Name (ARN).</p> */ inline AddApplicationReferenceDataSourceResult& WithApplicationARN(const Aws::String& value) { SetApplicationARN(value); return *this;} /** * <p>The application Amazon Resource Name (ARN).</p> */ inline AddApplicationReferenceDataSourceResult& WithApplicationARN(Aws::String&& value) { SetApplicationARN(std::move(value)); return *this;} /** * <p>The application Amazon Resource Name (ARN).</p> */ inline AddApplicationReferenceDataSourceResult& WithApplicationARN(const char* value) { SetApplicationARN(value); return *this;} /** * <p>The updated application version ID. Kinesis Data Analytics increments this ID * when the application is updated.</p> */ inline long long GetApplicationVersionId() const{ return m_applicationVersionId; } /** * <p>The updated application version ID. Kinesis Data Analytics increments this ID * when the application is updated.</p> */ inline void SetApplicationVersionId(long long value) { m_applicationVersionId = value; } /** * <p>The updated application version ID. Kinesis Data Analytics increments this ID * when the application is updated.</p> */ inline AddApplicationReferenceDataSourceResult& WithApplicationVersionId(long long value) { SetApplicationVersionId(value); return *this;} /** * <p>Describes reference data sources configured for the application. </p> */ inline const Aws::Vector<ReferenceDataSourceDescription>& GetReferenceDataSourceDescriptions() const{ return m_referenceDataSourceDescriptions; } /** * <p>Describes reference data sources configured for the application. </p> */ inline void SetReferenceDataSourceDescriptions(const Aws::Vector<ReferenceDataSourceDescription>& value) { m_referenceDataSourceDescriptions = value; } /** * <p>Describes reference data sources configured for the application. </p> */ inline void SetReferenceDataSourceDescriptions(Aws::Vector<ReferenceDataSourceDescription>&& value) { m_referenceDataSourceDescriptions = std::move(value); } /** * <p>Describes reference data sources configured for the application. </p> */ inline AddApplicationReferenceDataSourceResult& WithReferenceDataSourceDescriptions(const Aws::Vector<ReferenceDataSourceDescription>& value) { SetReferenceDataSourceDescriptions(value); return *this;} /** * <p>Describes reference data sources configured for the application. </p> */ inline AddApplicationReferenceDataSourceResult& WithReferenceDataSourceDescriptions(Aws::Vector<ReferenceDataSourceDescription>&& value) { SetReferenceDataSourceDescriptions(std::move(value)); return *this;} /** * <p>Describes reference data sources configured for the application. </p> */ inline AddApplicationReferenceDataSourceResult& AddReferenceDataSourceDescriptions(const ReferenceDataSourceDescription& value) { m_referenceDataSourceDescriptions.push_back(value); return *this; } /** * <p>Describes reference data sources configured for the application. </p> */ inline AddApplicationReferenceDataSourceResult& AddReferenceDataSourceDescriptions(ReferenceDataSourceDescription&& value) { m_referenceDataSourceDescriptions.push_back(std::move(value)); return *this; } private: Aws::String m_applicationARN; long long m_applicationVersionId; Aws::Vector<ReferenceDataSourceDescription> m_referenceDataSourceDescriptions; }; } // namespace Model } // namespace KinesisAnalyticsV2 } // namespace Aws
{ "content_hash": "4994e30a56e2803117c31034be0e1c14", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 211, "avg_line_length": 38.32592592592592, "alnum_prop": 0.734441437959026, "repo_name": "cedral/aws-sdk-cpp", "id": "627992a6a34cf3aad61f6b36656035acfc5cdc8f", "size": "5293", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "aws-cpp-sdk-kinesisanalyticsv2/include/aws/kinesisanalyticsv2/model/AddApplicationReferenceDataSourceResult.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
Widget.EditorHeader = function (title) { var data = {title: title, color: property.baseline_color2} this.data = data this.html = parse(function(){/*! <header id="header" class="skel-layers-fixed"> <nav id="nav"> <ul> <!-- Login --> <li><div id="login" class="hand" onclick='Widget.EditorHeader.login();'> <i class="fa fa-user-secret"></i></div> </li> <!-- Database --> <li><a id="database" class="hand" style="color: {{color}};" href="{{@ property.databaseUrl + property.databaseHomeUrl}}" target="_blank"> <i class="fa fa-database"></i></a> </li> <!-- Comapre --> <li><a id="compare" class="hand" style="color: {{color}};" href="{{@ property.editorUrl + property.compareUrl}}" target="_blank"> <i class="fa fa-files-o"></i></a> </li> <!-- Cryptography --> <li><a id="cryptography" class="hand" style="color: {{color}};" href="{{@ property.editorUrl + property.cryptographyUrl}}" target="_blank"> <i class="fa fa-key"></i></a> </li> <!-- Search --> <li><div id="search" class="hand" onclick='Widget.EditorHeader.search();'> <i class="fa fa-question"></i></div> </li> <!-- Home Directory --> <li><div id="setHomeDirectoryAction" class="hand" onclick='Widget.EditorHeader.setHomeDirectory();'> <i class="fa fa-home"></i></div> </li> <!-- Open New Window --> <li><a id="openNewWindowAction" class="hand" style="color: {{color}};" href="javascript:;" target="_blank" onclick='Widget.EditorHeader.openNewWindow();'> <i class="fa fa-share"></i></a> </li> <!-- Repository --> <li><div id="setRepositoryAction" class="hand" onclick='Widget.EditorHeader.setRepository();'> <i class="fa fa-eye"></i> <i class="fa fa-user"></i></div> </li> <li><a id="repositoryFileHistoryAction" class="hand" style="color: {{color}};" href="javascript:;" target="_blank" onclick='return Widget.EditorHeader.repositoryFileHistory();'> <i class="fa fa-eye"></i> <i class="fa fa-file-o"></i></a> </li> <li><a id="repositoryStatusAction" class="hand" style="color: {{color}};" href="javascript:;" target="_blank" onclick='return Widget.EditorHeader.repositoryStatus();'> <i class="fa fa-eye"></i> <i class="fa fa-folder-open"></i></a> </li> <li><div id="repositoryLogHistoryAction" class="hand" onclick='Widget.EditorHeader.repositoryLogHistory();'> <i class="fa fa-eye"></i> <i class="fa fa-bars"></i></div> </li> <li><div id="repositoryCommitHistoryAction" class="hand" onclick='Widget.EditorHeader.repositoryCommitHistory();'> <i class="fa fa-eye"></i> <i class="fa fa-random"></i></div> </li> <!-- Upload & Download --> <li><div id="openUploaderAction" class="hand" onclick='Widget.EditorHeader.openUploader();'> <i class="fa fa-university"></i></div> </li> <li><div id="uploadFileAction" class="hand" onclick='Widget.EditorHeader.uploadFile();'> <i class="fa fa-cloud-upload"></i></div> <form action="" method="post" id="uploadFileForm" target="_blank" enctype="multipart/form-data" style="display: none;"> <input type="file" name="file" id="uploadFileInput" multiple=""/> <form/> </li> <li><div id="downloadFileAction" class="hand" onclick='Widget.EditorHeader.downloadFile();'> <i class="fa fa-cloud-download"></i></div> <form action="" method="post" id="downloadFileForm" target="_blank" style="display: none;"> <form/> </li> <!-- Create --> <li><div id="createFileAction" class="hand" onclick='Widget.EditorHeader.createFileName();'> <i class="fa fa-plus"></i> <i class="fa fa-file-o"></i></div> </li> <li><div id="createDirectoryAction" class="hand" onclick='Widget.EditorHeader.createDirectoryName();'> <i class="fa fa-plus"></i> <i class="fa fa-folder-open"></i></div> </li> <!-- Remove --> <li><div id="removeFileAction" class="hand" onclick='Widget.EditorHeader.removeFileName();'> <i class="fa fa-minus"></i> <i class="fa fa-file-o"></i></div> </li> <li><div id="removeDirectoryAction" class="hand" onclick='Widget.EditorHeader.removeDirectoryName();'> <i class="fa fa-minus"></i> <i class="fa fa-folder-open"></i></div> </li> <!-- Rename --> <li><div id="renameFileAction" class="hand" onclick='Widget.EditorHeader.renameFileName();'> <i class="fa fa-wrench"></i> <i class="fa fa-file-o"></i></div> </li> <li><div id="renameDirectoryAction" class="hand" onclick='Widget.EditorHeader.renameDirectoryName();'> <i class="fa fa-wrench"></i> <i class="fa fa-folder-open"></i></div> </li> <!-- Edit --> <li><div id="editFileAction" class="hand" onclick='Widget.EditorHeader.editFile();'> <i class="fa fa-pencil-square-o"></i></div> </li> <!-- Save --> <li><div id="saveAction" class="button special" onclick='Widget.EditorHeader.save();'> {{@ property.editorSaved}}</div> </li> </ul> </nav> </header> */}, data) } Widget.EditorHeader.prototype = { constructor: Widget.EditorHeader } Widget.EditorHeader.height = function () { return $('#header').height() } // // login // Widget.EditorHeader.login = function () { var loginPopup = new Widget.TwoFieldsPopup({ info:"Set login credentials.", placeholder1: "Email", placeholder2: "Password", password: 2, proceed: function (emailGuid, passwordGuid) { var email = $("#" + emailGuid).val() var password = $("#" + passwordGuid).val() if (!isEmpty(email) && !isEmpty(password)) { $.post(property.securityLoginUserUrl, {email: email, password: password}) .success(function (data) { Widget.successHandler(data) }) .error(Widget.errorHandler) this.delete() } else { this.delete() var infoPopup = new Widget.InfoPopup({info: "Email and Password are required!"}) } }}) } // // search // Widget.EditorHeader.search = function () { var directoryName = editor.homeDirectory || editor.directoryName if (isEmpty(directoryName)) { var infoPopup = new Widget.InfoPopup({info: "directory is required!"}) return false } var searchPopup = new Widget.EditorSearchPopup({ info:"Search.", proceed: function (proceedButtonGuid, queryGuid, replaceGuid, filterGuid, isRegexGuid, isFileNameGuid, isIgnoreCaseGuid) { var query = $("#" + queryGuid).val() var replace = $("#" + replaceGuid).val() var filter = $("#" + filterGuid).val() var isRegex = $("#" + isRegexGuid).is(':checked') var isFileName = $("#" + isFileNameGuid).is(':checked') var isIgnoreCase = $("#" + isIgnoreCaseGuid).is(':checked') if (!isEmpty(query)) { if (isEmpty(replace)) { $("#" + proceedButtonGuid).attr("href", Widget.EditorHeader.newSessionUrl( property.editorUrl + property.editorSearchUrl, {directoryName: encodeURIComponent(directoryName), query: encodeURIComponent(query), filter: encodeURIComponent(filter), isRegex: isRegex, isFileName: isFileName, isIgnoreCase: isIgnoreCase})) } else { $("#" + proceedButtonGuid).attr("href", Widget.EditorHeader.newSessionUrl( property.editorUrl + property.editorSearchUrl, {directoryName: encodeURIComponent(directoryName), query: encodeURIComponent(query), replace: encodeURIComponent(replace), filter: encodeURIComponent(filter), isRegex: isRegex, isFileName: isFileName, isIgnoreCase: isIgnoreCase})) } } else { this.delete() var infoPopup = new Widget.InfoPopup({info: "query is required!"}) return false } }}) } // // homeDirectory // Widget.EditorHeader.setHomeDirectory = function () { if (!isEmpty(editor.directoryName)) { var paths = editor.directoryName.split('/'); var simpleDirectoryName = paths[paths.length - 1] var questionPopup = new Widget.QuestionPopup({ question: "Set " + simpleDirectoryName + " as home directory?", proceed: function () { var newSessionUrl = Widget.EditorHeader.newSessionUrl( property.editorUrl + property.editorDirectoryUrl, {d: encodeURIComponent(editor.directoryName)}, true) $.get(newSessionUrl) .success(function (dirs) { var subdirs = new Widget.EditorNavigation(Widget.json(dirs), {path: editor.directoryName, name: simpleDirectoryName}) editorTemplate.setDirectoryNavigation(subdirs.html) editor.homeDirectory = editor.directoryName $("#title").html(simpleDirectoryName) $("#menu").html(simpleDirectoryName) }) .error(Widget.errorHandler) this.delete() }}) } else { var infoPopup = new Widget.InfoPopup({info: "Select directory!"}) } } // // newWindow // Widget.EditorHeader.openNewWindow = function () { var directoryName = editor.homeDirectory || editor.directoryName if (!isEmpty(directoryName)) { var newSessionUrl = Widget.EditorHeader.newSessionUrl( property.editorUrl + property.editorHomeUrl, {directoryName: encodeURIComponent(directoryName)}) $("#openNewWindowAction").attr("href", newSessionUrl) } else { var infoPopup = new Widget.InfoPopup({info: "directory is required!"}) return false } } // // repository // Widget.EditorHeader.setRepository = function () { var repositoryPopup = new Widget.ThreeFieldsPopup({ info:"Set repository credentials.", placeholder1: "Repository Name", placeholder2: "User Name", placeholder3: "Password", password: 3, proceed: function (guid1, guid2, guid3) { var repository = $("#" + guid1).val() var username = $("#" + guid2).val() var password = $("#" + guid3).val() this.delete() if (!isEmpty(repository) && !isEmpty(username) && !isEmpty(password)) { vars.repository = { repository: repository, username: username, password: password } var infoPopup = new Widget.InfoPopup({info: "repository set!"}) } else { var infoPopup = new Widget.InfoPopup({info: "repository, username and password are required!"}) } }}) } Widget.EditorHeader.getRepository = function () { var repository if (vars.repository) { repository = vars.repository } else { repository = { repository: getURLParameter("repository") || "", username: getURLParameter("username") || "", password: getURLParameter("password") || "" } } return repository } Widget.EditorHeader.isRepositorySet = function () { var repository = Widget.EditorHeader.getRepository() return (!isEmpty(repository.repository) && !isEmpty(repository.username) && !isEmpty(repository.password)) } Widget.EditorHeader.newSessionUrl = function (controller, data, noHiddenData) { var url = controller + "?session=new" if (noHiddenData) { // do not include hidden data } else { // include repository var repository = Widget.EditorHeader.getRepository() for (var key in repository) { url += "&" + key + "=" + repository[key] } } for (var key in data) { url += "&" + key + "=" + data[key] } return url } Widget.EditorHeader.repositoryFileHistory = function () { var directoryName = editor.homeDirectory || editor.directoryName if (isEmpty(directoryName)) { directoryName = getURLParameter("directoryName") } var fileName = editor.fileName if (Widget.EditorHeader.isRepositorySet() && !isEmpty(fileName)) { var newSessionUrl = Widget.EditorHeader.newSessionUrl( property.repositoryUrl + property.repositoryFileHistoryUrl, {fileName: encodeURIComponent(fileName), directoryName: encodeURIComponent(directoryName)}) $("#repositoryFileHistoryAction").attr("href", newSessionUrl) } else { var infoPopup = new Widget.InfoPopup({info: "repository and file are required!"}) return false } } Widget.EditorHeader.repositoryStatus = function () { var directoryName = editor.homeDirectory || editor.directoryName if (Widget.EditorHeader.isRepositorySet() && !isEmpty(directoryName)) { var newSessionUrl = Widget.EditorHeader.newSessionUrl( property.repositoryUrl + property.repositoryStatusUrl, {directoryName: encodeURIComponent(directoryName)}) $("#repositoryStatusAction").attr("href", newSessionUrl) } else { var infoPopup = new Widget.InfoPopup({info: "repository and directory are required!"}) return false } } Widget.EditorHeader.repositoryLogHistory = function () { var directoryName = editor.homeDirectory || editor.directoryName if (Widget.EditorHeader.isRepositorySet() && !isEmpty(directoryName)) { var limitLogHistoryPopup = new Widget.OneFieldPopup({ info:"Repository log history.", placeholder: "Number of revisions", proceed: function (guid) { var limit = $("#" + guid).val() this.delete() var newSessionUrl = Widget.EditorHeader.newSessionUrl( property.repositoryUrl + property.repositoryLogHistoryUrl, {directoryName: encodeURIComponent(directoryName), limit: limit}) window.open(newSessionUrl) }}) } else { var infoPopup = new Widget.InfoPopup({info: "repository and directory are required!"}) return false } } Widget.EditorHeader.repositoryCommitHistory = function () { if (getURLParameter("repository") == "SVN") { Widget.EditorHeader.repositoryCommitHistorySVN() } else if (getURLParameter("repository") == "GIT") { Widget.EditorHeader.repositoryCommitHistoryGIT() } } Widget.EditorHeader.repositoryCommitHistorySVN = function () { var directoryName = editor.homeDirectory || editor.directoryName if (Widget.EditorHeader.isRepositorySet() && !isEmpty(directoryName)) { var commitHistoryPopup = new Widget.TwoFieldsPopup({ info:"Repository commit history.", placeholder1: "New revision", placeholder2: "Old revision", proceed: function (newRevisionGuid, oldRevisionGuid) { var newRevision = $("#" + newRevisionGuid).val() var oldRevision = $("#" + oldRevisionGuid).val() this.delete() if (!isEmpty(newRevision) && !isEmpty(oldRevision)) { var newSessionUrl = Widget.EditorHeader.newSessionUrl( property.repositoryUrl + property.repositoryCommitHistoryUrl, {directoryName: encodeURIComponent(directoryName), newRevision: newRevision, oldRevision: oldRevision}) window.open(newSessionUrl) } else { var infoPopup = new Widget.InfoPopup({info: "new and old revisions is required!"}) } }}) } else { var infoPopup = new Widget.InfoPopup({info: "repository and directory are required!"}) return false } } Widget.EditorHeader.repositoryCommitHistoryGIT = function () { var directoryName = editor.homeDirectory || editor.directoryName if (Widget.EditorHeader.isRepositorySet() && !isEmpty(directoryName)) { var commitHistoryPopup = new Widget.TwoFieldsPopup({ info:"Repository commit history.", placeholder1: "New commit", placeholder2: "Old commit", proceed: function (newRevisionGuid, oldRevisionGuid) { var newRevision = $("#" + newRevisionGuid).val() var oldRevision = $("#" + oldRevisionGuid).val() this.delete() if (!isEmpty(newRevision)) { var newSessionUrl = Widget.EditorHeader.newSessionUrl( property.repositoryUrl + property.repositoryCommitHistoryUrl, {directoryName: encodeURIComponent(directoryName), newRevision: newRevision, oldRevision: oldRevision}) window.open(newSessionUrl) } else { var infoPopup = new Widget.InfoPopup({info: "commit number is required!"}) } }}) } else { var infoPopup = new Widget.InfoPopup({info: "repository and directory are required!"}) return false } } // // upload // Widget.EditorHeader.openUploader = function () { $('#uploadFileInput').trigger('click') } Widget.EditorHeader.uploadFile = function () { if (!isEmpty(editor.directoryName) && !isEmpty($("#uploadFileInput").val())) { var directoryName = editor.directoryName var paths = editor.directoryName.split('/'); var simpleDirectoryName = paths[paths.length - 1] var questionPopup = new Widget.QuestionPopup({ question: "Upload file(s) to " + simpleDirectoryName + "?", proceed: function () { $("#uploadFileForm").attr("action", property.editorUrl + property.editorUploadFileUrl + "?directoryName=" + encodeURIComponent(directoryName)) $("#uploadFileForm").trigger("submit") this.delete() }}) } else { var infoPopup = new Widget.InfoPopup({info: "Select parent directory and file(s) to upload!"}) } } Widget.EditorHeader.downloadFile = function () { if (!isEmpty(editor.fileName)) { var fileName = editor.fileName var paths = editor.fileName.split('/'); var simpleFileName = paths[paths.length - 1] var questionPopup = new Widget.QuestionPopup({ question: "Download file " + simpleFileName + "?", proceed: function () { $("#downloadFileForm").attr("action", property.editorUrl + property.editorDownloadFileUrl + "?f=" + encodeURIComponent(fileName)) $("#downloadFileForm").trigger("submit") this.delete() }}) } else { var infoPopup = new Widget.InfoPopup({info: "Select file to download!"}) } } // // create/add // Widget.EditorHeader.createFileName = function () { if (!isEmpty(editor.directoryName)) { var createFileNamePopup = new Widget.OneFieldPopup({ info:"Create file.", placeholder: "File Name", proceed: function (guid) { var name = $("#" + guid).val() if (!isEmpty(name)) { var paths = editor.directoryName.split('/'); paths.push(name) $.get(Widget.EditorHeader.newSessionUrl( property.editorUrl + property.editorCreateFileUrl, {fileName: encodeURIComponent(paths.join('/'))})) .success(function (data) { Widget.successHandler(data, name + " created!") }) .error(Widget.errorHandler) } this.delete() }}) } else { var infoPopup = new Widget.InfoPopup({info: "Select parent directory!"}) } } Widget.EditorHeader.createDirectoryName = function () { if (!isEmpty(editor.directoryName)) { var createDirectoryNamePopup = new Widget.OneFieldPopup({ info:"Create directory.", placeholder: "Directory Name", proceed: function (guid) { var name = $("#" + guid).val() if (!isEmpty(name)) { var paths = editor.directoryName.split('/'); paths.push(name) $.get(Widget.EditorHeader.newSessionUrl( property.editorUrl + property.editorCreateDirectoryUrl, {directoryName: encodeURIComponent(paths.join('/'))})) .success(function (data) { Widget.successHandler(data, name + " created!") }) .error(Widget.errorHandler) } this.delete() }}) } else { var infoPopup = new Widget.InfoPopup({info: "Select parent directory!"}) } } // // remove/delete // Widget.EditorHeader.removeFileName = function () { if (!isEmpty(editor.fileName)) { var fileName = editor.fileName var paths = editor.fileName.split('/'); var simpleFileName = paths[paths.length - 1] var questionPopup = new Widget.QuestionPopup({ question: "Delete " + simpleFileName + "?", proceed: function () { $.get(Widget.EditorHeader.newSessionUrl( property.editorUrl + property.editorRemoveUrl, {path: encodeURIComponent(fileName), isFile: "true"})) .success(function (data) { Widget.successHandler(data, simpleFileName + " deleted!") $("#" + editor.fileGuid).hide() editor.fileName = null editor.fileGuid = null }) .error(Widget.errorHandler) this.delete() }}) } else { var infoPopup = new Widget.InfoPopup({info: "Select file to delete!"}) } } Widget.EditorHeader.removeDirectoryName = function () { if (!isEmpty(editor.directoryName)) { var directoryName = editor.directoryName var paths = editor.directoryName.split('/'); var simpleDirectoryName = paths[paths.length - 1] var questionPopup = new Widget.QuestionPopup({ question: "Delete " + simpleDirectoryName + "?", proceed: function () { $.get(Widget.EditorHeader.newSessionUrl( property.editorUrl + property.editorRemoveUrl, {path: encodeURIComponent(directoryName), isFile: "false"})) .success(function (data) { Widget.successHandler(data, simpleDirectoryName + " deleted!") $("#" + editor.directoryGuid).parent().hide() // hide directory list element editor.directoryName = null editor.directoryGuid = null }) .error(Widget.errorHandler) this.delete() }}) } else { var infoPopup = new Widget.InfoPopup({info: "Select directory to delete!"}) } } // // rename/move // Widget.EditorHeader.renameFileName = function () { if (!isEmpty(editor.fileName)) { var paths = editor.fileName.split('/'); var simpleFileName = paths[paths.length - 1] var renameFileNamePopup = new Widget.OneFieldPopup({ info:"Rename.", placeholder: "", value: simpleFileName, proceed: function (guid) { var name = $("#" + guid).val() if (!isEmpty(name)) { paths[paths.length - 1] = name $.get(Widget.EditorHeader.newSessionUrl(property.editorUrl + property.editorRenameUrl, { oldName: encodeURIComponent(editor.fileName), newName: encodeURIComponent(paths.join('/')), directoryName: encodeURIComponent(editor.homeDirectory) })) .success(function (data) { Widget.successHandler(data, simpleFileName + " renamed to " + name) }) .error(Widget.errorHandler) } this.delete() }}) } else { var infoPopup = new Widget.InfoPopup({info: "Select file!"}) } } Widget.EditorHeader.renameDirectoryName = function () { if (!isEmpty(editor.directoryName)) { var paths = editor.directoryName.split('/'); var simpleDirectoryName = paths[paths.length - 1] var renameDirectoryNamePopup = new Widget.OneFieldPopup({ info:"Rename.", placeholder: "", value: simpleDirectoryName, proceed: function (guid) { var name = $("#" + guid).val() if (!isEmpty(name)) { paths[paths.length - 1] = name $.get(Widget.EditorHeader.newSessionUrl( property.editorUrl + property.editorRenameUrl, {oldName: encodeURIComponent(editor.directoryName), newName: encodeURIComponent(paths.join('/')), directoryName: encodeURIComponent(editor.homeDirectory)})) .success(function (data) { Widget.successHandler(data, simpleDirectoryName + " renamed to " + name) }) .error(Widget.errorHandler) } this.delete() }}) } else { var infoPopup = new Widget.InfoPopup({info: "Select directory!"}) } } // // edit // Widget.EditorHeader.editFile = function () { var directoryName = editor.homeDirectory || editor.directoryName if (isEmpty(directoryName)) { var infoPopup = new Widget.InfoPopup({info: "Select directory!"}) } else if (isEmpty(editor.fileName)) { var infoPopup = new Widget.InfoPopup({info: "Select file!"}) } else { var newSessionUrl = Widget.EditorHeader.newSessionUrl( property.editorUrl + property.editorEditFileUrl, {directoryName: encodeURIComponent(directoryName), fileName: encodeURIComponent(editor.fileName)}) window.open(newSessionUrl) } } // // save // Widget.EditorHeader.save = function () { if (!isEmpty(editor.fileName)) { var fileName = editor.fileName $.post(property.editorUrl + property.editorSaveUrl + "?f=" + encodeURIComponent(fileName), editor.getValue()) .success(function () { Widget.EditorHeader.saved(true) }) .error(Widget.errorHandler) } } Widget.EditorHeader.saved = function (isSaved) { if (isSaved) { $("#saveAction").html(property.editorSaved); } else { $("#saveAction").html(property.editorUnsaved); } }
{ "content_hash": "6ad4e0228818301398f93ed8d5a383bd", "timestamp": "", "source": "github", "line_count": 786, "max_line_length": 124, "avg_line_length": 31.24936386768448, "alnum_prop": 0.638303069782591, "repo_name": "cyberz-eu/octopus", "id": "f24a71bd94d49bb2334f8592837bc7e263cd6965", "size": "24562", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "extensions/editor/src/widget/EditorHeader.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "31009" }, { "name": "JavaScript", "bytes": "167720" }, { "name": "Lua", "bytes": "492943" }, { "name": "Shell", "bytes": "4530" } ], "symlink_target": "" }
* [Primary concepts](#primary-concepts) * [Additional user guides](#additional-user-guides) Getting started guides are in [getting-started-guides](getting-started-guides). There are example files and walkthroughs in the [examples](../examples) folder. If you're developing Kubernetes, docs are in the [devel](devel) folder. Design docs are in [design](design). ## Primary concepts * **Overview** ([overview.md](overview.md)): A brief overview of Kubernetes concepts. * **Nodes** ([node.md](node.md)): A node is a worker machine in Kubernetes. * **Pods** ([pods.md](pods.md)): A pod is a tightly-coupled group of containers with shared volumes. * **The Life of a Pod** ([pod-states.md](pod-states.md)): Covers the intersection of pod states, the PodStatus type, the life-cycle of a pod, events, restart policies, and replication controllers. * **Replication Controllers** ([replication-controller.md](replication-controller.md)): A replication controller ensures that a specified number of pod "replicas" are running at any one time. * **Services** ([services.md](services.md)): A Kubernetes service is an abstraction which defines a logical set of pods and a policy by which to access them. * **Volumes** ([volumes.md](volumes.md)): A Volume is a directory, possibly with some data in it, which is accessible to a Container. * **Labels** ([labels.md](labels.md)): Labels are key/value pairs that are attached to objects, such as pods. Labels can be used to organize and to select subsets of objects. * **Accessing the API** ([accessing_the_api.md](accessing_the_api.md)): Ports, IPs, proxies, and firewall rules. * **Kubernetes Web Interface** ([ux.md](ux.md)): Accessing the Kubernetes web user interface. * **Kubecfg Command Line Interface** ([cli.md](cli.md)): The `kubecfg` command line reference. * **Roadmap** ([roadmap.md](roadmap.md)): The set of supported use cases, features, docs, and patterns that are required before Kubernetes 1.0. * **Glossary** ([glossary.md](glossary.md)): Terms and concepts. ## Further reading * **Annotations** ([annotations.md](annotations.md)): Attaching arbitrary non-identifying metadata. * **API Conventions** ([api-conventions.md](api-conventions.md)): Defining the verbs and resources used in the Kubernetes API. * **Authentication Plugins** ([authentication.md](authentication.md)): The current and planned states of authentication tokens. * **Authorization Plugins** ([authorization.md](authorization.md)): Authorization applies to all HTTP requests on the main apiserver port. This doc explains the available authorization implementations. * **API Client Libraries** ([client-libraries.md](client-libraries.md)): A list of existing client libraries, both supported and user-contributed. * **Kubernetes Container Environment** ([container-environment.md](container-environment.md)): Describes the environment for Kubelet managed containers on a Kubernetes node. * **DNS Integration with SkyDNS** ([dns.md](dns.md)): Resolving a DNS name directly to a Kubernetes service. * **Identifiers** ([identifiers.md](identifiers.md)): Names and UIDs explained. * **Images** ([images.md](images.md)): Information about container images and private registries. * **Logging** ([logging.md](logging.md)): Pointers to logging info. * **Namespaces** ([namespaces.md](namespaces.md)): Namespaces help different projects, teams, or customers to share a kubernetes cluster. * **Networking** ([networking.md](networking.md)): Pod networking overview. * **OpenVSwitch GRE/VxLAN networking** ([ovs-networking.md](ovs-networking.md)): Using OpenVSwitch to set up networking between pods across Kubernetes nodes. * **The Kubernetes Resource Model** ([resources.md](resources.md)): Provides resource information such as size, type, and quantity to assist in assigning Kubernetes resources appropriately. * **Using Salt to configure Kubernetes** ([salt.md](salt.md)): The Kubernetes cluster can be configured using Salt.
{ "content_hash": "3189eda132c4d065521db0cc1b31d47e", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 94, "avg_line_length": 38.55238095238095, "alnum_prop": 0.7339426877470355, "repo_name": "rjnagal/kubernetes", "id": "88f2a224d6d63d4dbc12870afb89a41f4298b31f", "size": "4076", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3153" }, { "name": "Go", "bytes": "3536068" }, { "name": "Java", "bytes": "3258" }, { "name": "JavaScript", "bytes": "12056" }, { "name": "Makefile", "bytes": "6918" }, { "name": "PHP", "bytes": "1029" }, { "name": "Perl", "bytes": "84" }, { "name": "Python", "bytes": "8794" }, { "name": "Scheme", "bytes": "23274" }, { "name": "Shell", "bytes": "419148" } ], "symlink_target": "" }
package org.apache.kafka.common.utils; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import org.apache.kafka.common.KafkaException; public class Utils { public static String NL = System.getProperty("line.separator"); /** * Turn the given UTF8 byte array into a string * * @param bytes The byte array * @return The string */ public static String utf8(byte[] bytes) { try { return new String(bytes, "UTF8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("This shouldn't happen.", e); } } /** * Turn a string into a utf8 byte[] * * @param string The string * @return The byte[] */ public static byte[] utf8(String string) { try { return string.getBytes("UTF8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("This shouldn't happen.", e); } } /** * Read an unsigned integer from the current position in the buffer, incrementing the position by 4 bytes * * @param buffer The buffer to read from * @return The integer read, as a long to avoid signedness */ public static long readUnsignedInt(ByteBuffer buffer) { return buffer.getInt() & 0xffffffffL; } /** * Read an unsigned integer from the given position without modifying the buffers position * * @param buffer the buffer to read from * @param index the index from which to read the integer * @return The integer read, as a long to avoid signedness */ public static long readUnsignedInt(ByteBuffer buffer, int index) { return buffer.getInt(index) & 0xffffffffL; } /** * Write the given long value as a 4 byte unsigned integer. Overflow is ignored. * * @param buffer The buffer to write to * @param value The value to write */ public static void writetUnsignedInt(ByteBuffer buffer, long value) { buffer.putInt((int) (value & 0xffffffffL)); } /** * Write the given long value as a 4 byte unsigned integer. Overflow is ignored. * * @param buffer The buffer to write to * @param index The position in the buffer at which to begin writing * @param value The value to write */ public static void writeUnsignedInt(ByteBuffer buffer, int index, long value) { buffer.putInt(index, (int) (value & 0xffffffffL)); } /** * Get the absolute value of the given number. If the number is Int.MinValue return 0. This is different from * java.lang.Math.abs or scala.math.abs in that they return Int.MinValue (!). */ public static int abs(int n) { return n & 0x7fffffff; } /** * Get the length for UTF8-encoding a string without encoding it first * * @param s The string to calculate the length for * @return The length when serialized */ public static int utf8Length(CharSequence s) { int count = 0; for (int i = 0, len = s.length(); i < len; i++) { char ch = s.charAt(i); if (ch <= 0x7F) { count++; } else if (ch <= 0x7FF) { count += 2; } else if (Character.isHighSurrogate(ch)) { count += 4; ++i; } else { count += 3; } } return count; } /** * Read the given byte buffer into a byte array */ public static byte[] toArray(ByteBuffer buffer) { return toArray(buffer, 0, buffer.limit()); } /** * Read a byte array from the given offset and size in the buffer */ public static byte[] toArray(ByteBuffer buffer, int offset, int size) { byte[] dest = new byte[size]; if (buffer.hasArray()) { System.arraycopy(buffer.array(), buffer.arrayOffset() + offset, dest, 0, size); } else { int pos = buffer.position(); buffer.get(dest); buffer.position(pos); } return dest; } /** * Check that the parameter t is not null * * @param t The object to check * @return t if it isn't null * @throws NullPointerException if t is null. */ public static <T> T notNull(T t) { if (t == null) throw new NullPointerException(); else return t; } /** * Instantiate the class */ public static Object newInstance(Class<?> c) { try { return c.newInstance(); } catch (IllegalAccessException e) { throw new KafkaException("Could not instantiate class " + c.getName(), e); } catch (InstantiationException e) { throw new KafkaException("Could not instantiate class " + c.getName() + " Does it have a public no-argument constructor?", e); } } /** * Generates 32 bit murmur2 hash from byte array * @param data byte array to hash * @return 32 bit hash of the given array */ public static int murmur2(final byte[] data) { int length = data.length; int seed = 0x9747b28c; // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. final int m = 0x5bd1e995; final int r = 24; // Initialize the hash to a random value int h = seed ^ length; int length4 = length / 4; for (int i = 0; i < length4; i++) { final int i4 = i * 4; int k = (data[i4 + 0] & 0xff) + ((data[i4 + 1] & 0xff) << 8) + ((data[i4 + 2] & 0xff) << 16) + ((data[i4 + 3] & 0xff) << 24); k *= m; k ^= k >>> r; k *= m; h *= m; h ^= k; } // Handle the last few bytes of the input array switch (length % 4) { case 3: h ^= (data[(length & ~3) + 2] & 0xff) << 16; case 2: h ^= (data[(length & ~3) + 1] & 0xff) << 8; case 1: h ^= (data[length & ~3] & 0xff); h *= m; } h ^= h >>> 13; h *= m; h ^= h >>> 15; return h; } }
{ "content_hash": "d833c83fe4e29a97e678728c298cba5e", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 138, "avg_line_length": 30.248803827751196, "alnum_prop": 0.5476115153432458, "repo_name": "stealthly/kafka", "id": "50af60198a3f20933d0e8cf89c3b95d89ee73f35", "size": "7108", "binary": false, "copies": "2", "ref": "refs/heads/v0.8.2", "path": "clients/src/main/java/org/apache/kafka/common/utils/Utils.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "4a0c443e4f1fa2a343e63fd19cf8e41d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "179e27821ec52f1be40520581a7cfef0ba88e57d", "size": "201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Elymus/Elymus bungeanus/ Syn. Pseudoroegneria geniculata nevskii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
pkg_prereqs=('apt-get') pkg_extract_path=~/ pkg_description='mc - best cli file manager ever' function install_package() { b.system.pretend_super sudo apt-get install -y mc }
{ "content_hash": "7e85605e1b80bdf09ac233dc47fb65c1", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 49, "avg_line_length": 23, "alnum_prop": 0.7010869565217391, "repo_name": "smileart/omg", "id": "342e628216c8be9c3369beb8f39c2fc0a97a1ff5", "size": "184", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "packages/debian/mc/mc.sh", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "1760" }, { "name": "Shell", "bytes": "62749" }, { "name": "Vim script", "bytes": "14435" } ], "symlink_target": "" }
package config import ( "fmt" "io/ioutil" "strings" "github.com/rebuy-de/aws-nuke/v2/pkg/types" log "github.com/sirupsen/logrus" "gopkg.in/yaml.v2" ) type ResourceTypes struct { Targets types.Collection `yaml:"targets"` Excludes types.Collection `yaml:"excludes"` CloudControl types.Collection `yaml:"cloud-control"` } type Account struct { Filters Filters `yaml:"filters"` ResourceTypes ResourceTypes `yaml:"resource-types"` Presets []string `yaml:"presets"` } type Nuke struct { // Deprecated: Use AccountBlocklist instead. AccountBlacklist []string `yaml:"account-blacklist"` AccountBlocklist []string `yaml:"account-blocklist"` Regions []string `yaml:"regions"` Accounts map[string]Account `yaml:"accounts"` ResourceTypes ResourceTypes `yaml:"resource-types"` Presets map[string]PresetDefinitions `yaml:"presets"` FeatureFlags FeatureFlags `yaml:"feature-flags"` CustomEndpoints CustomEndpoints `yaml:"endpoints"` } type FeatureFlags struct { DisableDeletionProtection DisableDeletionProtection `yaml:"disable-deletion-protection"` ForceDeleteLightsailAddOns bool `yaml:"force-delete-lightsail-addons"` } type DisableDeletionProtection struct { RDSInstance bool `yaml:"RDSInstance"` EC2Instance bool `yaml:"EC2Instance"` CloudformationStack bool `yaml:"CloudformationStack"` ELBv2 bool `yaml:"ELBv2"` QLDBLedger bool `yaml:"QLDBLedger"` } type PresetDefinitions struct { Filters Filters `yaml:"filters"` } type CustomService struct { Service string `yaml:"service"` URL string `yaml:"url"` TLSInsecureSkipVerify bool `yaml:"tls_insecure_skip_verify"` } type CustomServices []*CustomService type CustomRegion struct { Region string `yaml:"region"` Services CustomServices `yaml:"services"` TLSInsecureSkipVerify bool `yaml:"tls_insecure_skip_verify"` } type CustomEndpoints []*CustomRegion func Load(path string) (*Nuke, error) { var err error raw, err := ioutil.ReadFile(path) if err != nil { return nil, err } config := new(Nuke) err = yaml.UnmarshalStrict(raw, config) if err != nil { return nil, err } if err := config.resolveDeprecations(); err != nil { return nil, err } return config, nil } func (c *Nuke) ResolveBlocklist() []string { if c.AccountBlocklist != nil { return c.AccountBlocklist } log.Warn("deprecated configuration key 'account-blacklist' - please use 'account-blocklist' instead") return c.AccountBlacklist } func (c *Nuke) HasBlocklist() bool { var blocklist = c.ResolveBlocklist() return blocklist != nil && len(blocklist) > 0 } func (c *Nuke) InBlocklist(searchID string) bool { for _, blocklistID := range c.ResolveBlocklist() { if blocklistID == searchID { return true } } return false } func (c *Nuke) ValidateAccount(accountID string, aliases []string) error { if !c.HasBlocklist() { return fmt.Errorf("The config file contains an empty blocklist. " + "For safety reasons you need to specify at least one account ID. " + "This should be your production account.") } if c.InBlocklist(accountID) { return fmt.Errorf("You are trying to nuke the account with the ID %s, "+ "but it is blocklisted. Aborting.", accountID) } if len(aliases) == 0 { return fmt.Errorf("The specified account doesn't have an alias. " + "For safety reasons you need to specify an account alias. " + "Your production account should contain the term 'prod'.") } for _, alias := range aliases { if strings.Contains(strings.ToLower(alias), "prod") { return fmt.Errorf("You are trying to nuke an account with the alias '%s', "+ "but it has the substring 'prod' in it. Aborting.", alias) } } if _, ok := c.Accounts[accountID]; !ok { return fmt.Errorf("Your account ID '%s' isn't listed in the config. "+ "Aborting.", accountID) } return nil } func (c *Nuke) Filters(accountID string) (Filters, error) { account := c.Accounts[accountID] filters := account.Filters if filters == nil { filters = Filters{} } if account.Presets == nil { return filters, nil } for _, presetName := range account.Presets { notFound := fmt.Errorf("Could not find filter preset '%s'", presetName) if c.Presets == nil { return nil, notFound } preset, ok := c.Presets[presetName] if !ok { return nil, notFound } filters.Merge(preset.Filters) } return filters, nil } func (c *Nuke) resolveDeprecations() error { deprecations := map[string]string{ "EC2DhcpOptions": "EC2DHCPOptions", "EC2InternetGatewayAttachement": "EC2InternetGatewayAttachment", "EC2NatGateway": "EC2NATGateway", "EC2Vpc": "EC2VPC", "EC2VpcEndpoint": "EC2VPCEndpoint", "EC2VpnConnection": "EC2VPNConnection", "EC2VpnGateway": "EC2VPNGateway", "EC2VpnGatewayAttachement": "EC2VPNGatewayAttachment", "ECRrepository": "ECRRepository", "IamGroup": "IAMGroup", "IamGroupPolicyAttachement": "IAMGroupPolicyAttachment", "IamInstanceProfile": "IAMInstanceProfile", "IamInstanceProfileRole": "IAMInstanceProfileRole", "IamPolicy": "IAMPolicy", "IamRole": "IAMRole", "IamRolePolicyAttachement": "IAMRolePolicyAttachment", "IamServerCertificate": "IAMServerCertificate", "IamUser": "IAMUser", "IamUserAccessKeys": "IAMUserAccessKey", "IamUserGroupAttachement": "IAMUserGroupAttachment", "IamUserPolicyAttachement": "IAMUserPolicyAttachment", "RDSCluster": "RDSDBCluster", } for _, a := range c.Accounts { for resourceType, resources := range a.Filters { replacement, ok := deprecations[resourceType] if !ok { continue } log.Warnf("deprecated resource type '%s' - converting to '%s'\n", resourceType, replacement) if _, ok := a.Filters[replacement]; ok { return fmt.Errorf("using deprecated resource type and replacement: '%s','%s'", resourceType, replacement) } a.Filters[replacement] = resources delete(a.Filters, resourceType) } } return nil } // GetRegion returns the custom region or nil when no such custom endpoints are defined for this region func (endpoints CustomEndpoints) GetRegion(region string) *CustomRegion { for _, r := range endpoints { if r.Region == region { if r.TLSInsecureSkipVerify { for _, s := range r.Services { s.TLSInsecureSkipVerify = r.TLSInsecureSkipVerify } } return r } } return nil } // GetService returns the custom region or nil when no such custom endpoints are defined for this region func (services CustomServices) GetService(serviceType string) *CustomService { for _, s := range services { if serviceType == s.Service { return s } } return nil } func (endpoints CustomEndpoints) GetURL(region, serviceType string) string { r := endpoints.GetRegion(region) if r == nil { return "" } s := r.Services.GetService(serviceType) if s == nil { return "" } return s.URL }
{ "content_hash": "f22b794da22ce3a87d785e932c073ed4", "timestamp": "", "source": "github", "line_count": 258, "max_line_length": 109, "avg_line_length": 28.546511627906977, "alnum_prop": 0.656754921928038, "repo_name": "rebuy-de/aws-nuke", "id": "7c8d7b32ae219864298a053a18f6ef8f025c8868", "size": "7365", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pkg/config/config.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "539" }, { "name": "Go", "bytes": "688430" }, { "name": "Makefile", "bytes": "2365" }, { "name": "Shell", "bytes": "230" } ], "symlink_target": "" }
package org.apache.dubbo.common.utils; import org.apache.log4j.Level; import org.junit.jupiter.api.Test; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class LogTest { @Test public void testLogName() throws Exception { Log log = new Log(); log.setLogName("log-name"); assertThat(log.getLogName(), equalTo("log-name")); } @Test public void testLogLevel() throws Exception { Log log = new Log(); log.setLogLevel(Level.ALL); assertThat(log.getLogLevel(), is(Level.ALL)); } @Test public void testLogMessage() throws Exception { Log log = new Log(); log.setLogMessage("log-message"); assertThat(log.getLogMessage(), equalTo("log-message")); } @Test public void testLogThread() throws Exception { Log log = new Log(); log.setLogThread("log-thread"); assertThat(log.getLogThread(), equalTo("log-thread")); } }
{ "content_hash": "e9b23d78f113ce2c471848ad8e7e008f", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 64, "avg_line_length": 25.70731707317073, "alnum_prop": 0.6461100569259962, "repo_name": "aglne/dubbo", "id": "203cadb547f466719d8aed2ceb2c059cc143e3f1", "size": "1856", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3447" }, { "name": "CSS", "bytes": "18582" }, { "name": "Java", "bytes": "5301948" }, { "name": "JavaScript", "bytes": "63148" }, { "name": "Lex", "bytes": "2077" }, { "name": "Shell", "bytes": "7011" }, { "name": "Thrift", "bytes": "668" } ], "symlink_target": "" }
package com.amazonaws.services.ec2.model.transform; import java.util.Map; import java.util.Map.Entry; import javax.xml.stream.events.XMLEvent; import com.amazonaws.services.ec2.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.MapEntry; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * Instance State Change StAX Unmarshaller */ public class InstanceStateChangeStaxUnmarshaller implements Unmarshaller<InstanceStateChange, StaxUnmarshallerContext> { public InstanceStateChange unmarshall(StaxUnmarshallerContext context) throws Exception { InstanceStateChange instanceStateChange = new InstanceStateChange(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return instanceStateChange; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("instanceId", targetDepth)) { instanceStateChange.setInstanceId(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("currentState", targetDepth)) { instanceStateChange.setCurrentState(InstanceStateStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("previousState", targetDepth)) { instanceStateChange.setPreviousState(InstanceStateStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return instanceStateChange; } } } } private static InstanceStateChangeStaxUnmarshaller instance; public static InstanceStateChangeStaxUnmarshaller getInstance() { if (instance == null) instance = new InstanceStateChangeStaxUnmarshaller(); return instance; } }
{ "content_hash": "fb4d85b7d71d28ed4e067b12b41d914d", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 122, "avg_line_length": 37.095238095238095, "alnum_prop": 0.6640992725716731, "repo_name": "apetresc/aws-sdk-for-java-on-gae", "id": "cc402d3c97da6713dbd0ca9a0e7abf6b8313d1e4", "size": "2924", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/amazonaws/services/ec2/model/transform/InstanceStateChangeStaxUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "10870469" } ], "symlink_target": "" }
package org.apache.ignite.internal.processors.cache.transactions; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.UUID; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.cache.CacheObject; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.GridCacheEntryEx; import org.apache.ignite.internal.processors.cache.GridCacheEntryRemovedException; import org.apache.ignite.internal.processors.cache.GridCacheFilterFailedException; import org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate; import org.apache.ignite.internal.processors.cache.KeyCacheObject; import org.apache.ignite.internal.processors.cache.version.GridCacheVersion; import org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException; import org.apache.ignite.internal.util.lang.GridTuple; import org.apache.ignite.lang.IgniteUuid; import org.apache.ignite.transactions.TransactionConcurrency; import org.apache.ignite.transactions.TransactionIsolation; import org.apache.ignite.transactions.TransactionState; import org.jetbrains.annotations.Nullable; /** * Transaction managed by cache ({@code 'Ex'} stands for external). */ public interface IgniteInternalTx { /** * */ @SuppressWarnings("PublicInnerClass") public enum FinalizationStatus { /** Transaction was not finalized yet. */ NONE, /** Transaction is being finalized by user. */ USER_FINISH, /** Transaction is being finalized by recovery procedure. */ RECOVERY_FINISH } /** * @return {@code True} if transaction started on the node initiated cache operation. */ public boolean localResult(); /** * Gets unique identifier for this transaction. * * @return Transaction UID. */ public IgniteUuid xid(); /** * ID of the node on which this transaction started. * * @return Originating node ID. */ public UUID nodeId(); /** * ID of the thread in which this transaction started. * * @return Thread ID. */ public long threadId(); /** * Start time of this transaction. * * @return Start time of this transaction on this node. */ public long startTime(); /** * Cache transaction isolation level. * * @return Isolation level. */ public TransactionIsolation isolation(); /** * Cache transaction concurrency mode. * * @return Concurrency mode. */ public TransactionConcurrency concurrency(); /** * Flag indicating whether transaction was started automatically by the * system or not. System will start transactions implicitly whenever * any cache {@code put(..)} or {@code remove(..)} operation is invoked * outside of transaction. * * @return {@code True} if transaction was started implicitly. */ public boolean implicit(); /** * Get invalidation flag for this transaction. If set to {@code true}, then * remote values will be {@code invalidated} (set to {@code null}) instead * of updated. * <p> * Invalidation messages don't carry new values, so they are a lot lighter * than update messages. However, when a value is accessed on a node after * it's been invalidated, it must be loaded from persistent store. * * @return Invalidation flag. */ public boolean isInvalidate(); /** * Gets current transaction state value. * * @return Current transaction state. */ public TransactionState state(); /** * Gets timeout value in milliseconds for this transaction. If transaction times * out prior to it's completion, {@link org.apache.ignite.internal.transactions.IgniteTxTimeoutCheckedException} will be thrown. * * @return Transaction timeout value. */ public long timeout(); /** * Sets transaction timeout value. This value can be set only before a first operation * on transaction has been performed. * * @param timeout Transaction timeout value. * @return Previous timeout. */ public long timeout(long timeout); /** * Changes transaction state from COMMITTING to MARKED_ROLLBACK. * Must be called only from thread committing transaction. */ public void errorWhenCommitting(); /** * Modify the transaction associated with the current thread such that the * only possible outcome of the transaction is to roll back the * transaction. * * @return {@code True} if rollback-only flag was set as a result of this operation, * {@code false} if it was already set prior to this call or could not be set * because transaction is already finishing up committing or rolling back. */ public boolean setRollbackOnly(); /** * If transaction was marked as rollback-only. * * @return {@code True} if transaction can only be rolled back. */ public boolean isRollbackOnly(); /** * Removes metadata by key. * * @param key Key of the metadata to remove. * @param <T> Type of the value. * @return Value of removed metadata or {@code null}. */ @Nullable public <T> T removeMeta(int key); /** * Gets metadata by key. * * @param key Metadata key. * @param <T> Type of the value. * @return Metadata value or {@code null}. */ @Nullable public <T> T meta(int key); /** * Adds a new metadata. * * @param key Metadata key. * @param val Metadata value. * @param <T> Type of the value. * @return Metadata previously associated with given name, or * {@code null} if there was none. */ @Nullable public <T> T addMeta(int key, T val); /** * @return Size of the transaction. */ public int size(); /** * @return {@code True} if transaction is allowed to use store. */ public boolean storeEnabled(); /** * @return {@code True} if transaction is allowed to use store and transactions spans one or more caches with * store enabled. */ public boolean storeWriteThrough(); /** * Checks if this is system cache transaction. System transactions are isolated from user transactions * because some of the public API methods may be invoked inside user transactions and internally start * system cache transactions. * * @return {@code True} if transaction is started for system cache. */ public boolean system(); /** * @return Pool where message for the given transaction must be processed. */ public byte ioPolicy(); /** * @return Last recorded topology version. */ public AffinityTopologyVersion topologyVersion(); /** * @return Topology version snapshot. */ public AffinityTopologyVersion topologyVersionSnapshot(); /** * @return Flag indicating whether transaction is implicit with only one key. */ public boolean implicitSingle(); /** * @return Transaction state. */ public IgniteTxState txState(); /** * @return {@code true} or {@code false} if the deployment is enabled or disabled for all active caches involved * in this transaction. */ public boolean activeCachesDeploymentEnabled(); /** * Attempts to set topology version and returns the current value. * If topology version was previously set, then it's value will * be returned (but not updated). * * @param topVer Topology version. * @return Recorded topology version. */ public AffinityTopologyVersion topologyVersion(AffinityTopologyVersion topVer); /** * @return {@code True} if transaction is empty. */ public boolean empty(); /** * @param status Finalization status to set. * @return {@code True} if could mark was set. */ public boolean markFinalizing(FinalizationStatus status); /** * @param cacheCtx Cache context. * @param part Invalid partition. */ public void addInvalidPartition(GridCacheContext<?, ?> cacheCtx, int part); /** * @return Invalid partitions. */ public Map<Integer, Set<Integer>> invalidPartitions(); /** * Gets owned version for near remote transaction. * * @param key Key to get version for. * @return Owned version, if any. */ @Nullable public GridCacheVersion ownedVersion(IgniteTxKey key); /** * Gets ID of additional node involved. For example, in DHT case, other node is * near node ID. * * @return Parent node IDs. */ @Nullable public UUID otherNodeId(); /** * @return Event node ID. */ public UUID eventNodeId(); /** * Gets node ID which directly started this transaction. In case of DHT local transaction it will be * near node ID, in case of DHT remote transaction it will be primary node ID. * * @return Originating node ID. */ public UUID originatingNodeId(); /** * @return Master node IDs. */ public Collection<UUID> masterNodeIds(); /** * @return Near transaction ID. */ @Nullable public GridCacheVersion nearXidVersion(); /** * @return Transaction nodes mapping (primary node -> related backup nodes). */ @Nullable public Map<UUID, Collection<UUID>> transactionNodes(); /** * @param entry Entry to check. * @return {@code True} if lock is owned. * @throws GridCacheEntryRemovedException If entry has been removed. */ public boolean ownsLock(GridCacheEntryEx entry) throws GridCacheEntryRemovedException; /** * @param entry Entry to check. * @return {@code True} if lock is owned. */ public boolean ownsLockUnsafe(GridCacheEntryEx entry); /** * @return {@code True} if near transaction. */ public boolean near(); /** * @return {@code True} if DHT transaction. */ public boolean dht(); /** * @return {@code True} if dht colocated transaction. */ public boolean colocated(); /** * @return {@code True} if transaction is local, {@code false} if it's remote. */ public boolean local(); /** * @return Subject ID initiated this transaction. */ public UUID subjectId(); /** * Task name hash in case if transaction was initiated within task execution. * * @return Task name hash. */ public int taskNameHash(); /** * @return {@code True} if transaction is user transaction, which means: * <ul> * <li>Explicit</li> * <li>Local</li> * <li>Not DHT</li> * </ul> */ public boolean user(); /** * @param key Key to check. * @return {@code True} if key is present. */ public boolean hasWriteKey(IgniteTxKey key); /** * @return Read set. */ public Set<IgniteTxKey> readSet(); /** * @return Write set. */ public Set<IgniteTxKey> writeSet(); /** * @return All transaction entries. */ public Collection<IgniteTxEntry> allEntries(); /** * @return Write entries. */ public Collection<IgniteTxEntry> writeEntries(); /** * @return Read entries. */ public Collection<IgniteTxEntry> readEntries(); /** * @return Transaction write map. */ public Map<IgniteTxKey, IgniteTxEntry> writeMap(); /** * @return Transaction read map. */ public Map<IgniteTxKey, IgniteTxEntry> readMap(); /** * Gets a list of entries that needs to be locked on the next step of prepare stage of * optimistic transaction. * * @return List of tx entries for optimistic locking. */ public Collection<IgniteTxEntry> optimisticLockEntries(); /** * Seals transaction for updates. */ public void seal(); /** * @param key Key for the entry. * @return Entry for the key (either from write set or read set). */ @Nullable public IgniteTxEntry entry(IgniteTxKey key); /** * @param ctx Cache context. * @param failFast Fail-fast flag. * @param key Key to look up. * @return Current value for the key within transaction. * @throws GridCacheFilterFailedException If filter failed and failFast is {@code true}. */ @Nullable public GridTuple<CacheObject> peek( GridCacheContext ctx, boolean failFast, KeyCacheObject key) throws GridCacheFilterFailedException; /** * @return Transaction version. */ public GridCacheVersion xidVersion(); /** * @return Version created at commit time. */ public GridCacheVersion commitVersion(); /** * @param commitVer Commit version. */ public void commitVersion(GridCacheVersion commitVer); /** * @return Future. */ @Nullable public IgniteInternalFuture<?> salvageTx(); /** * @param endVer End version (a.k.a. <tt>'tnc'</tt> or <tt>'transaction number counter'</tt>) * assigned to this transaction at the end of write phase. */ public void endVersion(GridCacheVersion endVer); /** * @return Transaction write version. For all transactions except DHT transactions, will be equal to * {@link #xidVersion()}. */ public GridCacheVersion writeVersion(); /** * Sets write version. * * @param ver Write version. */ public void writeVersion(GridCacheVersion ver); /** * @return Future for transaction completion. */ public IgniteInternalFuture<IgniteInternalTx> finishFuture(); /** * @return Future for transaction prepare if prepare is in progress. */ @Nullable public IgniteInternalFuture<?> currentPrepareFuture(); /** * @param state Transaction state. * @return {@code True} if transition was valid, {@code false} otherwise. */ public boolean state(TransactionState state); /** * @param invalidate Invalidate flag. */ public void invalidate(boolean invalidate); /** * @param sysInvalidate System invalidate flag. */ public void systemInvalidate(boolean sysInvalidate); /** * @return System invalidate flag. */ public boolean isSystemInvalidate(); /** * Asynchronously rollback this transaction. * * @return Rollback future. */ public IgniteInternalFuture<IgniteInternalTx> rollbackAsync(); /** * Asynchronously commits this transaction by initiating {@code two-phase-commit} process. * * @return Future for commit operation. */ public IgniteInternalFuture<IgniteInternalTx> commitAsync(); /** * Callback invoked whenever there is a lock that has been acquired * by this transaction for any of the participating entries. * * @param entry Cache entry. * @param owner Lock candidate that won ownership of the lock. * @return {@code True} if transaction cared about notification. */ public boolean onOwnerChanged(GridCacheEntryEx entry, GridCacheMvccCandidate owner); /** * @return {@code True} if transaction timed out. */ public boolean timedOut(); /** * @return {@code True} if transaction had completed successfully or unsuccessfully. */ public boolean done(); /** * @return {@code True} for OPTIMISTIC transactions. */ public boolean optimistic(); /** * @return {@code True} for PESSIMISTIC transactions. */ public boolean pessimistic(); /** * @return {@code True} if read-committed. */ public boolean readCommitted(); /** * @return {@code True} if repeatable-read. */ public boolean repeatableRead(); /** * @return {@code True} if serializable. */ public boolean serializable(); /** * Gets allowed remaining time for this transaction. * * @return Remaining time. * @throws IgniteTxTimeoutCheckedException If transaction timed out. */ public long remainingTime() throws IgniteTxTimeoutCheckedException; /** * @return Alternate transaction versions. */ public Collection<GridCacheVersion> alternateVersions(); /** * @return {@code True} if transaction needs completed versions for processing. */ public boolean needsCompletedVersions(); /** * @param base Base for committed versions. * @param committed Committed transactions relative to base. * @param rolledback Rolled back transactions relative to base. */ public void completedVersions(GridCacheVersion base, Collection<GridCacheVersion> committed, Collection<GridCacheVersion> rolledback); /** * @return {@code True} if transaction has at least one internal entry. */ public boolean internal(); /** * @return {@code True} if transaction is a one-phase-commit transaction. */ public boolean onePhaseCommit(); /** * @param e Commit error. */ public void commitError(Throwable e); }
{ "content_hash": "2deb3e6ce916c3e825c8b59c14144ff3", "timestamp": "", "source": "github", "line_count": 622, "max_line_length": 132, "avg_line_length": 27.988745980707396, "alnum_prop": 0.6428858636337527, "repo_name": "mcherkasov/ignite", "id": "75980030238bf24e5a8f08b0f97bbf650a50d664", "size": "18211", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteInternalTx.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "44742" }, { "name": "C", "bytes": "5286" }, { "name": "C#", "bytes": "4794452" }, { "name": "C++", "bytes": "2546848" }, { "name": "CSS", "bytes": "153258" }, { "name": "Groovy", "bytes": "15092" }, { "name": "HTML", "bytes": "509773" }, { "name": "Java", "bytes": "28612113" }, { "name": "JavaScript", "bytes": "1121079" }, { "name": "M4", "bytes": "12424" }, { "name": "Makefile", "bytes": "103933" }, { "name": "Nginx", "bytes": "3468" }, { "name": "PHP", "bytes": "11079" }, { "name": "PowerShell", "bytes": "13588" }, { "name": "Scala", "bytes": "681299" }, { "name": "Shell", "bytes": "594614" }, { "name": "Smalltalk", "bytes": "1911" } ], "symlink_target": "" }
<?php /** PHPExcel */ require_once 'PHPExcel.php'; /** PHPExcel_Cell */ require_once 'PHPExcel/Cell.php'; /** PHPExcel_Worksheet_RowDimension */ require_once 'PHPExcel/Worksheet/RowDimension.php'; /** PHPExcel_Worksheet_ColumnDimension */ require_once 'PHPExcel/Worksheet/ColumnDimension.php'; /** PHPExcel_Worksheet_PageSetup */ require_once 'PHPExcel/Worksheet/PageSetup.php'; /** PHPExcel_Worksheet_PageMargins */ require_once 'PHPExcel/Worksheet/PageMargins.php'; /** PHPExcel_Worksheet_HeaderFooter */ require_once 'PHPExcel/Worksheet/HeaderFooter.php'; /** PHPExcel_Worksheet_Drawing */ require_once 'PHPExcel/Worksheet/Drawing.php'; /** PHPExcel_Worksheet_Protection */ require_once 'PHPExcel/Worksheet/Protection.php'; /** PHPExcel_Style */ require_once 'PHPExcel/Style.php'; /** PHPExcel_Style_Fill */ require_once 'PHPExcel/Style/Fill.php'; /** PHPExcel_IComparable */ require_once 'PHPExcel/IComparable.php'; /** PHPExcel_Shared_Font */ require_once 'PHPExcel/Shared/Font.php'; /** PHPExcel_Shared_PasswordHasher */ require_once 'PHPExcel/Shared/PasswordHasher.php'; /** PHPExcel_ReferenceHelper */ require_once 'PHPExcel/ReferenceHelper.php'; /** * PHPExcel_Worksheet * * @category PHPExcel * @package PHPExcel * @copyright Copyright (c) 2006 - 2007 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_Worksheet implements PHPExcel_IComparable { /* Break types */ const BREAK_NONE = 0; const BREAK_ROW = 1; const BREAK_COLUMN = 2; /** * Parent spreadsheet * * @var PHPExcel */ private $_parent; /** * Collection of cells * * @var PHPExcel_Cell[] */ private $_cellCollection = array(); /** * Collection of row dimensions * * @var PHPExcel_Worksheet_RowDimension[] */ private $_rowDimensions = array(); /** * Collection of column dimensions * * @var PHPExcel_Worksheet_ColumnDimension[] */ private $_columnDimensions = array(); /** * Collection of drawings * * @var PHPExcel_Worksheet_Drawing[] */ private $_drawingCollection = null; /** * Worksheet title * * @var string */ private $_title; /** * Page setup * * @var PHPExcel_Worksheet_PageSetup */ private $_pageSetup; /** * Page margins * * @var PHPExcel_Worksheet_PageMargins */ private $_pageMargins; /** * Page header/footer * * @var PHPExcel_Worksheet_HeaderFooter */ private $_headerFooter; /** * Protection * * @var PHPExcel_Worksheet_Protection */ private $_protection; /** * Collection of styles * * @var PHPExcel_Style[] */ private $_styles = array(); /** * Is the current cell collection sorted already? * * @var boolean */ private $_cellCollectionIsSorted = false; /** * Collection of breaks * * @var array */ private $_breaks = array(); /** * Collection of merged cell ranges * * @var array */ private $_mergeCells = array(); /** * Collection of protected cell ranges * * @var array */ private $_protectedCells = array(); /** * Autofilter Range * * @var string */ private $_autoFilter = ''; /** * Freeze pane * * @var string */ private $_freezePane = ''; /** * Create a new worksheet * * @param PHPExcel $pParent * @param string $pTitle */ public function __construct($pParent = null, $pTitle = 'Worksheet') { // Set parent and title if (!is_null($pParent) && $pParent instanceof PHPExcel) { $this->_parent = $pParent; $this->setTitle($pTitle); } else { throw new Exception("Invalid PHPExcel object given."); } // Set page setup $this->_pageSetup = new PHPExcel_Worksheet_PageSetup(); // Set page margins $this->_pageMargins = new PHPExcel_Worksheet_PageMargins(); // Set page header/footer $this->_headerFooter = new PHPExcel_Worksheet_HeaderFooter(); // Create a default style and a default gray125 style $this->_styles['default'] = new PHPExcel_Style(); $this->_styles['gray125'] = new PHPExcel_Style(); $this->_styles['gray125']->getFill()->setFillType(PHPExcel_Style_Fill::FILL_PATTERN_GRAY125); // Drawing collection $this->_drawingCollection = new ArrayObject(); // Protection $this->_protection = new PHPExcel_Worksheet_Protection(); } /** * Get collection of cells * * @return PHPExcel_Cell[] */ public function getCellCollection() { // Re-order cell collection? if (!$this->_cellCollectionIsSorted) { uasort($this->_cellCollection, array('PHPExcel_Cell', 'compareCells')); } return $this->_cellCollection; } /** * Get collection of row dimensions * * @return PHPExcel_Worksheet_RowDimension[] */ public function getRowDimensions() { return $this->_rowDimensions; } /** * Get collection of column dimensions * * @return PHPExcel_Worksheet_ColumnDimension[] */ public function getColumnDimensions() { return $this->_columnDimensions; } /** * Get collection of drawings * * @return PHPExcel_Worksheet_Drawing[] */ public function getDrawingCollection() { return $this->_drawingCollection; } /** * Calculate worksheet dimension * * @return string String containing the dimension of this worksheet */ public function calculateWorksheetDimension() { // Return return 'A1' . ':' . $this->getHighestColumn() . $this->getHighestRow(); } /** * Calculate widths for auto-size columns */ public function calculateColumnWidths() { $autoSizes = array(); foreach ($this->getColumnDimensions() as $colDimension) { if ($colDimension->getAutoSize()) { $autoSizes[$colDimension->getColumnIndex()] = -1; } } foreach ($this->getCellCollection() as $cell) { if (isset($autoSizes[$cell->getColumn()])) { $autoSizes[$cell->getColumn()] = max( $autoSizes[$cell->getColumn()], PHPExcel_Shared_Font::calculateColumnWidth( $this->getStyle($cell->getCoordinate())->getFont()->getSize(), false, $cell->getCalculatedValue() ) ); } } foreach ($autoSizes as $columnIndex => $width) { $this->getColumnDimension($columnIndex)->setWidth($width); } } /** * Get parent * * @return PHPExcel */ public function getParent() { return $this->_parent; } /** * Get title * * @return string */ public function getTitle() { return $this->_title; } /** * Set title * * @param string $pValue String containing the dimension of this worksheet */ public function setTitle($pValue = 'Worksheet') { // Loop trough all sheets in parent PHPExcel and verify unique names $titleCount = 0; $aNames = $this->getParent()->getSheetNames(); foreach ($aNames as $strName) { if ($strName == $pValue || substr($strName, 0, strrpos($strName, ' ')) == $pValue) { $titleCount++; } } // Eventually, add a number to the sheet name if ($titleCount > 0) { $this->setTitle($pValue . ' ' . $titleCount); return; } // Set title $this->_title = $pValue; } /** * Get page setup * * @return PHPExcel_Worksheet_PageSetup */ public function getPageSetup() { return $this->_pageSetup; } /** * Set page setup * * @param PHPExcel_Worksheet_PageSetup $pValue */ public function setPageSetup($pValue) { if ($pValue instanceof PHPExcel_Worksheet_PageSetup) { $this->_pageSetup = $pValue; } else { throw new Exception("Invalid PHPExcel_Worksheet_PageSetup object passed."); } } /** * Get page margins * * @return PHPExcel_Worksheet_PageMargins */ public function getPageMargins() { return $this->_pageMargins; } /** * Set page margins * * @param PHPExcel_Worksheet_PageMargins $pValue */ public function setPageMargins($pValue) { if ($pValue instanceof PHPExcel_Worksheet_PageMargins) { $this->_pageMargins = $pValue; } else { throw new Exception("Invalid PHPExcel_Worksheet_PageMargins object passed."); } } /** * Get page header/footer * * @return PHPExcel_Worksheet_HeaderFooter */ public function getHeaderFooter() { return $this->_headerFooter; } /** * Set page header/footer * * @param PHPExcel_Worksheet_HeaderFooter $pValue */ public function setHeaderFooter($pValue) { if ($pValue instanceof PHPExcel_Worksheet_HeaderFooter) { $this->_headerFooter = $pValue; } else { throw new Exception("Invalid PHPExcel_Worksheet_HeaderFooter object passed."); } } /** * Get Protection * * @return PHPExcel_Worksheet_Protection */ public function getProtection() { return $this->_protection; } /** * Set Protection * * @param PHPExcel_Worksheet_Protection $pValue */ public function setProtection($pValue) { if ($pValue instanceof PHPExcel_Worksheet_Protection) { $this->_protection = $pValue; } else { throw new Exception("Invalid PHPExcel_Worksheet_Protection object passed."); } } /** * Get highest worksheet column * * @return string Highest column name */ public function getHighestColumn() { // Highest column $highestColumn = 'A'; // Loop trough cells foreach ($this->_cellCollection as $cell) { if (PHPExcel_Cell::columnIndexFromString($highestColumn) < PHPExcel_Cell::columnIndexFromString($cell->getColumn())) { $highestColumn = $cell->getColumn(); } } // Return return $highestColumn; } /** * Get highest worksheet row * * @return int Highest row number */ public function getHighestRow() { // Highest row $highestRow = 1; // Loop trough cells foreach ($this->_cellCollection as $cell) { if ($cell->getRow() > $highestRow) { $highestRow = $cell->getRow(); } } // Return return $highestRow; } /** * Set a cell value * * @param string $pCoordinate Coordinate of the cell * @param mixed $pValue Value of the cell */ public function setCellValue($pCoordinate = 'A1', $pValue = null) { // Uppercase coordinate $pCoordinate = strtoupper($pCoordinate); // Set value $this->getCell($pCoordinate)->setValue($pValue, true); } /** * Set a cell value by using numeric cell coordinates * * @param string $pColumn Numeric column coordinate of the cell * @param string $pRow Numeric row coordinate of the cell * @param mixed $pValue Value of the cell */ public function setCellValueByColumnAndRow($pColumn = 0, $pRow = 0, $pValue = null) { $this->setCellValue(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow, $pValue); } /** * Get cell at a specific coordinate * * @param string $pCoordinate Coordinate of the cell * @throws Exception * @return PHPExcel_Cell Cell that was found */ public function getCell($pCoordinate = 'A1') { // Uppercase coordinate $pCoordinate = strtoupper($pCoordinate); if (eregi(':', $pCoordinate)) { throw new Exception('Cell coordinate can not be a range of cells.'); } else if (eregi('\$', $pCoordinate)) { throw new Exception('Cell coordinate must not be absolute.'); } else { // Coordinates $aCoordinates = PHPExcel_Cell::coordinateFromString($pCoordinate); // Cell exists? if (!isset($this->_cellCollection[ strtoupper($pCoordinate) ])) { $this->_cellCollection[ strtoupper($pCoordinate) ] = new PHPExcel_Cell($aCoordinates[0], $aCoordinates[1], null, null, $this); $this->_cellCollectionIsSorted = false; } return $this->_cellCollection[ strtoupper($pCoordinate) ]; } } /** * Get cell at a specific coordinate by using numeric cell coordinates * * @param string $pColumn Numeric column coordinate of the cell * @param string $pRow Numeric row coordinate of the cell * @return PHPExcel_Cell Cell that was found */ public function getCellByColumnAndRow($pColumn = 0, $pRow = 0) { return $this->getCell(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); } /** * Get row dimension at a specific row * * @param int $pRow Numeric index of the row * @return PHPExcel_Worksheet_RowDimension */ public function getRowDimension($pRow = 0) { // Found $found = null; // Loop trough rows foreach ($this->_rowDimensions as $row) { if ($row->getRowIndex() == $pRow) { $found = $row; break; } } // Found? If not, create a new one if (is_null($found)) { $found = new PHPExcel_Worksheet_RowDimension($pRow); $this->_rowDimensions[] = $found; } // Return return $found; } /** * Get column dimension at a specific column * * @param string $pColumn String index of the column * @return PHPExcel_Worksheet_ColumnDimension */ public function getColumnDimension($pColumn = 'A') { // Uppercase coordinate $pColumn = strtoupper($pColumn); // Found $found = null; // Loop trough columns foreach ($this->_columnDimensions as $column) { if ($column->getColumnIndex() == $pColumn) { $found = $column; break; } } // Found? If not, create a new one if (is_null($found)) { $found = new PHPExcel_Worksheet_ColumnDimension($pColumn); $this->_columnDimensions[] = $found; } // Return return $found; } /** * Get column dimension at a specific column by using numeric cell coordinates * * @param string $pColumn Numeric column coordinate of the cell * @param string $pRow Numeric row coordinate of the cell * @return PHPExcel_Worksheet_ColumnDimension */ public function getColumnDimensionByColumn($pColumn = 0) { return $this->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($pColumn)); } /** * Get styles * * @return PHPExcel_Style[] */ public function getStyles() { return $this->_styles; } /** * Get style for cell * * @param string $pCellCoordinate Cell coordinate to get style for * @return PHPExcel_Style * @throws Exception */ public function getStyle($pCellCoordinate = 'A1') { // Uppercase coordinate $pCellCoordinate = strtoupper($pCellCoordinate); if (eregi(':', $pCellCoordinate)) { throw new Exception('Cell coordinate string can not be a range of cells.'); } else if (eregi('\$', $pCellCoordinate)) { throw new Exception('Cell coordinate string must not be absolute.'); } else if ($pCellCoordinate == '') { throw new Exception('Cell coordinate can not be zero-length string.'); } else { // Create a cell for this coordinate. // Reason: When we have an empty cell that has style information, // it should exist for our IWriter $this->getCell($pCellCoordinate); // Check if we already have style information for this cell. // If not, create a new style. if (isset($this->_styles[$pCellCoordinate])) { return $this->_styles[$pCellCoordinate]; } else { $newStyle = new PHPExcel_Style(); $this->_styles[$pCellCoordinate] = $newStyle; return $newStyle; } } } /** * Get style for cell by using numeric cell coordinates * * @param int $pColumn Numeric column coordinate of the cell * @param int $pRow Numeric row coordinate of the cell * @return PHPExcel_Style */ public function getStyleByColumnAndRow($pColumn = 0, $pRow = 0) { return $this->getStyle(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); } /** * Duplicate cell style to a range of cells * * Please note that this will overwrite existing cell styles for cells in range! * * @param PHPExcel_Style $pCellStyle Cell style to duplicate * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") * @throws Exception */ public function duplicateStyle($pCellStyle = null, $pRange = '') { // Uppercase coordinate $pRange = strtoupper($pRange); if ($pCellStyle instanceof PHPExcel_Style) { // Is it a cell range or a single cell? $rangeA = ''; $rangeB = ''; if (strpos($pRange, ':') === false) { $rangeA = $pRange; $rangeB = $pRange; } else { list($rangeA, $rangeB) = explode(':', $pRange); } // Calculate range outer borders $rangeStart = PHPExcel_Cell::coordinateFromString($rangeA); $rangeEnd = PHPExcel_Cell::coordinateFromString($rangeB); // Translate column into index $rangeStart[0] = PHPExcel_Cell::columnIndexFromString($rangeStart[0]) - 1; $rangeEnd[0] = PHPExcel_Cell::columnIndexFromString($rangeEnd[0]) - 1; // Make sure we can loop upwards on rows and columns if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { $tmp = $rangeStart; $rangeStart = $rangeEnd; $rangeEnd = $tmp; } // Loop trough cells and apply styles for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; $col++) { for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; $row++) { $this->getCell(PHPExcel_Cell::stringFromColumnIndex($col) . $row); $this->_styles[ PHPExcel_Cell::stringFromColumnIndex($col) . $row ] = clone $pCellStyle; } } } else { throw new Exception("Invalid PHPExcel_Style object passed."); } } /** * Set break on a cell * * @param string $pCell Cell coordinate (e.g. A1) * @param int $pBreak Break type (type of PHPExcel_Worksheet::BREAK_*) * @throws Exception */ public function setBreak($pCell = 'A1', $pBreak = PHPExcel_Worksheet::BREAK_NONE) { // Uppercase coordinate $pCell = strtoupper($pCell); if ($pCell != '') { $this->_breaks[strtoupper($pCell)] = $pBreak; } else { throw new Exception('No cell coordinate specified.'); } } /** * Set break on a cell by using numeric cell coordinates * * @param int $pColumn Numeric column coordinate of the cell * @param int $pRow Numeric row coordinate of the cell * @param int $pBreak Break type (type of PHPExcel_Worksheet::BREAK_*) * @throws Exception */ public function setBreakByColumnAndRow($pColumn = 0, $pRow = 0, $pBreak = PHPExcel_Worksheet::BREAK_NONE) { $this->setBreak(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow, $pBreak); } /** * Get breaks * * @return array[] */ public function getBreaks() { return $this->_breaks; } /** * Set merge on a cell range * * @param string $pRange Cell range (e.g. A1:E1) * @throws Exception */ public function mergeCells($pRange = 'A1:A1') { // Uppercase coordinate $pRange = strtoupper($pRange); if (eregi(':', $pRange)) { $this->_mergeCells[$pRange] = $pRange; } else { throw new Exception('Merge must be set on a range of cells.'); } } /** * Set merge on a cell range by using numeric cell coordinates * * @param int $pColumn1 Numeric column coordinate of the first cell * @param int $pRow1 Numeric row coordinate of the first cell * @param int $pColumn2 Numeric column coordinate of the last cell * @param int $pRow2 Numeric row coordinate of the last cell * @throws Exception */ public function mergeCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 0, $pColumn2 = 0, $pRow2 = 0) { $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; $this->mergeCells($cellRange); } /** * Remove merge on a cell range * * @param string $pRange Cell range (e.g. A1:E1) * @throws Exception */ public function unmergeCells($pRange = 'A1:A1') { // Uppercase coordinate $pRange = strtoupper($pRange); if (eregi(':', $pRange)) { if (isset($this->_mergeCells[$pRange])) { unset($this->_mergeCells[$pRange]); } else { throw new Exception('Cell range ' . $pRange . ' not known as merged.'); } } else { throw new Exception('Merge can only be removed from a range of cells.'); } } /** * Remove merge on a cell range by using numeric cell coordinates * * @param int $pColumn1 Numeric column coordinate of the first cell * @param int $pRow1 Numeric row coordinate of the first cell * @param int $pColumn2 Numeric column coordinate of the last cell * @param int $pRow2 Numeric row coordinate of the last cell * @throws Exception */ public function unmergeCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 0, $pColumn2 = 0, $pRow2 = 0) { $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; $this->unmergeCells($cellRange); } /** * Get merge cells * * @return array[] */ public function getMergeCells() { return $this->_mergeCells; } /** * Set protection on a cell range * * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) * @param string $pPassword Password to unlock the protection * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true * @throws Exception */ public function protectCells($pRange = 'A1', $pPassword = '', $pAlreadyHashed = false) { // Uppercase coordinate $pRange = strtoupper($pRange); if (!$pAlreadyHashed) { $pPassword = PHPExcel_Shared_PasswordHasher::hashPassword($pPassword); } $this->_protectedCells[$pRange] = $pPassword; } /** * Set protection on a cell range by using numeric cell coordinates * * @param int $pColumn1 Numeric column coordinate of the first cell * @param int $pRow1 Numeric row coordinate of the first cell * @param int $pColumn2 Numeric column coordinate of the last cell * @param int $pRow2 Numeric row coordinate of the last cell * @param string $pPassword Password to unlock the protection * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true * @throws Exception */ public function protectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 0, $pColumn2 = 0, $pRow2 = 0, $pPassword = '', $pAlreadyHashed = false) { $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; $this->protectCells($cellRange, $pPassword, $pAlreadyHashed); } /** * Remove protection on a cell range * * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) * @throws Exception */ public function unprotectCells($pRange = 'A1') { // Uppercase coordinate $pRange = strtoupper($pRange); if (isset($this->_protectedCells[$pRange])) { unset($this->_protectedCells[$pRange]); } else { throw new Exception('Cell range ' . $pRange . ' not known as protected.'); } } /** * Remove protection on a cell range by using numeric cell coordinates * * @param int $pColumn1 Numeric column coordinate of the first cell * @param int $pRow1 Numeric row coordinate of the first cell * @param int $pColumn2 Numeric column coordinate of the last cell * @param int $pRow2 Numeric row coordinate of the last cell * @param string $pPassword Password to unlock the protection * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true * @throws Exception */ public function unprotectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 0, $pColumn2 = 0, $pRow2 = 0, $pPassword = '', $pAlreadyHashed = false) { $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; $this->unprotectCells($cellRange, $pPassword, $pAlreadyHashed); } /** * Get protected cells * * @return array[] */ public function getProtectedCells() { return $this->_protectedCells; } /** * Get Autofilter Range * * @return string */ public function getAutoFilter() { return $this->_autoFilter; } /** * Set Autofilter Range * * @param string $pRange Cell range (i.e. A1:E10) * @throws Exception */ public function setAutoFilter($pRange = '') { // Uppercase coordinate $pRange = strtoupper($pRange); if (eregi(':', $pRange)) { $this->_autoFilter = $pRange; } else { throw new Exception('Autofilter must be set on a range of cells.'); } } /** * Set Autofilter Range by using numeric cell coordinates * * @param int $pColumn Numeric column coordinate of the cell * @param int $pRow Numeric row coordinate of the cell * @throws Exception */ public function setAutoFilterByColumnAndRow($pColumn = 0, $pRow = 0) { $this->setAutoFilter(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); } /** * Get Freeze Pane * * @return string */ public function getFreezePane() { return $this->_freezePane; } /** * Freeze Pane * * @param string $pCell Cell (i.e. A1) * @throws Exception */ public function freezePane($pCell = '') { // Uppercase coordinate $pCell = strtoupper($pCell); if (!eregi(':', $pCell)) { $this->_freezePane = $pCell; } else { throw new Exception('Freeze pane can not be set on a range of cells.'); } } /** * Freeze Pane by using numeric cell coordinates * * @param int $pColumn Numeric column coordinate of the cell * @param int $pRow Numeric row coordinate of the cell * @throws Exception */ public function freezePaneByColumnAndRow($pColumn = 0, $pRow = 0) { $this->freezePane(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); } /** * Unfreeze Pane * * @return string */ public function unfreezePane() { $this->freezePane(''); } /** * Insert a new row, updating all possible related data * * @param int $pBefore Insert before this one * @param int $pNumRows Number of rows to insert * @throws Exception */ function insertNewRowBefore($pBefore = 1, $pNumRows = 1) { if ($pBefore >= 1) { $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this); } else { throw new Exception("Rows can only be inserted before at least row 1."); } } /** * Insert a new column, updating all possible related data * * @param int $pBefore Insert before this one * @param int $pNumCols Number of columns to insert * @throws Exception */ function insertNewColumnBefore($pBefore = 'A', $pNumCols = 1) { if (!is_numeric($pBefore)) { $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this); } else { throw new Exception("Column references should not be numeric."); } } /** * Insert a new column, updating all possible related data * * @param int $pBefore Insert before this one (numeric column coordinate of the cell) * @param int $pNumCols Number of columns to insert * @throws Exception */ function insertNewColumnBeforeByIndex($pBefore = 0, $pNumCols = 1) { if ($pBefore >= 1) { $this->insertNewColumnBeforeByColumn(PHPExcel_Cell::stringFromColumnIndex($pBefore), $pNumCols); } else { throw new Exception("Columns can only be inserted before at least column A (1)."); } } /** * Delete a row, updating all possible related data * * @param int $pRow Remove starting with this one * @param int $pNumRows Number of rows to remove * @throws Exception */ function removeRow($pRow = 1, $pNumRows = 1) { if ($pRow >= 1) { $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this); } else { throw new Exception("Rows to be deleted should at least start from row 1."); } } /** * Remove a column, updating all possible related data * * @param int $pColumn Remove starting with this one * @param int $pNumCols Number of columns to remove * @throws Exception */ function removeColumn($pColumn = 'A', $pNumCols = 1) { if (!is_numeric($pColumn)) { $pColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($pColumn) - 1 + $pNumCols); $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); $objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this); } else { throw new Exception("Column references should not be numeric."); } } /** * Remove a column, updating all possible related data * * @param int $pColumn Remove starting with this one (numeric column coordinate of the cell) * @param int $pNumCols Number of columns to remove * @throws Exception */ function removeColumnByIndex($pColumn = 0, $pNumCols = 1) { if ($pBefore >= 1) { $this->removeColumn(PHPExcel_Cell::stringFromColumnIndex($pColumn), $pNumCols); } else { throw new Exception("Columns can only be inserted before at least column A (1)."); } } /** * Get hash code * * @return string Hash code */ public function getHashCode() { return md5( $this->_title . $this->_autoFilter . $this->_protection->isProtectionEnabled() . $this->calculateWorksheetDimension() . __CLASS__ ); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } }
{ "content_hash": "33ad386a0dfb8ba6170977848865abed", "timestamp": "", "source": "github", "line_count": 1161, "max_line_length": 144, "avg_line_length": 27.3755383290267, "alnum_prop": 0.5980870276562943, "repo_name": "ALTELMA/OfficeEquipmentManager", "id": "5d501a657c0db83358fb61e4d7978f212860655d", "size": "32837", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "application/libraries/PHPExcel/branches/v1.3.5/Classes/PHPExcel/Worksheet.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "209" }, { "name": "Batchfile", "bytes": "7424" }, { "name": "CSS", "bytes": "6892" }, { "name": "HTML", "bytes": "1547796" }, { "name": "JavaScript", "bytes": "11472" }, { "name": "PHP", "bytes": "79520483" } ], "symlink_target": "" }
/** * @file * libavfilter API usage example. * * @example filter_audio.c * This example will generate a sine wave audio, * pass it through a simple filter chain, and then compute the MD5 checksum of * the output data. * * The filter chain it uses is: * (input) -> abuffer -> volume -> aformat -> abuffersink -> (output) * * abuffer: This provides the endpoint where you can feed the decoded samples. * volume: In this example we hardcode it to 0.90. * aformat: This converts the samples to the samplefreq, channel layout, * and sample format required by the audio device. * abuffersink: This provides the endpoint where you can read the samples after * they have passed through the filter chain. */ #include <inttypes.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include "libavutil/channel_layout.h" #include "libavutil/md5.h" #include "libavutil/opt.h" #include "libavutil/samplefmt.h" #include "libavfilter/avfilter.h" #include "libavfilter/buffersink.h" #include "libavfilter/buffersrc.h" #define INPUT_SAMPLERATE 48000 #define INPUT_FORMAT AV_SAMPLE_FMT_FLTP #define INPUT_CHANNEL_LAYOUT AV_CH_LAYOUT_5POINT0 #define VOLUME_VAL 0.90 static int init_filter_graph(AVFilterGraph **graph, AVFilterContext **src, AVFilterContext **sink) { AVFilterGraph *filter_graph; AVFilterContext *abuffer_ctx; AVFilter *abuffer; AVFilterContext *volume_ctx; AVFilter *volume; AVFilterContext *aformat_ctx; AVFilter *aformat; AVFilterContext *abuffersink_ctx; AVFilter *abuffersink; AVDictionary *options_dict = NULL; uint8_t options_str[1024]; uint8_t ch_layout[64]; int err; /* Create a new filtergraph, which will contain all the filters. */ filter_graph = avfilter_graph_alloc(); if (!filter_graph) { fprintf(stderr, "Unable to create filter graph.\n"); return AVERROR(ENOMEM); } /* Create the abuffer filter; * it will be used for feeding the data into the graph. */ abuffer = avfilter_get_by_name("abuffer"); if (!abuffer) { fprintf(stderr, "Could not find the abuffer filter.\n"); return AVERROR_FILTER_NOT_FOUND; } abuffer_ctx = avfilter_graph_alloc_filter(filter_graph, abuffer, "src"); if (!abuffer_ctx) { fprintf(stderr, "Could not allocate the abuffer instance.\n"); return AVERROR(ENOMEM); } /* Set the filter options through the AVOptions API. */ av_get_channel_layout_string(ch_layout, sizeof(ch_layout), 0, INPUT_CHANNEL_LAYOUT); av_opt_set (abuffer_ctx, "channel_layout", ch_layout, AV_OPT_SEARCH_CHILDREN); av_opt_set (abuffer_ctx, "sample_fmt", av_get_sample_fmt_name(INPUT_FORMAT), AV_OPT_SEARCH_CHILDREN); av_opt_set_q (abuffer_ctx, "time_base", (AVRational){ 1, INPUT_SAMPLERATE }, AV_OPT_SEARCH_CHILDREN); av_opt_set_int(abuffer_ctx, "sample_rate", INPUT_SAMPLERATE, AV_OPT_SEARCH_CHILDREN); /* Now initialize the filter; we pass NULL options, since we have already * set all the options above. */ err = avfilter_init_str(abuffer_ctx, NULL); if (err < 0) { fprintf(stderr, "Could not initialize the abuffer filter.\n"); return err; } /* Create volume filter. */ volume = avfilter_get_by_name("volume"); if (!volume) { fprintf(stderr, "Could not find the volume filter.\n"); return AVERROR_FILTER_NOT_FOUND; } volume_ctx = avfilter_graph_alloc_filter(filter_graph, volume, "volume"); if (!volume_ctx) { fprintf(stderr, "Could not allocate the volume instance.\n"); return AVERROR(ENOMEM); } /* A different way of passing the options is as key/value pairs in a * dictionary. */ av_dict_set(&options_dict, "volume", AV_STRINGIFY(VOLUME_VAL), 0); err = avfilter_init_dict(volume_ctx, &options_dict); av_dict_free(&options_dict); if (err < 0) { fprintf(stderr, "Could not initialize the volume filter.\n"); return err; } /* Create the aformat filter; * it ensures that the output is of the format we want. */ aformat = avfilter_get_by_name("aformat"); if (!aformat) { fprintf(stderr, "Could not find the aformat filter.\n"); return AVERROR_FILTER_NOT_FOUND; } aformat_ctx = avfilter_graph_alloc_filter(filter_graph, aformat, "aformat"); if (!aformat_ctx) { fprintf(stderr, "Could not allocate the aformat instance.\n"); return AVERROR(ENOMEM); } /* A third way of passing the options is in a string of the form * key1=value1:key2=value2.... */ snprintf(options_str, sizeof(options_str), "sample_fmts=%s:sample_rates=%d:channel_layouts=0x%"PRIx64, av_get_sample_fmt_name(AV_SAMPLE_FMT_S16), 44100, (uint64_t)AV_CH_LAYOUT_STEREO); err = avfilter_init_str(aformat_ctx, options_str); if (err < 0) { av_log(NULL, AV_LOG_ERROR, "Could not initialize the aformat filter.\n"); return err; } /* Finally create the abuffersink filter; * it will be used to get the filtered data out of the graph. */ abuffersink = avfilter_get_by_name("abuffersink"); if (!abuffersink) { fprintf(stderr, "Could not find the abuffersink filter.\n"); return AVERROR_FILTER_NOT_FOUND; } abuffersink_ctx = avfilter_graph_alloc_filter(filter_graph, abuffersink, "sink"); if (!abuffersink_ctx) { fprintf(stderr, "Could not allocate the abuffersink instance.\n"); return AVERROR(ENOMEM); } /* This filter takes no options. */ err = avfilter_init_str(abuffersink_ctx, NULL); if (err < 0) { fprintf(stderr, "Could not initialize the abuffersink instance.\n"); return err; } /* Connect the filters; * in this simple case the filters just form a linear chain. */ err = avfilter_link(abuffer_ctx, 0, volume_ctx, 0); if (err >= 0) err = avfilter_link(volume_ctx, 0, aformat_ctx, 0); if (err >= 0) err = avfilter_link(aformat_ctx, 0, abuffersink_ctx, 0); if (err < 0) { fprintf(stderr, "Error connecting filters\n"); return err; } /* Configure the graph. */ err = avfilter_graph_config(filter_graph, NULL); if (err < 0) { av_log(NULL, AV_LOG_ERROR, "Error configuring the filter graph\n"); return err; } *graph = filter_graph; *src = abuffer_ctx; *sink = abuffersink_ctx; return 0; } /* Do something useful with the filtered data: this simple * example just prints the MD5 checksum of each plane to stdout. */ static int process_output(struct AVMD5 *md5, AVFrame *frame) { int planar = av_sample_fmt_is_planar(frame->format); int channels = av_get_channel_layout_nb_channels(frame->channel_layout); int planes = planar ? channels : 1; int bps = av_get_bytes_per_sample(frame->format); int plane_size = bps * frame->nb_samples * (planar ? 1 : channels); int i, j; for (i = 0; i < planes; i++) { uint8_t checksum[16]; av_md5_init(md5); av_md5_sum(checksum, frame->extended_data[i], plane_size); fprintf(stdout, "plane %d: 0x", i); for (j = 0; j < sizeof(checksum); j++) fprintf(stdout, "%02X", checksum[j]); fprintf(stdout, "\n"); } fprintf(stdout, "\n"); return 0; } /* Construct a frame of audio data to be filtered; * this simple example just synthesizes a sine wave. */ static int get_input(AVFrame *frame, int frame_num) { int err, i, j; #define FRAME_SIZE 1024 /* Set up the frame properties and allocate the buffer for the data. */ frame->sample_rate = INPUT_SAMPLERATE; frame->format = INPUT_FORMAT; frame->channel_layout = INPUT_CHANNEL_LAYOUT; frame->nb_samples = FRAME_SIZE; frame->pts = frame_num * FRAME_SIZE; err = av_frame_get_buffer(frame, 0); if (err < 0) return err; /* Fill the data for each channel. */ for (i = 0; i < 5; i++) { float *data = (float*)frame->extended_data[i]; for (j = 0; j < frame->nb_samples; j++) data[j] = sin(2 * M_PI * (frame_num + j) * (i + 1) / FRAME_SIZE); } return 0; } int main(int argc, char *argv[]) { struct AVMD5 *md5; AVFilterGraph *graph; AVFilterContext *src, *sink; AVFrame *frame; uint8_t errstr[1024]; float duration; int err, nb_frames, i; if (argc < 2) { fprintf(stderr, "Usage: %s <duration>\n", argv[0]); return 1; } duration = atof(argv[1]); nb_frames = duration * INPUT_SAMPLERATE / FRAME_SIZE; if (nb_frames <= 0) { fprintf(stderr, "Invalid duration: %s\n", argv[1]); return 1; } avfilter_register_all(); /* Allocate the frame we will be using to store the data. */ frame = av_frame_alloc(); if (!frame) { fprintf(stderr, "Error allocating the frame\n"); return 1; } md5 = av_md5_alloc(); if (!md5) { fprintf(stderr, "Error allocating the MD5 context\n"); return 1; } /* Set up the filtergraph. */ err = init_filter_graph(&graph, &src, &sink); if (err < 0) { fprintf(stderr, "Unable to init filter graph:"); goto fail; } /* the main filtering loop */ for (i = 0; i < nb_frames; i++) { /* get an input frame to be filtered */ err = get_input(frame, i); if (err < 0) { fprintf(stderr, "Error generating input frame:"); goto fail; } /* Send the frame to the input of the filtergraph. */ err = av_buffersrc_add_frame(src, frame); if (err < 0) { av_frame_unref(frame); fprintf(stderr, "Error submitting the frame to the filtergraph:"); goto fail; } /* Get all the filtered output that is available. */ while ((err = av_buffersink_get_frame(sink, frame)) >= 0) { /* now do something with our filtered frame */ err = process_output(md5, frame); if (err < 0) { fprintf(stderr, "Error processing the filtered frame:"); goto fail; } av_frame_unref(frame); } if (err == AVERROR(EAGAIN)) { /* Need to feed more frames in. */ continue; } else if (err == AVERROR_EOF) { /* Nothing more to do, finish. */ break; } else if (err < 0) { /* An error occurred. */ fprintf(stderr, "Error filtering the data:"); goto fail; } } avfilter_graph_free(&graph); av_frame_free(&frame); av_freep(&md5); return 0; fail: av_strerror(err, errstr, sizeof(errstr)); fprintf(stderr, "%s\n", errstr); return 1; }
{ "content_hash": "add2a7db698962dcb8f43b4ae022c16f", "timestamp": "", "source": "github", "line_count": 346, "max_line_length": 112, "avg_line_length": 31.86705202312139, "alnum_prop": 0.5993107201160892, "repo_name": "QuintonJason/qvids", "id": "8451f9cba226b51044e041fb0638c52380d3407a", "size": "11827", "binary": false, "copies": "31", "ref": "refs/heads/master", "path": "front-end/build/ffmpeg/doc/examples/filter_audio.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "10005918" }, { "name": "Batchfile", "bytes": "3372" }, { "name": "C", "bytes": "86027208" }, { "name": "C++", "bytes": "1780780" }, { "name": "CMake", "bytes": "11830" }, { "name": "CSS", "bytes": "25117" }, { "name": "HTML", "bytes": "45682" }, { "name": "JavaScript", "bytes": "102316154" }, { "name": "Makefile", "bytes": "1215706" }, { "name": "Objective-C", "bytes": "155378" }, { "name": "Perl", "bytes": "120954" }, { "name": "Perl6", "bytes": "156870" }, { "name": "Python", "bytes": "140870" }, { "name": "Roff", "bytes": "8668" }, { "name": "Shell", "bytes": "335396" }, { "name": "Verilog", "bytes": "5660" } ], "symlink_target": "" }
package org.apache.accumulo.test.functional; import static java.nio.charset.StandardCharsets.UTF_8; import java.util.ArrayList; import java.util.Iterator; import java.util.Map.Entry; import java.util.SortedSet; import java.util.TreeSet; import org.apache.accumulo.core.client.BatchScanner; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.BatchWriterConfig; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.security.Authorizations; import org.apache.accumulo.harness.AccumuloClusterIT; import org.apache.hadoop.io.Text; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.google.common.collect.Iterators; public class CreateAndUseIT extends AccumuloClusterIT { @Override protected int defaultTimeoutSeconds() { return 4 * 60; } private static SortedSet<Text> splits; @BeforeClass public static void createData() throws Exception { splits = new TreeSet<>(); for (int i = 1; i < 256; i++) { splits.add(new Text(String.format("%08x", i << 8))); } } @Test public void verifyDataIsPresent() throws Exception { Text cf = new Text("cf1"); Text cq = new Text("cq1"); String tableName = getUniqueNames(1)[0]; getConnector().tableOperations().create(tableName); getConnector().tableOperations().addSplits(tableName, splits); BatchWriter bw = getConnector().createBatchWriter(tableName, new BatchWriterConfig()); for (int i = 1; i < 257; i++) { Mutation m = new Mutation(new Text(String.format("%08x", (i << 8) - 16))); m.put(cf, cq, new Value(Integer.toString(i).getBytes(UTF_8))); bw.addMutation(m); } bw.close(); Scanner scanner1 = getConnector().createScanner(tableName, Authorizations.EMPTY); int ei = 1; for (Entry<Key,Value> entry : scanner1) { Assert.assertEquals(String.format("%08x", (ei << 8) - 16), entry.getKey().getRow().toString()); Assert.assertEquals(Integer.toString(ei), entry.getValue().toString()); ei++; } Assert.assertEquals("Did not see expected number of rows", 257, ei); } @Test public void createTableAndScan() throws Exception { String table2 = getUniqueNames(1)[0]; getConnector().tableOperations().create(table2); getConnector().tableOperations().addSplits(table2, splits); Scanner scanner2 = getConnector().createScanner(table2, Authorizations.EMPTY); int count = 0; for (Entry<Key,Value> entry : scanner2) { if (entry != null) count++; } if (count != 0) { throw new Exception("Did not see expected number of entries, count = " + count); } } @Test public void createTableAndBatchScan() throws Exception { ArrayList<Range> ranges = new ArrayList<>(); for (int i = 1; i < 257; i++) { ranges.add(new Range(new Text(String.format("%08x", (i << 8) - 16)))); } String table3 = getUniqueNames(1)[0]; getConnector().tableOperations().create(table3); getConnector().tableOperations().addSplits(table3, splits); BatchScanner bs = getConnector().createBatchScanner(table3, Authorizations.EMPTY, 3); bs.setRanges(ranges); Iterator<Entry<Key,Value>> iter = bs.iterator(); int count = Iterators.size(iter); bs.close(); Assert.assertEquals("Did not expect to find any entries", 0, count); } }
{ "content_hash": "a4d30bade78d8006b256c0f937b834db", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 101, "avg_line_length": 31.008695652173913, "alnum_prop": 0.6929332585530006, "repo_name": "adamjshook/accumulo", "id": "cffd84824eabefaaa252a78c5b065288ad4302bc", "size": "4367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/src/test/java/org/apache/accumulo/test/functional/CreateAndUseIT.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2423" }, { "name": "C++", "bytes": "1414083" }, { "name": "CSS", "bytes": "5933" }, { "name": "Groovy", "bytes": "1385" }, { "name": "HTML", "bytes": "11698" }, { "name": "Java", "bytes": "20215877" }, { "name": "JavaScript", "bytes": "249594" }, { "name": "Makefile", "bytes": "2865" }, { "name": "Perl", "bytes": "28190" }, { "name": "Protocol Buffer", "bytes": "1325" }, { "name": "Python", "bytes": "729147" }, { "name": "Ruby", "bytes": "211593" }, { "name": "Shell", "bytes": "194340" }, { "name": "Thrift", "bytes": "55653" } ], "symlink_target": "" }
package cc.ntechnologies.controller; import cc.ntechnologies.FacesUtils; import cc.ntechnologies.entities.GenericImage; import cc.ntechnologies.entities.News; import cc.ntechnologies.entities.Organizer; import cc.ntechnologies.service.NewsService; import cc.ntechnologies.service.OrganizerService; import org.primefaces.model.UploadedFile; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import javax.inject.Inject; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @Scope("request") public class NewsController implements Serializable { private static final long serialVersionUID = 1L; private NewsService newsService; private OrganizerService organizerService; private FacesUtils facesUtils; private Map<String, Long> organizersMap = new HashMap<String, Long>(); @Size(min=1, message="Please provide news title.") private String title; @Size(min=1, message="Please provide news text.") private String text; @NotNull(message="Please provide news image.") private UploadedFile image; @NotNull(message="Please provide news organizer.") private Long organizerId; @Inject public NewsController(final NewsService newsService, final OrganizerService organizerService, FacesUtils facesUtils) { List<Organizer> organizersList = organizerService.getAll(0, Integer.MAX_VALUE); for (Organizer organizer : organizersList) { this.organizersMap.put(organizer.getFullName(), organizer.getId()); } this.newsService = newsService; this.organizerService = organizerService; this.facesUtils = facesUtils; } public void createNews() { Organizer organizer = organizerService.findOrganizerById(this.organizerId); GenericImage genericImage = new GenericImage(); genericImage.createImageFromFile(image); News news = new News(title, text, organizer, genericImage); newsService.save(news); facesUtils.addSuccessMessage("Added news " + news.getTitle()); } public Map<String, Long> getOrganizersMap() { return this.organizersMap; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getText() { return text; } public void setText(String text) { this.text = text; } public UploadedFile getImage() { return this.image; } public void setImage(UploadedFile image) { this.image = image; } public Long getOrganizerId() { return this.organizerId; } public void setOrganizerId(Long organizerId) { this.organizerId = organizerId; } }
{ "content_hash": "cebed3524b728983c22476669ee6ea4c", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 122, "avg_line_length": 29.454545454545453, "alnum_prop": 0.7119341563786008, "repo_name": "qqalexqq/project6452", "id": "e7ccd28f8cea6f2a4d1d8efd2bb902659897f172", "size": "2916", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/cc/ntechnologies/controller/NewsController.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "HTML", "bytes": "36165" }, { "name": "Java", "bytes": "105094" }, { "name": "Shell", "bytes": "7058" } ], "symlink_target": "" }
<?php /** * @namespace */ namespace Zend\Pdf\Outline; use Zend\Pdf\Exception; use Zend\Pdf; use Zend\Pdf\InternalType; use Zend\Pdf\ObjectFactory; /** * Abstract PDF outline representation class * * @todo Implement an ability to associate an outline item with a structure element (PDF 1.3 feature) * * @uses Countable * @uses RecursiveIterator * @uses \Zend\Pdf\Exception * @uses \Zend\Pdf\Outline\Created * @uses \Zend\Pdf\ObjectFactory; * @package Zend_PDF * @subpackage Zend_PDF_Outline * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class AbstractOutline implements \RecursiveIterator, \Countable { /** * True if outline is open. * * @var boolean */ protected $_open = false; /** * Array of child outlines (array of \Zend\Pdf\Outline\AbstractOutline objects) * * @var array */ public $childOutlines = array(); /** * Get outline title. * * @return string */ abstract public function getTitle(); /** * Set outline title * * @param string $title * @return \Zend\Pdf\Outline\AbstractOutline */ abstract public function setTitle($title); /** * Returns true if outline item is open by default * * @return boolean */ public function isOpen() { return $this->_open; } /** * Sets 'isOpen' outline flag * * @param boolean $isOpen * @return \Zend\Pdf\Outline\AbstractOutline */ public function setIsOpen($isOpen) { $this->_open = $isOpen; return $this; } /** * Returns true if outline item is displayed in italic * * @return boolean */ abstract public function isItalic(); /** * Sets 'isItalic' outline flag * * @param boolean $isItalic * @return \Zend\Pdf\Outline\AbstractOutline */ abstract public function setIsItalic($isItalic); /** * Returns true if outline item is displayed in bold * * @return boolean */ abstract public function isBold(); /** * Sets 'isBold' outline flag * * @param boolean $isBold * @return \Zend\Pdf\Outline\AbstractOutline */ abstract public function setIsBold($isBold); /** * Get outline text color. * * @return \Zend\Pdf\Color\Rgb */ abstract public function getColor(); /** * Set outline text color. * (null means default color which is black) * * @param \Zend\Pdf\Color\Rgb $color * @return \Zend\Pdf\Outline\AbstractOutline */ abstract public function setColor(Pdf\Color\Rgb $color); /** * Get outline target. * * @return \Zend\Pdf\InternalStructure\NavigationTarget */ abstract public function getTarget(); /** * Set outline target. * Null means no target * * @param \Zend\Pdf\InternalStructure\NavigationTarget|string $target * @return \Zend\Pdf\Outline\AbstractOutline */ abstract public function setTarget($target = null); /** * Get outline options * * @return array */ public function getOptions() { return array('title' => $this->_title, 'open' => $this->_open, 'color' => $this->_color, 'italic' => $this->_italic, 'bold' => $this->_bold, 'target' => $this->_target); } /** * Set outline options * * @param array $options * @return \Zend\Pdf\Action\AbstractAction * @throws \Zend\Pdf\Exception */ public function setOptions(array $options) { foreach ($options as $key => $value) { switch ($key) { case 'title': $this->setTitle($value); break; case 'open': $this->setIsOpen($value); break; case 'color': $this->setColor($value); break; case 'italic': $this->setIsItalic($value); break; case 'bold': $this->setIsBold($value); break; case 'target': $this->setTarget($value); break; default: throw new Exception\InvalidArgumentException("Unknown option name - '$key'."); break; } } return $this; } /** * Create new Outline object * * It provides two forms of input parameters: * * 1. \Zend\Pdf\Outline\AbstractOutline::create(string $title[, \Zend\Pdf\InternalStructure\NavigationTarget $target]) * 2. \Zend\Pdf\Outline\AbstractOutline::create(array $options) * * Second form allows to provide outline options as an array. * The followed options are supported: * 'title' - string, outline title, required * 'open' - boolean, true if outline entry is open (default value is false) * 'color' - \Zend\Pdf\Color\Rgb object, true if outline entry is open (default value is null - black) * 'italic' - boolean, true if outline entry is displayed in italic (default value is false) * 'bold' - boolean, true if outline entry is displayed in bold (default value is false) * 'target' - \Zend\Pdf\InternalStructure\NavigationTarget object or string, outline item destination * * @return \Zend\Pdf\Outline\AbstractOutline * @throws \Zend\Pdf\Exception */ public static function create($param1, $param2 = null) { if (is_string($param1)) { if ($param2 !== null && !($param2 instanceof Pdf\InternalStructure\NavigationTarget || is_string($param2))) { throw new Exception\InvalidArgumentException('Outline create method takes $title (string) and $target (\Zend\Pdf\InternalStructure\NavigationTarget or string) or an array as an input'); } return new Created(array('title' => $param1, 'target' => $param2)); } else { if (!is_array($param1) || $param2 !== null) { throw new Exception\InvalidArgumentException('Outline create method takes $title (string) and $destination (\Zend\Pdf\InternalStructure\NavigationTarget) or an array as an input'); } return new Created($param1); } } /** * Returns number of the total number of open items at all levels of the outline. * * @internal * @return integer */ public function openOutlinesCount() { $count = 1; // Include this outline if ($this->isOpen()) { foreach ($this->childOutlines as $child) { $count += $child->openOutlinesCount(); } } return $count; } /** * Dump Outline and its child outlines into PDF structures * * Returns dictionary indirect object or reference * * @param \Zend\Pdf\ObjectFactory $factory object factory for newly created indirect objects * @param boolean $updateNavigation Update navigation flag * @param \Zend\Pdf\InternalType\AbstractTypeObject $parent Parent outline dictionary reference * @param \Zend\Pdf\InternalType\AbstractTypeObject $prev Previous outline dictionary reference * @param SplObjectStorage $processedOutlines List of already processed outlines * @return \Zend\Pdf\InternalType\AbstractTypeObject */ abstract public function dumpOutline(ObjectFactory $factory, $updateNavigation, InternalType\AbstractTypeObject $parent, InternalType\AbstractTypeObject $prev = null, \SplObjectStorage $processedOutlines = null); //////////////////////////////////////////////////////////////////////// // RecursiveIterator interface methods ////////////// /** * Returns the child outline. * * @return \Zend\Pdf\Outline\AbstractOutline */ public function current() { return current($this->childOutlines); } /** * Returns current iterator key * * @return integer */ public function key() { return key($this->childOutlines); } /** * Go to next child */ public function next() { return next($this->childOutlines); } /** * Rewind children */ public function rewind() { return reset($this->childOutlines); } /** * Check if current position is valid * * @return boolean */ public function valid() { return current($this->childOutlines) !== false; } /** * Returns the child outline. * * @return \Zend\Pdf\Outline\AbstractOutline|null */ public function getChildren() { return current($this->childOutlines); } /** * Implements RecursiveIterator interface. * * @return bool whether container has any pages */ public function hasChildren() { return count($this->childOutlines) > 0; } //////////////////////////////////////////////////////////////////////// // Countable interface methods ////////////// /** * count() * * @return int */ public function count() { return count($this->childOutlines); } }
{ "content_hash": "3f1e2c44661ca3d0038e929b2ece9e0b", "timestamp": "", "source": "github", "line_count": 363, "max_line_length": 201, "avg_line_length": 26.988980716253444, "alnum_prop": 0.5523119322241502, "repo_name": "phphatesme/LiveTest", "id": "41588001490833f66af1d177ed474f47ad1e3cd8", "size": "10498", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/lib/Zend/Pdf/Outline/AbstractOutline.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "14662639" }, { "name": "Shell", "bytes": "613" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in &#268;as. Nár. Mus. , Odd. P&#345;ír. 140:127. 1972 #### Original name null ### Remarks null
{ "content_hash": "5c2c50b14c5f94261f769b5ddb2e33cb", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 51, "avg_line_length": 13.923076923076923, "alnum_prop": 0.6574585635359116, "repo_name": "mdoering/backbone", "id": "927b2d51ff7e3555c32736a3b1ef86f38da0bdfa", "size": "252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Schoenoplectus/Schoenoplectus californicus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }