text
stringlengths
2
1.04M
meta
dict
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>compcert: 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.11.2 / compcert - 2.3.2</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> compcert <small> 2.3.2 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2021-03-31 05:27:10 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-03-31 05:27:10 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 coq 8.11.2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.10.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.1 Official release 4.10.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;http://compcert.inria.fr/&quot; dev-repo: &quot;git+https://github.com/AbsInt/CompCert.git&quot; bug-reports: &quot;https://github.com/AbsInt/CompCert/issues&quot; license: &quot;INRIA Non-Commercial License Agreement&quot; build: [ [&quot;./configure&quot; &quot;ia32-linux&quot;] [make &quot;-j%{jobs}%&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.4pl4&quot; &amp; &lt; &quot;8.5~&quot;} &quot;menhir&quot; {&gt;= &quot;20140422&quot;} ] synopsis: &quot;The CompCert C compiler&quot; authors: &quot;Xavier Leroy &lt;[email protected]&gt;&quot; extra-files: [&quot;coq-compcert.install&quot; &quot;md5=a7efe759bff32c6aac2c2ca483d5a266&quot;] url { src: &quot;http://compcert.inria.fr/release/compcert-2.3pl2.tgz&quot; checksum: &quot;md5=f97700e91163e6fbdb645721e2c1350f&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-compcert.2.3.2 coq.8.11.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2). The following dependencies couldn&#39;t be met: - coq-compcert -&gt; coq &lt; 8.5~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) 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-compcert.2.3.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"> <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": "9a2fb8a650f8910fbffaf12aad76d4d0", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 157, "avg_line_length": 40.2375, "alnum_prop": 0.5295122708915813, "repo_name": "coq-bench/coq-bench.github.io", "id": "c4a9994530434e07ce8a6b2ed0344859b6b2052a", "size": "6440", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.10.1-2.0.6/released/8.11.2/compcert/2.3.2.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/** * Appcache Loader * * After gaining the user's permission to make the app word offline, * load a page with an manifest in its HTML tag in an iframe * * @author Matt Andrews <[email protected]> */ /*global window, APP, APP_ROOT, confirm, console, document, localStorage*/ APP.appcache = (function () { 'use strict'; var statuses = { "-1": 'timeout', "0": 'uncached', "1": 'idle', "2": 'checking', "3": 'downloading', "4": 'updateready', "5": 'obsolete' }, offlineEnabled; function innerLoad() { // 5 minutes in the future var cookieExpires = new Date(new Date().getTime() + 60 * 5 * 1000); document.cookie = "appcacheUpdate=1;expires=" + cookieExpires.toGMTString(); var iframe = document.createElement('IFRAME'); iframe.setAttribute('style', 'width:0px; height:0px; visibility:hidden; position:absolute; border:none'); iframe.src = APP_ROOT + 'manifest.html'; iframe.id = 'appcacheloader'; document.body.appendChild(iframe); } function logEvent(evtcode, hasChecked) { var s = statuses[evtcode], loaderEl, cookieExpires; if (hasChecked || s === 'timeout') { if (s === 'uncached' || s === 'idle' || s === 'obsolete' || s === 'timeout' || s === 'updateready') { loaderEl = document.getElementById('appcacheloader'); loaderEl.parentNode.removeChild(loaderEl); // Remove appcacheUpdate cookie cookieExpires = new Date(new Date().getTime() - 60 * 5 * 1000); document.cookie = "appcacheUpdate=;expires=" + cookieExpires.toGMTString(); } } } function requestOffline() { return confirm("This website is capable of working offline. Would you like to enable this feature?"); } function start() { if (offlineEnabled !== true && offlineEnabled !== false) { offlineEnabled = requestOffline(); if (offlineEnabled) { localStorage.offlineEnabled = true; } } if (offlineEnabled === true) { innerLoad(); } } // If offline mode already enabled, run innerLoad offlineEnabled = localStorage.offlineEnabled; if (offlineEnabled !== undefined) { offlineEnabled = (offlineEnabled === "true"); } return { start: start, logEvent: logEvent }; }());
{ "content_hash": "40120928b119bea6b42232c202eeaab9", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 107, "avg_line_length": 28.30263157894737, "alnum_prop": 0.6620176662017666, "repo_name": "matthew-andrews/ft-style-offline-web-app-part-4", "id": "9bde1504a64e9f20b8b909eb66b5718f326ab3de", "size": "2151", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/appcache.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "26338" }, { "name": "PHP", "bytes": "10574" } ], "symlink_target": "" }
var createCallback = require('../functions/createCallback'), slice = require('../internals/slice'); /* Native method shortcuts for methods with the same name as other `lodash` methods */ var nativeMax = Math.max; /** * Gets the last element or last `n` elements of an array. If a callback is * provided elements at the end of the array are returned as long as the * callback returns truey. The callback is bound to `thisArg` and invoked * with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback] The function called * per element or the number of elements to return. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the last element(s) of `array`. * @example * * _.last([1, 2, 3]); * // => 3 * * _.last([1, 2, 3], 2); * // => [2, 3] * * _.last([1, 2, 3], function(num) { * return num > 1; * }); * // => [2, 3] * * var characters = [ * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.pluck(_.last(characters, 'blocked'), 'name'); * // => ['fred', 'pebbles'] * * // using "_.where" callback shorthand * _.last(characters, { 'employer': 'na' }); * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] */ function last(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = length; callback = createCallback(callback, thisArg, 3); while (index-- && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array ? array[length - 1] : undefined; } } return slice(array, nativeMax(0, length - n)); } module.exports = last;
{ "content_hash": "4ebe347702df21f4a3dce11cfacac71b", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 86, "avg_line_length": 32.22077922077922, "alnum_prop": 0.6142684401451027, "repo_name": "stanxii/ngb", "id": "d80605d7deab3bbbbac46668af7c8104cfe311be", "size": "2888", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node.js/node_modules/elasticsearch/node_modules/lodash-node/compat/arrays/last.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "117595" }, { "name": "Groovy", "bytes": "1232" }, { "name": "Java", "bytes": "75018" }, { "name": "JavaScript", "bytes": "306729" }, { "name": "Shell", "bytes": "2366" } ], "symlink_target": "" }
package com.ibm.watson.text_to_speech.v1.model; import static org.testng.Assert.*; import com.ibm.cloud.sdk.core.service.model.FileWithMetadata; import com.ibm.watson.text_to_speech.v1.utils.TestUtilities; import java.io.InputStream; import java.util.HashMap; import java.util.List; import org.testng.annotations.Test; /** Unit test class for the DeleteCustomPromptOptions model. */ public class DeleteCustomPromptOptionsTest { final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap(); final List<FileWithMetadata> mockListFileWithMetadata = TestUtilities.creatMockListFileWithMetadata(); @Test public void testDeleteCustomPromptOptions() throws Throwable { DeleteCustomPromptOptions deleteCustomPromptOptionsModel = new DeleteCustomPromptOptions.Builder() .customizationId("testString") .promptId("testString") .build(); assertEquals(deleteCustomPromptOptionsModel.customizationId(), "testString"); assertEquals(deleteCustomPromptOptionsModel.promptId(), "testString"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testDeleteCustomPromptOptionsError() throws Throwable { new DeleteCustomPromptOptions.Builder().build(); } }
{ "content_hash": "f01b5e45b26a7183f67a7b88c59503d9", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 89, "avg_line_length": 36.34285714285714, "alnum_prop": 0.7751572327044025, "repo_name": "watson-developer-cloud/java-sdk", "id": "dc646b8f6c69d01bf2d58b254cb2fdaa1ba8889c", "size": "1856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "text-to-speech/src/test/java/com/ibm/watson/text_to_speech/v1/model/DeleteCustomPromptOptionsTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "350" }, { "name": "HTML", "bytes": "50951" }, { "name": "Java", "bytes": "7270071" }, { "name": "Makefile", "bytes": "3123" }, { "name": "Python", "bytes": "381" }, { "name": "Shell", "bytes": "7894" } ], "symlink_target": "" }
var Sails = require('sails').Sails; var _ = require('lodash'); // Use a weird port to avoid tests failing if we // forget to shut down another Sails app var TEST_SERVER_PORT = 1337; module.exports = { TEST_PORT: TEST_SERVER_PORT, /** * Get default config for lifting */ getAppConfig: function() { var config = { port: TEST_SERVER_PORT, log: {level: 'verbose'}, hooks: { // Inject the adminpanel hook in this repo into this Sails app adminpanel: require('../..'), grunt: false, i18n: false }, views: { engine: 'jade' } //loadHooks: ['moduleloader', 'userconfig', 'http', 'session', 'sockets'] }; return config; }//, //setup: function (done) { // // New up an instance of Sails and lift it. // var app = Sails(); // app.lift(this.getAppConfig(), function (err) { // return done(err); // }); //}, // //teardown: function (done) { // // Tear down sails server // global.sails.lower(function () { // // Delete globals (just in case-- shouldn't matter) // delete global.sails; // return done(); // }); //} };
{ "content_hash": "c364f69ff6f75cbea6bbb1ff533a525f", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 85, "avg_line_length": 27.791666666666668, "alnum_prop": 0.48800599700149927, "repo_name": "funluiji/sails-hook-adminpanel", "id": "763f7c2b575c646a7536bb6f519478ea20b302b4", "size": "1334", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "test/helper/liftUtil.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3005" }, { "name": "HTML", "bytes": "24528" }, { "name": "JavaScript", "bytes": "284917" } ], "symlink_target": "" }
require File.expand_path("test/test_helper") describe Samlr::Tools::Timestamp do before { Samlr.jitter = nil } after { Samlr.jitter = nil } describe "::parse" do before { @time = ::Time.now } it "turns an iso8601 string into a time instance" do iso8601 = @time.utc.iso8601 assert_equal @time.to_i, Samlr::Tools::Timestamp.parse(iso8601).to_i end end describe "::stamp" do it "converts a given time to an iso8601 string in UTC" do assert_equal "2012-08-08T18:28:38Z", Samlr::Tools::Timestamp.stamp(Time.at(1344450518)) end it "defaults to a current timestamp in iso8601" do assert ::Time.iso8601(Samlr::Tools::Timestamp.stamp).is_a?(Time) end end describe "::not_on_or_after?" do describe "when no jitter is allowed" do it "disallows imprecision" do assert Samlr::Tools::Timestamp.not_on_or_after?(Time.now + 5) end end describe "when jitter is allowed" do before { Samlr.jitter = 10 } it "allows imprecision" do assert Samlr::Tools::Timestamp.not_on_or_after?(Time.now - 5) refute Samlr::Tools::Timestamp.not_on_or_after?(Time.now - 15) end end end describe "::before?" do describe "when no jitter is allowed" do it "disallows imprecision" do assert Samlr::Tools::Timestamp.not_before?(Time.now - 5) end end describe "when jitter is allowed" do before { Samlr.jitter = 10 } it "allows imprecision" do assert Samlr::Tools::Timestamp.not_before?(Time.now + 5) refute Samlr::Tools::Timestamp.not_before?(Time.now + 15) end end end end
{ "content_hash": "37e9935e8d3563324d266ab8df43c3a7", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 93, "avg_line_length": 28.53448275862069, "alnum_prop": 0.6404833836858006, "repo_name": "zendesk/samlr", "id": "ab02b9290a57410d8bfb0869209e00b44894c9ee", "size": "1655", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/unit/test_timestamp.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "89276" } ], "symlink_target": "" }
var express = require('express'); var router = express.Router(); var http = require('http'); var common = require('../utils/common.js'); var config = require('../config.js'); var tbSignUtil = require('../utils/taobaoSign.js'); var MySQLClient = require('../utils/MySQLClient.js'); var mysqlClientInstance = new MySQLClient(); var verifyCodeMap = new Map(); /** * 获取短信验证码 */ router.get('/', function (request, response, next) { var phoneNumber = request.query.phoneNumber; console.log('phoneNumber = ' + phoneNumber); if (!phoneNumber) { var result = { code: 1, message: '缺少phoneNumber参数' }; response.send(result); return; } var verifyCode = "1234"; var params = {code: verifyCode, product: config.alidayu.product}; // 短信发送的参数对象 var obj = { format: 'json', method: 'alibaba.aliqin.fc.sms.num.send', partner_id: config.alidayu.partner_id, rec_num: phoneNumber, sign_method: 'hmac', sms_type: 'normal', sms_param: JSON.stringify(params), sms_free_sign_name: config.alidayu.sms_free_sign_name, sms_template_code: config.alidayu.sms_template_code, v: '2.0' }; var result = tbSignUtil.sign(obj); obj.sign = result.sign; obj.timestamp = result.timestamp; console.log(obj); var requestEntity = common.getEncodedURL(obj); var options = { host: 'gw.api.taobao.com', path: '/router/rest', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', 'Content-Length': requestEntity.length } }; var req = http.request(options, function (res) { console.log('STATUS: ' + res.statusCode); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); chunk = JSON.parse(chunk); if (chunk.alibaba_aliqin_fc_sms_num_send_response && chunk.alibaba_aliqin_fc_sms_num_send_response.result && chunk.alibaba_aliqin_fc_sms_num_send_response.result.err_code == '0' && chunk.alibaba_aliqin_fc_sms_num_send_response.result.success) { verifyCodeMap.put(phoneNumber, verifyCode); var result = { code: 0, message: '成功' }; response.send(result); } else { var result = {}; result.code = chunk.error_response.code; result.message = chunk.error_response.sub_msg; response.send(result); } }); res.on('error', function (err) { console.log('RESPONSE ERROR: ' + err); var result = { code: 1, message: '失败' }; response.send(result); }); }); req.on('error', function (err) { console.log('REQUEST ERROR: ' + err); var result = { code: 1, message: '失败' }; response.send(result); }); req.write(requestEntity); req.end(); }); router.post('/', function (request, response, next) { var requestEntity = request.body; if (requestEntity) { var phoneNumber = requestEntity.phoneNumber; var verifyCode = requestEntity.verifyCode; console.log('phoneNumber = ' + phoneNumber); console.log('verifyCode = ' + verifyCode); if (phoneNumber && verifyCode && verifyCodeMap.get(phoneNumber) == verifyCode) { mysqlClientInstance.exec("SELECT id FROM t_user WHERE phoneNumber = ?", [phoneNumber], function (err, rows, fieds) { if (err) { console.log(err.stack); var result = { code: 1, message: '失败' }; response.send(result); return; } else { console.log('SELECT id FROM t_user WHERE phoneNumber = ? success'); if (!rows || rows.length == 0) { var result = { code: 1, message: '您输入的手机号与您的注册信息不符合,请联系管理员' }; response.send(result); } else if (rows.length == 1) { var password = sha('md5', '123456'); mysqlClientInstance.exec("UPDATE t_user SET password = ? WHERE phoneNumber = ?", [password, phoneNumber], function (err, rows, fieds) { if (err) { console.log(err.stack); var result = { code: 1, message: '失败' }; response.send(result); } else { console.log('UPDATE t_user SET password = ? WHERE phoneNumber = ? success'); var result = { code: 0, message: '重置密码成功' }; response.send(result); } return; }); } else { var result = { code: 1, message: '您输入的手机号与别人有相同,请更换手机号或者联系管理员' }; response.send(result); } return; } }); return; } } var result = { code: 1, message: '失败' }; response.send(result); }); module.exports = router;
{ "content_hash": "a4e47aa0ccb5d9201608273c76483be0", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 159, "avg_line_length": 30.390862944162436, "alnum_prop": 0.4579923166861533, "repo_name": "leleliu008/Order_NodeJS", "id": "2af64fa8a20970a580d9fdc6a6e9357b009787d8", "size": "6165", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/private/routes/verifyCode.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "15724" }, { "name": "Dockerfile", "bytes": "208" }, { "name": "HTML", "bytes": "120158" }, { "name": "JavaScript", "bytes": "98443" }, { "name": "Shell", "bytes": "83" } ], "symlink_target": "" }
<resources> <!-- TODO: Before you run your application, you need a Google Maps API key. To get one, follow this link, follow the directions and press "Create" at the end: https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=B5:53:FD:C5:E8:22:AC:03:22:60:95:AE:F9:1C:51:CD:32:48:2C:CB%3Bcom.github.stakkato95.testtask.activity You can also add your credentials to an existing key, using this line: B5:53:FD:C5:E8:22:AC:03:22:60:95:AE:F9:1C:51:CD:32:48:2C:CB;com.github.stakkato95.testtask.activity Once you have your key (it starts with "AIza"), replace the "google_maps_key" string in this file. --> <string name="google_maps_key" translatable="false" templateMergeStrategy="preserve"> AIzaSyBPR_oVC1bNrohafhGNRsO_Kk_p6w6UdsM </string> </resources>
{ "content_hash": "a2f89b9953dc167a06c9dd5529a4a64b", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 212, "avg_line_length": 47.72222222222222, "alnum_prop": 0.7229336437718277, "repo_name": "stakkato95/Test-task", "id": "3718417e0f08d2f09f845772acd93f03bd7f2c9c", "size": "859", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TestTask/app/src/debug/res/values/google_maps_api.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "65957" } ], "symlink_target": "" }
package org.cqframework.cql.cql2elm.model.invocation; import org.hl7.elm.r1.Expression; import org.hl7.elm.r1.Slice; import java.util.ArrayList; import java.util.Collections; /** * Created by Bryn on 5/17/2017. */ public class TailInvocation extends OperatorExpressionInvocation { public TailInvocation(Slice expression) { super(expression); } @Override public Iterable<Expression> getOperands() { return Collections.singletonList(((Slice) expression).getSource()); } @Override public void setOperands(Iterable<Expression> operands) { ((Slice) expression).setSource(assertAndGetSingleOperand(operands)); } }
{ "content_hash": "5ead2d19810416ebc4095f2dc1462a4b", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 76, "avg_line_length": 25.807692307692307, "alnum_prop": 0.7213114754098361, "repo_name": "cqframework/clinical_quality_language", "id": "34c2923be3a937b4e2192309c48e9435335d59d0", "size": "671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/java/cql-to-elm/src/main/java/org/cqframework/cql/cql2elm/model/invocation/TailInvocation.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "42251" }, { "name": "Batchfile", "bytes": "382" }, { "name": "C#", "bytes": "276543" }, { "name": "Java", "bytes": "2327037" }, { "name": "TSQL", "bytes": "1292" } ], "symlink_target": "" }
package io.airlift.node; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import io.airlift.configuration.ConfigurationModule; import org.weakref.jmx.guice.MBeanModule; public class NodeModule implements Module { @Override public void configure(Binder binder) { binder.requireExplicitBindings(); binder.disableCircularProxies(); binder.bind(NodeInfo.class).in(Scopes.SINGLETON); ConfigurationModule.bindConfig(binder).to(NodeConfig.class); MBeanModule.newExporter(binder).export(NodeInfo.class).withGeneratedName(); } }
{ "content_hash": "74b3d7e3a463b284e5ce001d0b8aded7", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 83, "avg_line_length": 27.73913043478261, "alnum_prop": 0.7398119122257053, "repo_name": "erichwang/airlift", "id": "4908f83aaf571c6e378b9ff6194523bfc00af91f", "size": "1237", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node/src/main/java/io/airlift/node/NodeModule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1803344" }, { "name": "Python", "bytes": "13631" }, { "name": "Shell", "bytes": "1450" } ], "symlink_target": "" }
@interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { return YES; } - (void)applicationWillResignActive:(UIApplication *)application { } - (void)applicationDidEnterBackground:(UIApplication *)application { } - (void)applicationWillEnterForeground:(UIApplication *)application { } - (void)applicationDidBecomeActive:(UIApplication *)application { } - (void)applicationWillTerminate:(UIApplication *)application { } @end
{ "content_hash": "f13c5d569bfc6be546b11ffadd6e63ae", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 110, "avg_line_length": 20.333333333333332, "alnum_prop": 0.7814207650273224, "repo_name": "bitpay/ios-sdk", "id": "38aced598eec913cabf346597057ad2f47652091", "size": "742", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Example/ios-example-objective-c/AppDelegate.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "7713" }, { "name": "Ruby", "bytes": "134" }, { "name": "Swift", "bytes": "17564" } ], "symlink_target": "" }
package com.yumo.common.android; import android.content.Context; /** * Created by yumodev on 17/2/24. * 资源相关的工具类 */ public class YmResUtil { /** * dip to px * * @param context * @param dip * @return */ public static float dipToPx(Context context, float dip) { if (context == null) { return dip; } final float density = context.getResources().getDisplayMetrics().density; return dip * density + 0.5f; } /** * px to dip * * @param context * @param px * @return */ public static int pxToDip(Context context, float px) { if (context == null) { return (int) px; } final float density = context.getResources().getDisplayMetrics().density; return (int) (px / density + 0.5f); } /** * 将px值转换为sp值,保证文字大小不变 * * @param context * @param px * @return */ public static int px2sp(Context context, float px) { if (context == null) { return (int) px; } final float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity; return (int) (px / scaledDensity + 0.5f); } /** * 将sp值转换为px值,保证文字大小不变 * * @param context * @param sp * @return */ public static int sp2px(Context context, float sp) { if (context == null) { return (int) sp; } final float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity; return (int) (sp * scaledDensity + 0.5f); } }
{ "content_hash": "f2974ac454c44befd1c2dba6d54ddcb9", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 93, "avg_line_length": 21.613333333333333, "alnum_prop": 0.5422578655151141, "repo_name": "YumoDevTest/AndroidOpenTest", "id": "8772f4c8025743d44be92c6b55eecd624a9e4f13", "size": "1697", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/src/main/java/com/yumo/common/android/YmResUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1284385" }, { "name": "Kotlin", "bytes": "46687" } ], "symlink_target": "" }
#pragma once #include "JSFunction.h" namespace JSC { class JSGlobalObject; class NativeStdFunctionCell; typedef std::function<EncodedJSValue (ExecState*)> NativeStdFunction; class JSNativeStdFunction : public JSFunction { public: typedef JSFunction Base; const static unsigned StructureFlags = Base::StructureFlags; DECLARE_EXPORT_INFO; JS_EXPORT_PRIVATE static JSNativeStdFunction* create(VM&, JSGlobalObject*, int length, const String& name, NativeStdFunction&&, Intrinsic = NoIntrinsic, NativeFunction nativeConstructor = callHostFunctionAsConstructor); static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype) { ASSERT(globalObject); return Structure::create(vm, globalObject, prototype, TypeInfo(JSFunctionType, StructureFlags), info()); } NativeStdFunctionCell* nativeStdFunctionCell() { return m_functionCell.get(); } protected: static void visitChildren(JSCell*, SlotVisitor&); void finishCreation(VM&, NativeExecutable*, int length, const String& name, NativeStdFunctionCell*); private: JSNativeStdFunction(VM&, JSGlobalObject*, Structure*); WriteBarrier<NativeStdFunctionCell> m_functionCell; }; } // namespace JSC
{ "content_hash": "b5a61afa9012d5140009a385db81bb88", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 223, "avg_line_length": 29.5, "alnum_prop": 0.7602905569007264, "repo_name": "acton393/incubator-weex", "id": "2da0c0eb063d331db4761cdc10a69cafb7a8fb76", "size": "2047", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "weex_core/Source/include/JavaScriptCore/runtime/JSNativeStdFunction.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1100" }, { "name": "C", "bytes": "60699" }, { "name": "C++", "bytes": "1854783" }, { "name": "CMake", "bytes": "10554" }, { "name": "HTML", "bytes": "2550" }, { "name": "Java", "bytes": "3880410" }, { "name": "JavaScript", "bytes": "4869113" }, { "name": "Objective-C", "bytes": "1424241" }, { "name": "Objective-C++", "bytes": "624134" }, { "name": "Python", "bytes": "53148" }, { "name": "Ruby", "bytes": "10196" }, { "name": "Shell", "bytes": "30067" }, { "name": "Vue", "bytes": "111308" } ], "symlink_target": "" }
<?php namespace hipanel\modules\domain\grid; use hipanel\grid\BoxedGridView; use hipanel\grid\MainColumn; use hipanel\modules\domain\models\Secdns; use hipanel\modules\domain\controllers\DomainController; use hiqdev\combo\StaticCombo; use Yii; use yii\helpers\Html; use yii\helpers\Url; class SecdnsGridView extends BoxedGridView { public function columns() { return array_merge(parent::columns(), [ 'domain' => [ 'format' => 'raw', 'attribute' => 'domain', 'filterAttribute' => 'domain_like', 'value' => function ($model): string { return Html::a(Html::encode($model->domain), DomainController::getActionUrl('view', $model->domain_id)); }, ], 'key_tag' => [ 'format' => 'raw', 'attribute' => 'key_tag', 'value' => function($model): string { return Html::tag('span', isset($model->key_tag) ? Html::encode($model->key_tag) : ''); } ], 'digest_alg' => [ 'attribute' => 'digest_alg', 'format' => 'raw', 'value' => function($model): string { return Html::tag('span', $model->getDigestAlgorithm()); }, ], 'digest_type' => [ 'attribute' => 'digest_type', 'format' => 'raw', 'value' => function($model): string { return Html::tag('span', $model->getDigestType()); }, ], 'digest' => [ 'attribute' => 'digest', 'format' => 'raw', 'value' => function($model): string { return Html::tag('span', isset($model->digest) ? Html::encode($model->digest) : ''); }, ], 'key_alg' => [ 'attribute' => 'key_alg', 'format' => 'raw', 'value' => function($model): string { return Html::tag('span', $model->getKeyAlgorithm()); }, ], 'pub_key' => [ 'attribute' => 'pub_key', 'format' => 'raw', 'value' => function($model): string { return Html::tag('span', isset($model->pub_key) ? Html::encode($model->pub_key) : ''); }, ], ]); } }
{ "content_hash": "950096b4e3c03852dd5af1e5b42e0272", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 124, "avg_line_length": 34.861111111111114, "alnum_prop": 0.43545816733067727, "repo_name": "hiqdev/hipanel-module-domain", "id": "40eb30d902f7573f30c53d024e468b9975c130f7", "size": "2741", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/grid/SecdnsGridView.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "12924" }, { "name": "PHP", "bytes": "591346" } ], "symlink_target": "" }
Vendoring ========= The Go code in this repo depends on a number of Go libraries. These are vendored in to the `src/cmd/linuxkit/vendor` directory using [go modules](https://golang.org/ref/mod) ## Updating dependencies Go modules should install any required dependencies to `go.mod` and `go.sum` when running normal go commands such as `go build`, `go vet`, etc. To install specific versions, use `go get <dependency>@<reference>`. See the [go modules](https://golang.org/ref/mod) documentation for more information. LinuxKit vendors all dependencies to make it completely self-contained. Once `go.mod` is up to date, you must update the dependencies, either using your local go toolchain or in a container. ## Updating locally To vendor all dependencies: 1. `cd src/cmd/linuxkit` 1. Run `go mod vendor` ## Updating in a container To update all dependencies: ``` docker run -it --rm \ -v $(pwd):/go/src/github.com/linuxkit/linuxkit \ -w /go/src/github.com/linuxkit/linuxkit/src/cmd/linuxkit \ --entrypoint=go linuxkit/go-compile:7b1f5a37d2a93cd4a9aa2a87db264d8145944006 mod vendor ```
{ "content_hash": "fed34a3695b280b6f30ec61a3c8658f5", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 128, "avg_line_length": 31.314285714285713, "alnum_prop": 0.7527372262773723, "repo_name": "djs55/linuxkit", "id": "5fbd637ec9d32e7ebe115d507ac2bc3bb9387837", "size": "1096", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "docs/vendoring.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "33724" }, { "name": "Cap'n Proto", "bytes": "2365" }, { "name": "Dockerfile", "bytes": "79310" }, { "name": "Go", "bytes": "562002" }, { "name": "HTML", "bytes": "188" }, { "name": "Makefile", "bytes": "46989" }, { "name": "OCaml", "bytes": "69432" }, { "name": "Python", "bytes": "6363" }, { "name": "Shell", "bytes": "178288" }, { "name": "Standard ML", "bytes": "37" } ], "symlink_target": "" }
<?php error_reporting(E_STRICT | E_ALL); // You can set the include path to src directory or reference // DfpUser.php directly via require_once. // $path = '/path/to/dfp_api_php_lib/src'; $path = dirname(__FILE__) . '/../../../../src'; set_include_path(get_include_path() . PATH_SEPARATOR . $path); require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php'; require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php'; try { // Get DfpUser from credentials in "../auth.ini" // relative to the DfpUser.php file's directory. $user = new DfpUser(); // Log SOAP XML request and response. $user->LogDefaults(); // Get the TeamService. $teamService = $user->GetService('TeamService', 'v201502'); // Create an array to store local team objects. $teams = array(); for ($i = 0; $i < 5; $i++) { $team = new Team(); $team->name = 'Team #' . uniqid(); $team->hasAllCompanies = false; $team->hasAllInventory = false; $teams[] = $team; } // Create the teams on the server. $teams = $teamService->createTeams($teams); // Display results. if (isset($teams)) { foreach ($teams as $team) { print 'A team with ID "' . $team->id . '" and name "'. $team->name . '" was created."' . "\n"; } } else { print "No teams created.\n"; } } catch (OAuth2Exception $e) { ExampleUtils::CheckForOAuth2Errors($e); } catch (ValidationException $e) { ExampleUtils::CheckForOAuth2Errors($e); } catch (Exception $e) { print $e->getMessage() . "\n"; }
{ "content_hash": "88cb01d468de3d8b96ac34a17437f3d0", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 69, "avg_line_length": 27.196428571428573, "alnum_prop": 0.6080105055810899, "repo_name": "egregorius/googleads-php-lib", "id": "bb407362faba679bda0101a2ae70d2dac44efe90", "size": "2493", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "examples/Dfp/v201502/TeamService/CreateTeams.php", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "38462305" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <Monster xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Name>paper golem</Name> <Attack1>Claw: 1d3</Attack1> <Difficulty>4</Difficulty> <BaseLevel>3</BaseLevel> <BaseExperience>31</BaseExperience> <Speed>12</Speed> <BaseAC>10</BaseAC> <BaseMR>0</BaseMR> <Alignment>0 (neutral)</Alignment> <Frequency>(by normal means) 1 (Very rare)</Frequency> <GenoCidable>No</GenoCidable> <Weight>400</Weight> <NutritionalValue>0</NutritionalValue> <Size>large</Size> <Resistances>conveyed None</Resistances> <ResistancesConveyed>None</ResistancesConveyed> <Characteristics> <string>does not breathe. </string> <string>is mindless. </string> <string>has a head, a couple of arms, and a torso. </string> <string>does not eat. (*) </string> <string>is neither male nor female. </string> <string>is normally generated hostile.</string> </Characteristics> </Monster>
{ "content_hash": "64da207eba999ceacc3b7580870cb3d7", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 108, "avg_line_length": 37.03703703703704, "alnum_prop": 0.701, "repo_name": "DualBrain/VbRogue", "id": "f351e63f7dfff355f7734c32dbd8408fd332c845", "size": "1000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Rogue-likes/netHackWiki/Monsters/paper golem.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "90" }, { "name": "Visual Basic", "bytes": "756177" } ], "symlink_target": "" }
<?= "<?php\n" ?> namespace App\Containers\{{ $crud->containerName() }}\Tasks{{ $crud->solveGroupClasses() }}; use App\Containers\{{ $crud->containerName() }}\Data\Repositories\{{ $repoClass = $crud->entityName().'Repository' }}; use App\Containers\{{ $crud->containerName() }}\Exceptions\{{ $crud->entityName() }}CreationFailedException; use App\Ship\Parents\Tasks\Task; /** * {{ $crud->taskClass('Create') }} Class. * * @author [name] <[<email address>]> */ class {{ $crud->taskClass('Create') }} extends Task { public function run(array $input) { try { ${{ $camelEntity = camel_case($crud->entityName()) }} = app({{ $repoClass }}::class)->create($input); } catch (Exception $e) { throw (new {{ $crud->entityName() }}CreationFailedException())->debug($e); } return ${{ $camelEntity }}; } }
{ "content_hash": "9f2b69cdee7e2d093d5dfb3494c9080c", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 118, "avg_line_length": 34.08, "alnum_prop": 0.602112676056338, "repo_name": "llstarscreamll/Crud", "id": "0cdfd51bfd8f1d5550fc238b41eaeb3afeee3e27", "size": "852", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "UI/WEB/Views/GeneratorTemplates/Porto/Tasks/Create.blade.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "281833" }, { "name": "PHP", "bytes": "821975" }, { "name": "TypeScript", "bytes": "103175" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Can. J. Bot. 67(5): 1573 (1989) #### Original name Leptosphaeria spartinae Ellis & Everh., 1885 ### Remarks null
{ "content_hash": "3aa5d8abcea1b1e7b93a6c6954a59966", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 44, "avg_line_length": 15.461538461538462, "alnum_prop": 0.6915422885572139, "repo_name": "mdoering/backbone", "id": "cb0dc5a43c9e5fab86a59a1418d6e7a7d62f4121", "size": "294", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Phaeosphaeriaceae/Phaeosphaeria/Phaeosphaeria spartinae/README.md", "mode": "33188", "license": "apache-2.0", "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> <!-- Generated by javadoc (1.8.0_72-internal) on Mon Mar 14 13:22:17 GMT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class org.apache.taverna.scufl2.xml.rdfs.Range (Apache Taverna Language APIs (Scufl2, Databundle) 0.15.1-incubating API)</title> <meta name="date" content="2016-03-14"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.taverna.scufl2.xml.rdfs.Range (Apache Taverna Language APIs (Scufl2, Databundle) 0.15.1-incubating API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/taverna/scufl2/xml/rdfs/Range.html" title="class in org.apache.taverna.scufl2.xml.rdfs">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/apache/taverna/scufl2/xml/rdfs/class-use/Range.html" target="_top">Frames</a></li> <li><a href="Range.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.taverna.scufl2.xml.rdfs.Range" class="title">Uses of Class<br>org.apache.taverna.scufl2.xml.rdfs.Range</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../org/apache/taverna/scufl2/xml/rdfs/Range.html" title="class in org.apache.taverna.scufl2.xml.rdfs">Range</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.apache.taverna.scufl2.xml.rdfs">org.apache.taverna.scufl2.xml.rdfs</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.taverna.scufl2.xml.rdfs"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/apache/taverna/scufl2/xml/rdfs/Range.html" title="class in org.apache.taverna.scufl2.xml.rdfs">Range</a> in <a href="../../../../../../../org/apache/taverna/scufl2/xml/rdfs/package-summary.html">org.apache.taverna.scufl2.xml.rdfs</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../org/apache/taverna/scufl2/xml/rdfs/package-summary.html">org.apache.taverna.scufl2.xml.rdfs</a> that return <a href="../../../../../../../org/apache/taverna/scufl2/xml/rdfs/Range.html" title="class in org.apache.taverna.scufl2.xml.rdfs">Range</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/apache/taverna/scufl2/xml/rdfs/Range.html" title="class in org.apache.taverna.scufl2.xml.rdfs">Range</a></code></td> <td class="colLast"><span class="typeNameLabel">ObjectFactory.</span><code><span class="memberNameLink"><a href="../../../../../../../org/apache/taverna/scufl2/xml/rdfs/ObjectFactory.html#createRange--">createRange</a></span>()</code> <div class="block">Create an instance of <a href="../../../../../../../org/apache/taverna/scufl2/xml/rdfs/Range.html" title="class in org.apache.taverna.scufl2.xml.rdfs"><code>Range</code></a></div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/taverna/scufl2/xml/rdfs/Range.html" title="class in org.apache.taverna.scufl2.xml.rdfs">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/apache/taverna/scufl2/xml/rdfs/class-use/Range.html" target="_top">Frames</a></li> <li><a href="Range.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2015&#x2013;2016 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "3adea944b2f2305489de1ee2c57c93e5", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 353, "avg_line_length": 43.208333333333336, "alnum_prop": 0.626119300179088, "repo_name": "apache/incubator-taverna-site", "id": "02061b88483297bbffceb2cb72872267a9e77f14", "size": "7259", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "content/javadoc/taverna-language/org/apache/taverna/scufl2/xml/rdfs/class-use/Range.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10003" }, { "name": "Clojure", "bytes": "49413" }, { "name": "Dockerfile", "bytes": "1398" }, { "name": "HTML", "bytes": "72209" }, { "name": "Perl", "bytes": "2822" }, { "name": "Python", "bytes": "31455" }, { "name": "Shell", "bytes": "374" } ], "symlink_target": "" }
namespace System.IO { internal abstract class FileInfo2 : IFileInfo { private readonly IFilesystem _filesystem; private readonly string _name; private readonly string _fullPath; private readonly string _directoryPath; protected FileInfo2(IFilesystem filesystem, string fullPath) { _filesystem = filesystem ?? throw new ArgumentNullException(nameof(filesystem)); _fullPath = fullPath; _directoryPath = Path.GetDirectoryName(fullPath); _name = Path.GetFileName(fullPath); } public override int GetHashCode() { return new PathComparer().GetHashCode(_fullPath); } public override bool Equals(object obj) { var other = obj as FileInfo2; if (other == null) return false; return new PathComparer().Equals(_fullPath, other._fullPath); } public IDirectoryInfo Directory { get { return _filesystem.GetDirectoryInfo(_directoryPath); } } public string DirectoryName { get { return _directoryPath; } } public string Name => _name; public string FullPath => _fullPath; public long Length { get { return _filesystem.FileLength(_fullPath); } } public bool IsReadOnly { get { return _filesystem.IsFileReadOnly(_fullPath); } } public bool Exists { get { return _filesystem.FileExists(_fullPath); } } public abstract DateTime CreationTimeUtc { get; } public abstract DateTime LastAccessTimeUtc { get; } public abstract DateTime LastWriteTimeUtc { get; } public Stream Create() { return _filesystem.CreateFile(_fullPath); } public void Delete() { _filesystem.DeleteFile(_fullPath); } public override string ToString() { return "{" + FullPath + "}"; } } }
{ "content_hash": "a4de9eb35d748d14efdc25b5bc4d0b77", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 83, "avg_line_length": 17.313725490196077, "alnum_prop": 0.6653454133635334, "repo_name": "Kittyfisto/System.Extensions", "id": "1193625273cd9e0349308f5dc1a1789c3e1e80c8", "size": "1768", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/System.Extensions/IO/FileInfo2.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "244050" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title></title> <link rel="stylesheet" href="../fpdoc.css" type="text/css"> </head> <body> <table cellpadding="0" cellspacing="0"> <tr> <td><p>&nbsp;</p></td> <td><p></p></td> <td nowrap="nowrap"><p><a href="../qbtorrentstrackers/tqbtorrentstrackersenumerator.create.html" onClick="opener.location.href = '../qbtorrentstrackers/tqbtorrentstrackersenumerator.create.html'; return false;">Create</a> (<a href="../qbtorrentstrackers/tqbtorrentstrackersenumerator.html" onClick="opener.location.href = '../qbtorrentstrackers/tqbtorrentstrackersenumerator.html'; return false;">TqBTorrentsTrackersEnumerator</a>)</p></td> </tr> <tr> <td><p>&nbsp;</p></td> <td><p></p></td> <td nowrap="nowrap"><p><a href="../qbtorrentstrackers/tqbtorrentstrackersenumerator.getcurrent.html" onClick="opener.location.href = '../qbtorrentstrackers/tqbtorrentstrackersenumerator.getcurrent.html'; return false;">GetCurrent</a> (<a href="../qbtorrentstrackers/tqbtorrentstrackersenumerator.html" onClick="opener.location.href = '../qbtorrentstrackers/tqbtorrentstrackersenumerator.html'; return false;">TqBTorrentsTrackersEnumerator</a>)</p></td> </tr> <tr> <td><p>&nbsp;</p></td> <td><p></p></td> <td nowrap="nowrap"><p><a href="../qbtorrentstrackers/tqbtorrentstrackersenumerator.movenext.html" onClick="opener.location.href = '../qbtorrentstrackers/tqbtorrentstrackersenumerator.movenext.html'; return false;">MoveNext</a> (<a href="../qbtorrentstrackers/tqbtorrentstrackersenumerator.html" onClick="opener.location.href = '../qbtorrentstrackers/tqbtorrentstrackersenumerator.html'; return false;">TqBTorrentsTrackersEnumerator</a>)</p></td> </tr> </table> </body> </html>
{ "content_hash": "e7320f77f1637f910f02d05772b173af", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 452, "avg_line_length": 65.57142857142857, "alnum_prop": 0.7440087145969498, "repo_name": "gcarreno/laz-qBitTorrent-WebUI", "id": "6ba465a0dff0965e69405461aeec2ea00362343a", "size": "1836", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/html/qbtorrentstrackers/tqbtorrentstrackersenumerator-4.html", "mode": "33188", "license": "mit", "language": [ { "name": "Pascal", "bytes": "149647" }, { "name": "Python", "bytes": "7134" }, { "name": "Shell", "bytes": "1704" } ], "symlink_target": "" }
package aws import ( "fmt" "log" "reflect" "regexp" "sort" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/elasticbeanstalk" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" "github.com/hashicorp/terraform/terraform" ) func TestAccAWSBeanstalkEnv_basic(t *testing.T) { var app elasticbeanstalk.EnvironmentDescription rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckBeanstalkEnvDestroy, Steps: []resource.TestStep{ { Config: testAccBeanstalkEnvConfig(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.tfenvtest", &app), ), }, }, }) } func TestAccAWSBeanstalkEnv_tier(t *testing.T) { var app elasticbeanstalk.EnvironmentDescription beanstalkQueuesNameRegexp := regexp.MustCompile("https://sqs.+?awseb[^,]+") rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckBeanstalkEnvDestroy, Steps: []resource.TestStep{ { Config: testAccBeanstalkWorkerEnvConfig(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvTier("aws_elastic_beanstalk_environment.tfenvtest", &app), resource.TestMatchResourceAttr( "aws_elastic_beanstalk_environment.tfenvtest", "queues.0", beanstalkQueuesNameRegexp), ), }, }, }) } func TestAccAWSBeanstalkEnv_outputs(t *testing.T) { var app elasticbeanstalk.EnvironmentDescription rInt := acctest.RandInt() beanstalkAsgNameRegexp := regexp.MustCompile("awseb.+?AutoScalingGroup[^,]+") beanstalkElbNameRegexp := regexp.MustCompile("awseb.+?EBLoa[^,]+") beanstalkInstancesNameRegexp := regexp.MustCompile("i-([0-9a-fA-F]{8}|[0-9a-fA-F]{17})") beanstalkLcNameRegexp := regexp.MustCompile("awseb.+?AutoScalingLaunch[^,]+") resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckBeanstalkEnvDestroy, Steps: []resource.TestStep{ { Config: testAccBeanstalkEnvConfig(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.tfenvtest", &app), resource.TestMatchResourceAttr( "aws_elastic_beanstalk_environment.tfenvtest", "autoscaling_groups.0", beanstalkAsgNameRegexp), resource.TestMatchResourceAttr( "aws_elastic_beanstalk_environment.tfenvtest", "load_balancers.0", beanstalkElbNameRegexp), resource.TestMatchResourceAttr( "aws_elastic_beanstalk_environment.tfenvtest", "instances.0", beanstalkInstancesNameRegexp), resource.TestMatchResourceAttr( "aws_elastic_beanstalk_environment.tfenvtest", "launch_configurations.0", beanstalkLcNameRegexp), ), }, }, }) } func TestAccAWSBeanstalkEnv_cname_prefix(t *testing.T) { var app elasticbeanstalk.EnvironmentDescription cnamePrefix := acctest.RandString(8) rInt := acctest.RandInt() beanstalkCnameRegexp := regexp.MustCompile("^" + cnamePrefix + ".+?elasticbeanstalk.com$") resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckBeanstalkEnvDestroy, Steps: []resource.TestStep{ { Config: testAccBeanstalkEnvCnamePrefixConfig(cnamePrefix, rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.tfenvtest", &app), resource.TestMatchResourceAttr( "aws_elastic_beanstalk_environment.tfenvtest", "cname", beanstalkCnameRegexp), ), }, }, }) } func TestAccAWSBeanstalkEnv_config(t *testing.T) { var app elasticbeanstalk.EnvironmentDescription rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckBeanstalkEnvDestroy, Steps: []resource.TestStep{ { Config: testAccBeanstalkConfigTemplate(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.tftest", &app), testAccCheckBeanstalkEnvConfigValue("aws_elastic_beanstalk_environment.tftest", "1"), ), }, { Config: testAccBeanstalkConfigTemplateUpdate(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.tftest", &app), testAccCheckBeanstalkEnvConfigValue("aws_elastic_beanstalk_environment.tftest", "2"), ), }, { Config: testAccBeanstalkConfigTemplateUpdate(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.tftest", &app), testAccCheckBeanstalkEnvConfigValue("aws_elastic_beanstalk_environment.tftest", "3"), ), }, }, }) } func TestAccAWSBeanstalkEnv_resource(t *testing.T) { var app elasticbeanstalk.EnvironmentDescription rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckBeanstalkEnvDestroy, Steps: []resource.TestStep{ { Config: testAccBeanstalkResourceOptionSetting(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.tfenvtest", &app), ), }, }, }) } func TestAccAWSBeanstalkEnv_vpc(t *testing.T) { var app elasticbeanstalk.EnvironmentDescription rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckBeanstalkEnvDestroy, Steps: []resource.TestStep{ { Config: testAccBeanstalkEnv_VPC(acctest.RandString(5), rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.default", &app), ), }, }, }) } func TestAccAWSBeanstalkEnv_template_change(t *testing.T) { var app elasticbeanstalk.EnvironmentDescription rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckBeanstalkEnvDestroy, Steps: []resource.TestStep{ { Config: testAccBeanstalkEnv_TemplateChange_stack(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.environment", &app), ), }, { Config: testAccBeanstalkEnv_TemplateChange_temp(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.environment", &app), ), }, { Config: testAccBeanstalkEnv_TemplateChange_stack(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.environment", &app), ), }, }, }) } func TestAccAWSBeanstalkEnv_basic_settings_update(t *testing.T) { var app elasticbeanstalk.EnvironmentDescription rInt := acctest.RandInt() resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckBeanstalkEnvDestroy, Steps: []resource.TestStep{ { Config: testAccBeanstalkEnvConfig_empty_settings(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.tfenvtest", &app), testAccVerifyBeanstalkConfig(&app, []string{}), ), }, { Config: testAccBeanstalkEnvConfig_settings(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.tfenvtest", &app), testAccVerifyBeanstalkConfig(&app, []string{"ENV_STATIC", "ENV_UPDATE"}), ), }, { Config: testAccBeanstalkEnvConfig_settings_update(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.tfenvtest", &app), testAccVerifyBeanstalkConfig(&app, []string{"ENV_STATIC", "ENV_UPDATE"}), ), }, { Config: testAccBeanstalkEnvConfig_empty_settings(rInt), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkEnvExists("aws_elastic_beanstalk_environment.tfenvtest", &app), testAccVerifyBeanstalkConfig(&app, []string{}), ), }, }, }) } func TestAccAWSBeanstalkEnv_version_label(t *testing.T) { var app elasticbeanstalk.EnvironmentDescription resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckBeanstalkEnvDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccBeanstalkEnvApplicationVersionConfig(acctest.RandInt()), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkApplicationVersionDeployed("aws_elastic_beanstalk_environment.default", &app), ), }, resource.TestStep{ Config: testAccBeanstalkEnvApplicationVersionConfigUpdate(acctest.RandInt()), Check: resource.ComposeTestCheckFunc( testAccCheckBeanstalkApplicationVersionDeployed("aws_elastic_beanstalk_environment.default", &app), ), }, }, }) } func testAccVerifyBeanstalkConfig(env *elasticbeanstalk.EnvironmentDescription, expected []string) resource.TestCheckFunc { return func(s *terraform.State) error { if env == nil { return fmt.Errorf("Nil environment in testAccVerifyBeanstalkConfig") } conn := testAccProvider.Meta().(*AWSClient).elasticbeanstalkconn resp, err := conn.DescribeConfigurationSettings(&elasticbeanstalk.DescribeConfigurationSettingsInput{ ApplicationName: env.ApplicationName, EnvironmentName: env.EnvironmentName, }) if err != nil { return fmt.Errorf("Error describing config settings in testAccVerifyBeanstalkConfig: %s", err) } // should only be 1 environment if len(resp.ConfigurationSettings) != 1 { return fmt.Errorf("Expected only 1 set of Configuration Settings in testAccVerifyBeanstalkConfig, got (%d)", len(resp.ConfigurationSettings)) } cs := resp.ConfigurationSettings[0] var foundEnvs []string testStrings := []string{"ENV_STATIC", "ENV_UPDATE"} for _, os := range cs.OptionSettings { for _, k := range testStrings { if *os.OptionName == k { foundEnvs = append(foundEnvs, k) } } } // if expected is zero, then we should not have found any of the predefined // env vars if len(expected) == 0 { if len(foundEnvs) > 0 { return fmt.Errorf("Found configs we should not have: %#v", foundEnvs) } return nil } sort.Strings(testStrings) sort.Strings(expected) if !reflect.DeepEqual(testStrings, expected) { return fmt.Errorf("Error matching strings, expected:\n\n%#v\n\ngot:\n\n%#v\n", testStrings, foundEnvs) } return nil } } func testAccCheckBeanstalkEnvDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).elasticbeanstalkconn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_elastic_beanstalk_environment" { continue } // Try to find the environment describeBeanstalkEnvOpts := &elasticbeanstalk.DescribeEnvironmentsInput{ EnvironmentIds: []*string{aws.String(rs.Primary.ID)}, } resp, err := conn.DescribeEnvironments(describeBeanstalkEnvOpts) if err == nil { switch { case len(resp.Environments) > 1: return fmt.Errorf("Error %d environments match, expected 1", len(resp.Environments)) case len(resp.Environments) == 1: if *resp.Environments[0].Status == "Terminated" { return nil } return fmt.Errorf("Elastic Beanstalk ENV still exists.") default: return nil } } // Verify the error is what we want ec2err, ok := err.(awserr.Error) if !ok { return err } if ec2err.Code() != "InvalidBeanstalkEnvID.NotFound" { return err } } return nil } func testAccCheckBeanstalkEnvExists(n string, app *elasticbeanstalk.EnvironmentDescription) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("Elastic Beanstalk ENV is not set") } env, err := describeBeanstalkEnv(testAccProvider.Meta().(*AWSClient).elasticbeanstalkconn, aws.String(rs.Primary.ID)) if err != nil { return err } *app = *env return nil } } func testAccCheckBeanstalkEnvTier(n string, app *elasticbeanstalk.EnvironmentDescription) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("Elastic Beanstalk ENV is not set") } env, err := describeBeanstalkEnv(testAccProvider.Meta().(*AWSClient).elasticbeanstalkconn, aws.String(rs.Primary.ID)) if err != nil { return err } if *env.Tier.Name != "Worker" { return fmt.Errorf("Beanstalk Environment tier is %s, expected Worker", *env.Tier.Name) } *app = *env return nil } } func testAccCheckBeanstalkEnvConfigValue(n string, expectedValue string) resource.TestCheckFunc { return func(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).elasticbeanstalkconn rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("Elastic Beanstalk ENV is not set") } resp, err := conn.DescribeConfigurationOptions(&elasticbeanstalk.DescribeConfigurationOptionsInput{ ApplicationName: aws.String(rs.Primary.Attributes["application"]), EnvironmentName: aws.String(rs.Primary.Attributes["name"]), Options: []*elasticbeanstalk.OptionSpecification{ { Namespace: aws.String("aws:elasticbeanstalk:application:environment"), OptionName: aws.String("TEMPLATE"), }, }, }) if err != nil { return err } if len(resp.Options) != 1 { return fmt.Errorf("Found %d options, expected 1.", len(resp.Options)) } log.Printf("[DEBUG] %d Elastic Beanstalk Option values returned.", len(resp.Options[0].ValueOptions)) for _, value := range resp.Options[0].ValueOptions { if *value != expectedValue { return fmt.Errorf("Option setting value: %s. Expected %s", *value, expectedValue) } } return nil } } func testAccCheckBeanstalkApplicationVersionDeployed(n string, app *elasticbeanstalk.EnvironmentDescription) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("Elastic Beanstalk ENV is not set") } env, err := describeBeanstalkEnv(testAccProvider.Meta().(*AWSClient).elasticbeanstalkconn, aws.String(rs.Primary.ID)) if err != nil { return err } if *env.VersionLabel != rs.Primary.Attributes["version_label"] { return fmt.Errorf("Elastic Beanstalk version deployed %s. Expected %s", *env.VersionLabel, rs.Primary.Attributes["version_label"]) } *app = *env return nil } } func describeBeanstalkEnv(conn *elasticbeanstalk.ElasticBeanstalk, envID *string) (*elasticbeanstalk.EnvironmentDescription, error) { describeBeanstalkEnvOpts := &elasticbeanstalk.DescribeEnvironmentsInput{ EnvironmentIds: []*string{envID}, } log.Printf("[DEBUG] Elastic Beanstalk Environment TEST describe opts: %s", describeBeanstalkEnvOpts) resp, err := conn.DescribeEnvironments(describeBeanstalkEnvOpts) if err != nil { return &elasticbeanstalk.EnvironmentDescription{}, err } if len(resp.Environments) == 0 { return &elasticbeanstalk.EnvironmentDescription{}, fmt.Errorf("Elastic Beanstalk ENV not found.") } if len(resp.Environments) > 1 { return &elasticbeanstalk.EnvironmentDescription{}, fmt.Errorf("Found %d environments, expected 1.", len(resp.Environments)) } return resp.Environments[0], nil } func testAccBeanstalkEnvConfig(rInt int) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_environment" "tfenvtest" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.tftest.name}" solution_stack_name = "64bit Amazon Linux running Python" depends_on = ["aws_elastic_beanstalk_application.tftest"] } `, rInt, rInt) } func testAccBeanstalkEnvConfig_empty_settings(r int) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_environment" "tfenvtest" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.tftest.name}" solution_stack_name = "64bit Amazon Linux running Python" wait_for_ready_timeout = "15m" }`, r, r) } func testAccBeanstalkEnvConfig_settings(r int) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_environment" "tfenvtest" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.tftest.name}" solution_stack_name = "64bit Amazon Linux running Python" wait_for_ready_timeout = "15m" setting { namespace = "aws:elasticbeanstalk:application:environment" name = "ENV_STATIC" value = "true" } setting { namespace = "aws:elasticbeanstalk:application:environment" name = "ENV_UPDATE" value = "true" } setting { namespace = "aws:elasticbeanstalk:application:environment" name = "ENV_REMOVE" value = "true" } setting { namespace = "aws:autoscaling:scheduledaction" resource = "ScheduledAction01" name = "MinSize" value = 2 } setting { namespace = "aws:autoscaling:scheduledaction" resource = "ScheduledAction01" name = "MaxSize" value = 3 } setting { namespace = "aws:autoscaling:scheduledaction" resource = "ScheduledAction01" name = "StartTime" value = "2016-07-28T04:07:02Z" } }`, r, r) } func testAccBeanstalkEnvConfig_settings_update(r int) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_environment" "tfenvtest" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.tftest.name}" solution_stack_name = "64bit Amazon Linux running Python" wait_for_ready_timeout = "15m" setting { namespace = "aws:elasticbeanstalk:application:environment" name = "ENV_STATIC" value = "true" } setting { namespace = "aws:elasticbeanstalk:application:environment" name = "ENV_UPDATE" value = "false" } setting { namespace = "aws:elasticbeanstalk:application:environment" name = "ENV_ADD" value = "true" } setting { namespace = "aws:autoscaling:scheduledaction" resource = "ScheduledAction01" name = "MinSize" value = 2 } setting { namespace = "aws:autoscaling:scheduledaction" resource = "ScheduledAction01" name = "MaxSize" value = 3 } setting { namespace = "aws:autoscaling:scheduledaction" resource = "ScheduledAction01" name = "StartTime" value = "2016-07-28T04:07:02Z" } }`, r, r) } func testAccBeanstalkWorkerEnvConfig(rInt int) string { return fmt.Sprintf(` resource "aws_iam_instance_profile" "tftest" { name = "tftest_profile-%d" roles = ["${aws_iam_role.tftest.name}"] } resource "aws_iam_role" "tftest" { name = "tftest_role" path = "/" assume_role_policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sts:AssumeRole\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Effect\":\"Allow\",\"Sid\":\"\"}]}" } resource "aws_iam_role_policy" "tftest" { name = "tftest_policy" role = "${aws_iam_role.tftest.id}" policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"QueueAccess\",\"Action\":[\"sqs:ChangeMessageVisibility\",\"sqs:DeleteMessage\",\"sqs:ReceiveMessage\"],\"Effect\":\"Allow\",\"Resource\":\"*\"}]}" } resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_environment" "tfenvtest" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.tftest.name}" tier = "Worker" solution_stack_name = "64bit Amazon Linux running Python" setting { namespace = "aws:autoscaling:launchconfiguration" name = "IamInstanceProfile" value = "${aws_iam_instance_profile.tftest.name}" } }`, rInt, rInt, rInt) } func testAccBeanstalkEnvCnamePrefixConfig(randString string, rInt int) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_environment" "tfenvtest" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.tftest.name}" cname_prefix = "%s" solution_stack_name = "64bit Amazon Linux running Python" } `, rInt, rInt, randString) } func testAccBeanstalkConfigTemplate(rInt int) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_environment" "tftest" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.tftest.name}" template_name = "${aws_elastic_beanstalk_configuration_template.tftest.name}" } resource "aws_elastic_beanstalk_configuration_template" "tftest" { name = "tf-test-original" application = "${aws_elastic_beanstalk_application.tftest.name}" solution_stack_name = "64bit Amazon Linux running Python" setting { namespace = "aws:elasticbeanstalk:application:environment" name = "TEMPLATE" value = "1" } } `, rInt, rInt) } func testAccBeanstalkConfigTemplateUpdate(rInt int) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_environment" "tftest" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.tftest.name}" template_name = "${aws_elastic_beanstalk_configuration_template.tftest.name}" } resource "aws_elastic_beanstalk_configuration_template" "tftest" { name = "tf-test-updated" application = "${aws_elastic_beanstalk_application.tftest.name}" solution_stack_name = "64bit Amazon Linux running Python" setting { namespace = "aws:elasticbeanstalk:application:environment" name = "TEMPLATE" value = "2" } } `, rInt, rInt) } func testAccBeanstalkResourceOptionSetting(rInt int) string { return fmt.Sprintf(` resource "aws_elastic_beanstalk_application" "tftest" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_environment" "tfenvtest" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.tftest.name}" solution_stack_name = "64bit Amazon Linux running Python" setting { namespace = "aws:autoscaling:scheduledaction" resource = "ScheduledAction01" name = "MinSize" value = "2" } setting { namespace = "aws:autoscaling:scheduledaction" resource = "ScheduledAction01" name = "MaxSize" value = "6" } setting { namespace = "aws:autoscaling:scheduledaction" resource = "ScheduledAction01" name = "Recurrence" value = "0 8 * * *" } }`, rInt, rInt) } func testAccBeanstalkEnv_VPC(name string, rInt int) string { return fmt.Sprintf(` resource "aws_vpc" "tf_b_test" { cidr_block = "10.0.0.0/16" } resource "aws_internet_gateway" "tf_b_test" { vpc_id = "${aws_vpc.tf_b_test.id}" } resource "aws_route" "r" { route_table_id = "${aws_vpc.tf_b_test.main_route_table_id}" destination_cidr_block = "0.0.0.0/0" gateway_id = "${aws_internet_gateway.tf_b_test.id}" } resource "aws_subnet" "main" { vpc_id = "${aws_vpc.tf_b_test.id}" cidr_block = "10.0.0.0/24" } resource "aws_security_group" "default" { name = "tf-b-test-%s" vpc_id = "${aws_vpc.tf_b_test.id}" } resource "aws_elastic_beanstalk_application" "default" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_environment" "default" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.default.name}" solution_stack_name = "64bit Amazon Linux running Python" setting { namespace = "aws:ec2:vpc" name = "VPCId" value = "${aws_vpc.tf_b_test.id}" } setting { namespace = "aws:ec2:vpc" name = "Subnets" value = "${aws_subnet.main.id}" } setting { namespace = "aws:ec2:vpc" name = "AssociatePublicIpAddress" value = "true" } setting { namespace = "aws:autoscaling:launchconfiguration" name = "SecurityGroups" value = "${aws_security_group.default.id}" } } `, name, rInt, rInt) } func testAccBeanstalkEnv_TemplateChange_stack(r int) string { return fmt.Sprintf(` provider "aws" { region = "us-east-1" } resource "aws_elastic_beanstalk_application" "app" { name = "beanstalk-app-%d" description = "" } resource "aws_elastic_beanstalk_environment" "environment" { name = "beanstalk-env-%d" application = "${aws_elastic_beanstalk_application.app.name}" # Go 1.4 solution_stack_name = "64bit Amazon Linux 2016.03 v2.1.0 running Go 1.4" } resource "aws_elastic_beanstalk_configuration_template" "template" { name = "beanstalk-config-%d" application = "${aws_elastic_beanstalk_application.app.name}" # Go 1.5 solution_stack_name = "64bit Amazon Linux 2016.03 v2.1.3 running Go 1.5" } `, r, r, r) } func testAccBeanstalkEnv_TemplateChange_temp(r int) string { return fmt.Sprintf(` provider "aws" { region = "us-east-1" } resource "aws_elastic_beanstalk_application" "app" { name = "beanstalk-app-%d" description = "" } resource "aws_elastic_beanstalk_environment" "environment" { name = "beanstalk-env-%d" application = "${aws_elastic_beanstalk_application.app.name}" # Go 1.4 template_name = "${aws_elastic_beanstalk_configuration_template.template.name}" } resource "aws_elastic_beanstalk_configuration_template" "template" { name = "beanstalk-config-%d" application = "${aws_elastic_beanstalk_application.app.name}" # Go 1.5 solution_stack_name = "64bit Amazon Linux 2016.03 v2.1.3 running Go 1.5" } `, r, r, r) } func testAccBeanstalkEnvApplicationVersionConfig(randInt int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "default" { bucket = "tftest.applicationversion.buckets-%d" } resource "aws_s3_bucket_object" "default" { bucket = "${aws_s3_bucket.default.id}" key = "python-v1.zip" source = "test-fixtures/python-v1.zip" } resource "aws_elastic_beanstalk_application" "default" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_application_version" "default" { application = "tf-test-name-%d" name = "tf-test-version-label" bucket = "${aws_s3_bucket.default.id}" key = "${aws_s3_bucket_object.default.id}" } resource "aws_elastic_beanstalk_environment" "default" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.default.name}" version_label = "${aws_elastic_beanstalk_application_version.default.name}" solution_stack_name = "64bit Amazon Linux running Python" } `, randInt, randInt, randInt, randInt) } func testAccBeanstalkEnvApplicationVersionConfigUpdate(randInt int) string { return fmt.Sprintf(` resource "aws_s3_bucket" "default" { bucket = "tftest.applicationversion.buckets-%d" } resource "aws_s3_bucket_object" "default" { bucket = "${aws_s3_bucket.default.id}" key = "python-v2.zip" source = "test-fixtures/python-v1.zip" } resource "aws_elastic_beanstalk_application" "default" { name = "tf-test-name-%d" description = "tf-test-desc" } resource "aws_elastic_beanstalk_application_version" "default" { application = "tf-test-name-%d" name = "tf-test-version-label-v2" bucket = "${aws_s3_bucket.default.id}" key = "${aws_s3_bucket_object.default.id}" } resource "aws_elastic_beanstalk_environment" "default" { name = "tf-test-name-%d" application = "${aws_elastic_beanstalk_application.default.name}" version_label = "${aws_elastic_beanstalk_application_version.default.name}" solution_stack_name = "64bit Amazon Linux running Python" } `, randInt, randInt, randInt, randInt) }
{ "content_hash": "e7fde310cafa20e73a268f3a476159ec", "timestamp": "", "source": "github", "line_count": 991, "max_line_length": 213, "avg_line_length": 29.376387487386477, "alnum_prop": 0.7017037647705413, "repo_name": "stardog-union/stardog-graviton", "id": "2a3b1e7629807e5542ce98d92966a96d097a3413", "size": "29112", "binary": false, "copies": "36", "ref": "refs/heads/develop", "path": "vendor/github.com/hashicorp/terraform/builtin/providers/aws/resource_aws_elastic_beanstalk_environment_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "BitBake", "bytes": "50002" }, { "name": "Dockerfile", "bytes": "1212" }, { "name": "Go", "bytes": "195457" }, { "name": "HCL", "bytes": "26587" }, { "name": "Makefile", "bytes": "602" }, { "name": "Python", "bytes": "43992" }, { "name": "Shell", "bytes": "11173" }, { "name": "Smarty", "bytes": "2192" } ], "symlink_target": "" }
import datetime import tzlocal def now_tz(): """Get the current local time as a time zone aware datetime.""" now = datetime.datetime.now(datetime.timezone.utc) return now.astimezone() def start_of_day_tz(): """Get the start of the current day as a time zone aware datetime.""" now = now_tz() return now.replace(hour=0, minute=0, second=0, microsecond=0) def end_of_day_tz(): """Get the end of the current day as a time zone aware datetime.""" now = now_tz() return now.replace(hour=23, minute=59, second=59, microsecond=9999) def parse_date_tz(date): """Parse an ISO8601 date string returning a time zone aware datetime. If you want parsing of times and time zones, try the dateutil package. """ parsed = datetime.datetime.strptime(date, "%Y-%m-%d") time_zone = tzlocal.get_localzone() return time_zone.localize(parsed)
{ "content_hash": "d03515cbb9d79fbaa588e5a8a8dd962c", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 74, "avg_line_length": 28.70967741935484, "alnum_prop": 0.6786516853932584, "repo_name": "genericmoniker/mirror", "id": "3aae291621ab952beb7c8700d2d4ac1e436929a2", "size": "890", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "backend/src/mirror/plugins/calendars/datetime_utils.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31880" }, { "name": "Dockerfile", "bytes": "3441" }, { "name": "HTML", "bytes": "15567" }, { "name": "JavaScript", "bytes": "8782" }, { "name": "Python", "bytes": "66404" }, { "name": "Riot", "bytes": "179" }, { "name": "Shell", "bytes": "3851" }, { "name": "Svelte", "bytes": "33588" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us"> <head> <link href="http://gmpg.org/xfn/11" rel="profile"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="generator" content="Hugo 0.16-DEV" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"> <title>control loop at html template in golang &middot; 钱国正博客</title> <link rel="stylesheet" href="/css/monokai.css"> <script src="/js/highlight.pack.js"></script> <script>hljs.initHighlightingOnLoad();</script> <link rel="stylesheet" href="https://qianguozheng.github.io/css/poole.css"> <link rel="stylesheet" href="https://qianguozheng.github.io/css/syntax.css"> <link rel="stylesheet" href="https://qianguozheng.github.io/css/hyde.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/apple-touch-icon-144-precomposed.png"> <link rel="shortcut icon" href="/favicon.png"> <link href="" rel="alternate" type="application/rss+xml" title="钱国正博客" /> </head> <body class="theme-base-08 "> <div class="sidebar"> <div class="container sidebar-sticky"> <div class="sidebar-about"> <a href="https://qianguozheng.github.io/"><h1>钱国正博客</h1></a> <p class="lead"> An elegant open source and mobile first theme for <a href="http://hugo.spf13.com">hugo</a> made by <a href="http://twitter.com/mdo">@mdo</a>. Originally made for Jekyll. </p> </div> <ul class="sidebar-nav"> <li><a href="/">Home</a> </li> <li><a href="/post/Golang-gorilla-context-doc/"> Golang gorilla context doc </a></li> <li><a href="/post/Golang-gorilla-mux/"> Golang gorilla mux </a></li> <li><a href="/post/Golang-introducing-HTTP-tracing/"> Golang introducing HTTP tracing </a></li> <li><a href="/post/golang-iotuils-devnull-deserve-deep-thinking/"> Golang iotuils devnull deserve deep thinking </a></li> <li><a href="/post/Golang-recover-usage/"> Golang recover usage </a></li> <li><a href="/post/Golang-session-problem/"> Golang session problem </a></li> <li><a href="/post/Linux-getsockopt-sample-usage/"> Linux getsockopt sample usage </a></li> <li><a href="/post/control-loop-at-html-template-in-golang/"> control loop at html template in golang </a></li> <li><a href="/post/go-ethereum-create-your-own-account/"> go ethereum create your own account </a></li> <li><a href="/post/go-ethereum-cypto-private-public-key/"> go ethereum crypto private public key </a></li> <li><a href="/post/hugo-deploy-as-submodule-on-github/"> hugo deploy as submodule on github </a></li> <li><a href="/post/netfilter-xt_recent/"> netfilter xt_recent </a></li> </ul> <p>&copy; 2018. All rights reserved. </p> </div> </div> <div class="content container"> <div class="post"> <h1>control loop at html template in golang</h1> <span class="post-date">Mon, Jul 30, 2018</span> <p>最近用go实现了一个管理后台,主要用来做一些路由器的配置,远程管理这些设备。</p> <p>其中有一个功能是设计到循环的,所以采用了俄slice传递参数到html模板里面,但是这些参数是固定的,而且模板不好控制循环遍历slice, 所以写了个全局变量来控制</p> <p>样例如下,想要输出想要的,不容易控制</p> <pre><code>{{range .Slice}} &lt;a&gt;print anything you want&lt;/a&gt; {{end}} </code></pre> <h2 id="实现:e6c67e8e87b403703afbcaee78be5537">实现</h2> <pre><code>type FuncMap map[string]interface{} 定义几个模板函数 template.FuncMap { &quot;var&quot;: newVar, &quot;set&quot;: setVar, &quot;cmp&quot;: cmpVar, } //声明模板的全局变量 func newVar(v interface{})(*interface{}, error) { x := interface{}(v) return &amp;x, nil } //赋值模板的全局变量 func setVar(x *interface{}, v interface{}) (string, error) { *x = v return &quot;&quot;, nil } //对比全局变量,这里和int类型对比 func cmpVar(x *interface{}, e int) bool { return (*x).(int) == e } //使用 {{$global_var := var 0}} {{range $k,$v := .Slice}} {{if eq $v.Port 0}} &lt;a&gt;print something&lt;/a&gt; {{set $global_var 1}} {{end}} {{if cmp $global_var 1}} &lt;a&gt;do another logic&lt;/a&gt; {{end}} {{end}} </code></pre> </div> <h2>Comments</h2> <div id="disqus_thread"></div> <script type="text/javascript"> var disqus_shortname = 'spf13'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </div> </body> </html>
{ "content_hash": "8041337a9956a1bfd2930d539f82675d", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 175, "avg_line_length": 31.471337579617835, "alnum_prop": 0.6292248532685691, "repo_name": "qianguozheng/qianguozheng.github.io", "id": "6cfb7a11680880845f8fa0fdcd838340cb066edb", "size": "5303", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "post/control-loop-at-html-template-in-golang/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "47840" }, { "name": "HTML", "bytes": "234187" }, { "name": "Shell", "bytes": "403" } ], "symlink_target": "" }
package org.uberfire.ext.wires.core.api.events; import org.uberfire.ext.wires.core.api.shapes.WiresBaseShape; public class ShapeDeletedEvent { private WiresBaseShape shape; public ShapeDeletedEvent( final WiresBaseShape shape ) { this.shape = shape; } public WiresBaseShape getShape() { return shape; } }
{ "content_hash": "5080a574190875b8ecf9156e5085686b", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 61, "avg_line_length": 19.333333333333332, "alnum_prop": 0.7040229885057471, "repo_name": "wmedvede/uberfire-extensions", "id": "47cae56eb16b7cd5ef6ea7b25d28205ba2250ed9", "size": "942", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "uberfire-wires/uberfire-wires-core/uberfire-wires-core-api/src/main/java/org/uberfire/ext/wires/core/api/events/ShapeDeletedEvent.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "28345" }, { "name": "HTML", "bytes": "1238" }, { "name": "Java", "bytes": "2453542" }, { "name": "JavaScript", "bytes": "19547" } ], "symlink_target": "" }
require 'test_helper' class Api::ApidocsControllerTest < ActionController::TestCase test 'should get index' do get :index assert_response :success assert_template :index assert_equal 'Unipept API', assigns(:title) assert_equal 'Overview', assigns(:sidebar_name) assert_not_nil assigns(:sidebar_nav) assert_nil assigns(:sidebar_subnav) end test 'should get pept2prot' do get :pept2prot assert_response :success assert_template :pept2prot assert_equal 'pept2prot', assigns(:title) assert_equal 'pept2prot', assigns(:sidebar_name) assert_not_nil assigns(:sidebar_nav) assert_not_nil assigns(:sidebar_subnav) end test 'should get pept2taxa' do get :pept2taxa assert_response :success assert_template :pept2taxa assert_equal 'pept2taxa', assigns(:title) assert_equal 'pept2taxa', assigns(:sidebar_name) assert_not_nil assigns(:sidebar_nav) assert_not_nil assigns(:sidebar_subnav) end test 'should get pept2lca' do get :pept2lca assert_response :success assert_template :pept2lca assert_equal 'pept2lca', assigns(:title) assert_equal 'pept2lca', assigns(:sidebar_name) assert_not_nil assigns(:sidebar_nav) assert_not_nil assigns(:sidebar_subnav) end test 'should get taxa2lca' do get :taxa2lca assert_response :success assert_template :taxa2lca assert_equal 'taxa2lca', assigns(:title) assert_equal 'taxa2lca', assigns(:sidebar_name) assert_not_nil assigns(:sidebar_nav) assert_not_nil assigns(:sidebar_subnav) end test 'should get taxonomy' do get :taxonomy assert_response :success assert_template :taxonomy assert_equal 'taxonomy', assigns(:title) assert_equal 'taxonomy', assigns(:sidebar_name) assert_not_nil assigns(:sidebar_nav) assert_not_nil assigns(:sidebar_subnav) end end
{ "content_hash": "b63ec072b2c383c38b63dd14df6b72b8", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 61, "avg_line_length": 29.77777777777778, "alnum_prop": 0.7073560767590619, "repo_name": "bmesuere/uni-test", "id": "3661e0862ca853e58e14ebab8958ec6b3202d7c4", "size": "1876", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "test/controllers/api/apidocs_controller_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "53054" }, { "name": "HTML", "bytes": "627682" }, { "name": "Java", "bytes": "57174" }, { "name": "JavaScript", "bytes": "429970" }, { "name": "PLpgSQL", "bytes": "12177" }, { "name": "Ruby", "bytes": "259640" }, { "name": "Shell", "bytes": "8842" } ], "symlink_target": "" }
<?php namespace Magento\Downloadable\Controller\Adminhtml\Downloadable\Product\Edit; class Upsell extends \Magento\Catalog\Controller\Adminhtml\Product\Upsell { }
{ "content_hash": "b4028ae69fb0c1811838df6a5d2c5bdc", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 78, "avg_line_length": 23.571428571428573, "alnum_prop": 0.8303030303030303, "repo_name": "j-froehlich/magento2_wk", "id": "569c83e9a2b281504dd421ebcb0259865a93c577", "size": "276", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/magento/module-downloadable/Controller/Adminhtml/Downloadable/Product/Edit/Upsell.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "13636" }, { "name": "CSS", "bytes": "2076720" }, { "name": "HTML", "bytes": "6151072" }, { "name": "JavaScript", "bytes": "2488727" }, { "name": "PHP", "bytes": "12466046" }, { "name": "Shell", "bytes": "6088" }, { "name": "XSLT", "bytes": "19979" } ], "symlink_target": "" }
namespace AForge.Robotics.Lego.Internals { using System; using System.IO; using System.IO.Ports; /// <summary> /// Implementation of serial communication interface with LEGO Mindstorm NXT brick. /// </summary> /// internal class SerialCommunication : INXTCommunicationInterface { // serial port for communication with NXT brick SerialPort port = null; /// <summary> /// Maximum message size, which can be sent over this communication interface to NXT /// brick. /// </summary> /// public const int MaxMessageSize = 64; /// <summary> /// Serial port name used for communication. /// </summary> /// public string PortName { get { return port.PortName; } } /// <summary> /// Get connection status. /// </summary> /// public bool IsConnected { get { return port.IsOpen; } } /// <summary> /// Initializes a new instance of the <see cref="SerialCommunication"/> class. /// </summary> /// /// <param name="portName">Serial port name to use for communication.</param> /// /// <remarks>This constructor initializes serial port with default write and read /// timeout values, which are 1000 milliseconds.</remarks> /// public SerialCommunication( string portName ) : this( portName, 1000, 1000 ) { } /// <summary> /// Initializes a new instance of the <see cref="SerialCommunication"/> class. /// </summary> /// /// <param name="portName">Serial port name to use for communication.</param> /// <param name="writeTimeout">Timeout value used for write operations.</param> /// <param name="readTimeout">Timeout value used for read operations.</param> /// public SerialCommunication( string portName, int writeTimeout, int readTimeout ) { this.port = new SerialPort( portName ); this.port.WriteTimeout = writeTimeout; this.port.ReadTimeout = readTimeout; this.port.BaudRate = 115200; this.port.DataBits = 8; this.port.StopBits = StopBits.One; this.port.Parity = Parity.None; this.port.RtsEnable = true; this.port.DtrEnable = true; } /// <summary> /// Connect to NXT brick. /// </summary> /// /// <returns>Returns <b>true</b> if connection was established successfully or <b>false</b> /// otherwise.</returns> /// /// <remarks>If communication interface was connected before the call, existing connection will be reused. /// If it is required to force reconnection, then <see cref="Disconnect"/> method should be called before. /// </remarks> /// public bool Connect( ) { if ( !port.IsOpen ) { // try to connect try { port.Open( ); } catch { return false; } } return true; } /// <summary> /// Disconnect from NXT brick. /// </summary> public void Disconnect( ) { if ( port.IsOpen ) { port.Close( ); } } /// <summary> /// Send message to NXT brick over the communication interface. /// </summary> /// /// <param name="message">Buffer containing the message to send.</param> /// /// <returns>Returns <b>true</b> if message was sent successfully or <b>false</b> /// otherwise.</returns> /// /// <remarks>This method assumes that message starts from the start of the /// specified buffer and occupies entire buffer.</remarks> /// public bool SendMessage( byte[] message ) { return SendMessage( message, 0, message.Length ); } /// <summary> /// Send message to NXT brick over the communication interface. /// </summary> /// /// <param name="message">Buffer containing the message to send.</param> /// <param name="length">Length of the message to send.</param> /// /// <returns>Returns <b>true</b> if message was sent successfully or <b>false</b> /// otherwise.</returns> /// /// <remarks>This method assumes that message starts from the start of the /// specified buffer.</remarks> /// public bool SendMessage( byte[] message, int length ) { return SendMessage( message, 0, length ); } /// <summary> /// Send message to NXT brick over the communication interface. /// </summary> /// /// <param name="message">Buffer containing the message to send.</param> /// <param name="offset">Offset of the message in the buffer.</param> /// <param name="length">Length of the message to send.</param> /// /// <returns>Returns <b>true</b> if message was sent successfully or <b>false</b> /// otherwise.</returns> /// public bool SendMessage( byte[] message, int offset, int length ) { // check connection status if ( !port.IsOpen ) { throw new NullReferenceException( "Serial port is not opened" ); } // check message size if ( length > MaxMessageSize ) { throw new ArgumentException( "Too large message" ); } try { // prepare request buffer byte[] requestBuffer = new byte[length + 2]; requestBuffer[0] = (byte) ( length & 0xFF ); requestBuffer[1] = (byte) ( ( length & 0xFF00 ) >> 8 ); Array.Copy( message, offset, requestBuffer, 2, length ); // send actual request port.Write( requestBuffer, 0, requestBuffer.Length ); } catch { return false; } return true; } /// <summary> /// Read message from NXT brick over the communication interface. /// </summary> /// /// <param name="buffer">Buffer to use for message reading.</param> /// <param name="length">On successful return the variable keeps message length.</param> /// /// <returns>Returns <b>true</b> if message was read successfully or <b>false</b> /// otherwise.</returns> /// public bool ReadMessage( byte[] buffer, out int length ) { return ReadMessage( buffer, 0, out length ); } /// <summary> /// Read message from NXT brick over the communication interface. /// </summary> /// /// <param name="buffer">Buffer to use for message reading.</param> /// <param name="offset">Offset in the buffer for message.</param> /// <param name="length">On successful return the variable keeps message length.</param> /// /// <returns>Returns <b>true</b> if message was read successfully or <b>false</b> /// otherwise.</returns> /// public bool ReadMessage( byte[] buffer, int offset, out int length ) { // check connection status if ( !port.IsOpen ) { throw new NullReferenceException( "Serial port is not opened" ); } length = 0; try { // read 2 bytes of message length int lsb = port.ReadByte( ); int msb = port.ReadByte( ); int toRead = ( msb << 8 ) + lsb; // check buffer size if ( toRead > buffer.Length - offset ) { // remove incomming message from the port while ( toRead != 0 ) { port.ReadByte( ); toRead--; } throw new ArgumentException( "Reply buffer is too small" ); } // read the message length = port.Read( buffer, offset, toRead ); while ( length < toRead ) { buffer[offset + length] = (byte) port.ReadByte( ); length++; } } catch { return false; } return true; } } }
{ "content_hash": "0ca52549e985b0e79dd80ab34d86e896", "timestamp": "", "source": "github", "line_count": 266, "max_line_length": 114, "avg_line_length": 34.597744360902254, "alnum_prop": 0.483537976746713, "repo_name": "lyuboasenov/scheduler", "id": "8205de3ff3d5a92ff7666a50b55fb304b495c8d3", "size": "9342", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/AForge.NET Framework-2.2.5/Sources/Robotics.Lego/Internals/SerialCommunication.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "30580" } ], "symlink_target": "" }
namespace UniversityStudentSystem.Common { public class CoursersConstants { /* Software */ //// Module 1 public const string CSharp = "C# Basics"; public const string CPlusPlus = "C++"; public const string OOP = "Object oriented programming"; //// Module 2 public const string JSBasic = "JS Basic"; public const string JSDom = "JS Dom"; public const string JSAdvanced = "JS Advanced"; //// Module 3 public const string ASPMVC = "ASP.NET MVC"; public const string ASPWebForms = "ASP.NET Web Forms"; public const string ASPWebApi = "ASP.NET Web Api"; /* Hardware */ public const string MicroprocessorsAndApplications = "Microprocessors and applications"; public const string ElectricalEngineering = "Electrical engineering"; public const string NetworkAdministration = "Network administration"; public const string DigitalCircuitFaultDetection = "Digital circuit fault detection"; public const string MicrocomputerDesign = "Microcomputer design"; public const string InfrastructureEngineering = "Infrastructure engineering"; /* IT */ public const string InformationalSystems = "Informational systems"; public const string LinearMaths = "Linear maths"; public const string AdvancedMathematics = "Advanced mathematics"; public const string ArtificialIntelligence = "Artificial Intelligence"; public const string DataBaseTechnologies = "DataBase technologies"; public const string ProcessAndModelingSystems = "Process and modeling systems"; public const string RouterConfiguration = "Router configuration"; public const string OperatingSystems = "Operating systems"; public const string LogicProgramming = "Logic programming"; /* Business */ public const string BusinessAdministration = "Business administration"; public const string Sociology = "Sociology"; public const string PublicAdministration = "Public administration"; public const string InternationalRelations = "International relations"; public const string BusinessEconomics = "Business economics"; public const string RegionalDevelopment = "Regional development"; public const string BusinessLogistics = "Business logistics"; public const string BusinessInformatics = "Business informatics"; /* Economics */ public const string Economics = "Economics"; public const string Macroeconomics = "Macroeconomics"; public const string Marketing = "Marketing"; public const string EconomicsOfIndustry = "Economics of industry"; public const string EconomicsOfTrade = "Economics of trade"; public const string EconomicsOfTourism = "Economics of tourism"; public const string RealEstateEconomics = "Real estate economics"; public const string StatisticsAndEconometrics = "Statistics and econometrics"; } }
{ "content_hash": "7f57eaaa3a81ef3e7e2ca3f731a08072", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 96, "avg_line_length": 50.95, "alnum_prop": 0.6967615309126595, "repo_name": "M-Yankov/UniversityStudentSystem", "id": "9c8ed9ad2005e5e592259091abcbd8169af73843", "size": "3059", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "UniversityStudentSystem/Common/UniversityStudentSystem.Common/CoursersConstants.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "118" }, { "name": "C#", "bytes": "580222" }, { "name": "CSS", "bytes": "7882" }, { "name": "JavaScript", "bytes": "177607" } ], "symlink_target": "" }
/** * @author Azaroth */ var SvgStar = new Class({ Extends: SvgMapItem, initialize: function(id, star){ this.parent('star'+id); this.star = star; this.cssClassPrefix = "star"; }, star : {}, $svgIcon : {}, $svgNameplate : {}, isStatic : function() { return true; }, buildBackground : function(t) { this.setT(t); return ""; }, buildObject : function(t) { this.setT(t); return '<circle id="'+this.getId(ID_OBJECT_SUFFIX)+'" cx="0" cy="0" r="20" class="star" />'; }, buildOverlay : function(t) { this.setT(t); return '<text id="'+this.idPrefix+'N" x="0" y="' + (20 + 18) + '" class="planetName">' + this.star.name + '</text>'; }, // Prepares for updating related elements. All calculations must be done here. Returns false, if there is currently nothing to update. prepareUpdate : function(t) { this.setT(t); return false; }, performUpdate : function() {}, revive : function() { var $svgIcon = this.$svgIcon = $('#'+this.getId(ID_OBJECT_SUFFIX)); var $svgNameplate = this.$svgNameplate = $('#'+this.getId('N')); var $svgStar = $('#'+this.getId(ID_OBJECT_SUFFIX)+', #'+this.getId('N')); var mouseoverHandler = function(){ console.debug("mouseoverHandler"); console.debug("$svgIcon:",$svgIcon); console.debug("$svgNameplate:",$svgNameplate); $svgStar.addClass('starHover'); }; var mouseleaveHandler = function(){ $svgStar.removeClass('starHover'); }; $svgIcon.mouseover(mouseoverHandler).mouseleave(mouseleaveHandler); $svgNameplate.mouseover(mouseoverHandler).mouseleave(mouseleaveHandler); }, getName: function() { return this.star.name; } });
{ "content_hash": "23f649b6b6f35cbcd2300eae16be58bf", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 135, "avg_line_length": 27.25, "alnum_prop": 0.6434250764525994, "repo_name": "SpaceTrafficDevelopers/SpaceTraffic", "id": "4cb68286cab6015c942784e5e6e1b78bc38cfa18", "size": "1635", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Backup/GameUi/JS/map/svg/SvgStar.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "220" }, { "name": "Batchfile", "bytes": "757" }, { "name": "C#", "bytes": "1681408" }, { "name": "CSS", "bytes": "93656" }, { "name": "HTML", "bytes": "258820" }, { "name": "Java", "bytes": "69263" }, { "name": "JavaScript", "bytes": "585878" }, { "name": "PowerShell", "bytes": "124" } ], "symlink_target": "" }
package models.db; import com.fasterxml.jackson.annotation.*; import com.google.gson.annotations.Expose; import lombok.Getter; import lombok.Setter; import models.db.acentera.impl.ProjectProvidersImpl; import org.hibernate.annotations.Where; import play.Logger; import utils.security.TagArrayBasePermission; import utils.security.TagSingleBasePermission; import javax.persistence.*; import java.util.*; @Entity @Table(name = "PROJECT_PROVIDERS") @Where(clause="disable_date is null") @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") @JsonRootName("provider") @JsonInclude(JsonInclude.Include.NON_NULL) public class ProjectProviders extends AutoIncrementId implements TagArrayBasePermission { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Expose @Getter @Setter Long id; @ManyToOne @JsonIdentityReference(alwaysAsId = true) @JsonProperty("project_id") public @Getter @Setter Project project; /*public void setProject(Projects p) { this.project = p; this.project_id = p.getId(); }*/ @Expose public @Getter @Setter String name; @Expose public @Getter @Setter String apikey; @JsonIgnore public @Getter @Setter String secretkey; @Expose public @Getter @Setter String type; @Expose public @Getter @Setter String internal_type; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name="project_providers_id") @Where(clause = "disable_date is null") @Expose public @Getter @Setter Set<ProjectProvidersQuotaTags> tags = new HashSet<ProjectProvidersQuotaTags>(); /* @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name="project_providers_id") @Where(clause = "disable_date is null") @Expose public ProjectProvidersTags tag;*/ @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name="project_providers_id") @Where(clause = "disable_date is null") @JsonIgnore @Expose public Set<ProjectProvidersTags> tag = new HashSet<ProjectProvidersTags>(); public void setTag(ProjectProvidersTags t) { if (tag != null) { Iterator<ProjectProvidersTags> itrTags = tag.iterator(); while(itrTags.hasNext()) { ProjectProvidersTags currentTag = itrTags.next(); currentTag.disable(); } } else { tag = new HashSet<ProjectProvidersTags>(); } this.tag.add(t); } @JsonProperty("tag") public String getTag() { Logger.debug("getTag of : " + this.getName()); if (tag == null) return ""; Logger.debug("getTag of : " + this.getName() + " - 1 "); ProjectProvidersTags tagItem = null; Iterator<ProjectProvidersTags> itrTags = tag.iterator(); while(itrTags.hasNext() && tagItem == null) { ProjectProvidersTags currentTag = itrTags.next(); Logger.debug("getTag of : " + this.getName() + " - 2 " + currentTag); if (!currentTag.isDisabled()) { tagItem = currentTag; } } Logger.debug("getTag of : " + this.getName() + " - 3 " + tagItem); if (tagItem == null) { return ""; } Logger.debug("getTag of : " + this.getName() + " - 3 " + tagItem); return tagItem.getName(); } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name="project_providers_id") @Where(clause = "disable_date is null") @JsonIgnore @Expose public @Getter @Setter Set<ProjectProvidersRegions> regions = new HashSet<ProjectProvidersRegions>(); public void addRegion(ProjectRegions pr) { ProjectProvidersRegions ppr = new ProjectProvidersRegions(); ppr.setProjectRegions(pr); this.regions.add(ppr); } @Transient @JsonIdentityReference(alwaysAsId = true) @JsonProperty("regions") public Set<ProjectRegions> lstRegions() { return ProjectProvidersImpl.getRegionsAvailables(this.getRegions()); } @Transient @JsonIdentityReference(alwaysAsId = true) @JsonProperty("region_sizes") public HashMap<Long, ArrayList<Long>> regionSizes() { HashMap<Long, ArrayList<Long>> hm = ProjectProvidersImpl.getRegionAvailableSizes(this.getRegions()); return hm; } /* we should do this instead.. but only 1 item max... and on set of a new one diable old one.. @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name="project_providers_id") @Where(clause = "disable_date is null") @Expose public @Getter @Setter Set<ProjectProvidersTags> tags = new HashSet<ProjectProvidersTags>();*/ public Long getProjectId() { return this.getProject().getId(); } private static final long serialVersionUID = -87392980223422L; public boolean isEquals(MetaData obj) { ProjectProviders uObj = (ProjectProviders) obj; if ( ! (getProject().equals(uObj.getProject()) ) ) return false; if ( ! (name.compareTo(uObj.getName() ) == 0 ) ) return false; if ( ! (type.compareTo(uObj.getType() ) == 0 ) ) return false; if ( ! (apikey.compareTo(uObj.getApikey() ) == 0 ) ) return false; if ( ! (secretkey.compareTo(uObj.getSecretkey() ) == 0 ) ) return false; return true; } @Override public List<String> getTagPermissions() { List<String> lstTags = new ArrayList<String>(); lstTags.add(this.getTag()); return lstTags; } }
{ "content_hash": "47746bc7d5be19033efc8528f1ac1d4d", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 114, "avg_line_length": 31.847457627118644, "alnum_prop": 0.6492815327301756, "repo_name": "ACenterAInc/acentera", "id": "d94a76a0958fa53300e4597d7be6ad97c8f173b0", "size": "6719", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/models/db/ProjectProviders.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1011962" }, { "name": "Java", "bytes": "542328" }, { "name": "JavaScript", "bytes": "4597809" }, { "name": "Ruby", "bytes": "4909" }, { "name": "Scala", "bytes": "61931" }, { "name": "Shell", "bytes": "1183" } ], "symlink_target": "" }
"""Helper classes for Google Assistant integration.""" from __future__ import annotations from abc import ABC, abstractmethod from asyncio import gather from collections.abc import Mapping from http import HTTPStatus import logging import pprint from aiohttp.web import json_response from homeassistant.components import webhook from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_SUPPORTED_FEATURES, CLOUD_NEVER_EXPOSED_ENTITIES, CONF_NAME, STATE_UNAVAILABLE, ) from homeassistant.core import Context, HomeAssistant, State, callback from homeassistant.helpers import start from homeassistant.helpers.area_registry import AreaEntry from homeassistant.helpers.device_registry import DeviceEntry from homeassistant.helpers.entity_registry import RegistryEntry from homeassistant.helpers.event import async_call_later from homeassistant.helpers.network import get_url from homeassistant.helpers.storage import Store from . import trait from .const import ( CONF_ALIASES, CONF_ROOM_HINT, DEVICE_CLASS_TO_GOOGLE_TYPES, DOMAIN, DOMAIN_TO_GOOGLE_TYPES, ERR_FUNCTION_NOT_SUPPORTED, NOT_EXPOSE_LOCAL, SOURCE_LOCAL, STORE_AGENT_USER_IDS, ) from .error import SmartHomeError SYNC_DELAY = 15 _LOGGER = logging.getLogger(__name__) async def _get_entity_and_device( hass, entity_id ) -> tuple[RegistryEntry, DeviceEntry] | None: """Fetch the entity and device entries for a entity_id.""" dev_reg, ent_reg = await gather( hass.helpers.device_registry.async_get_registry(), hass.helpers.entity_registry.async_get_registry(), ) if not (entity_entry := ent_reg.async_get(entity_id)): return None, None device_entry = dev_reg.devices.get(entity_entry.device_id) return entity_entry, device_entry async def _get_area(hass, entity_entry, device_entry) -> AreaEntry | None: """Calculate the area for an entity.""" if entity_entry and entity_entry.area_id: area_id = entity_entry.area_id elif device_entry and device_entry.area_id: area_id = device_entry.area_id else: return None area_reg = await hass.helpers.area_registry.async_get_registry() return area_reg.areas.get(area_id) async def _get_device_info(device_entry) -> dict[str, str] | None: """Retrieve the device info for a device.""" if not device_entry: return None device_info = {} if device_entry.manufacturer: device_info["manufacturer"] = device_entry.manufacturer if device_entry.model: device_info["model"] = device_entry.model if device_entry.sw_version: device_info["swVersion"] = device_entry.sw_version return device_info class AbstractConfig(ABC): """Hold the configuration for Google Assistant.""" _unsub_report_state = None def __init__(self, hass): """Initialize abstract config.""" self.hass = hass self._store = None self._google_sync_unsub = {} self._local_sdk_active = False async def async_initialize(self): """Perform async initialization of config.""" self._store = GoogleConfigStore(self.hass) await self._store.async_load() if not self.enabled: return async def sync_google(_): """Sync entities to Google.""" await self.async_sync_entities_all() start.async_at_start(self.hass, sync_google) @property def enabled(self): """Return if Google is enabled.""" return False @property def entity_config(self): """Return entity config.""" return {} @property def secure_devices_pin(self): """Return entity config.""" return None @property def is_reporting_state(self): """Return if we're actively reporting states.""" return self._unsub_report_state is not None @property def is_local_sdk_active(self): """Return if we're actively accepting local messages.""" return self._local_sdk_active @property def should_report_state(self): """Return if states should be proactively reported.""" return False @property def local_sdk_webhook_id(self): """Return the local SDK webhook ID. Return None to disable the local SDK. """ return None @property def local_sdk_user_id(self): """Return the user ID to be used for actions received via the local SDK.""" raise NotImplementedError @abstractmethod def get_agent_user_id(self, context): """Get agent user ID from context.""" @abstractmethod def should_expose(self, state) -> bool: """Return if entity should be exposed.""" def should_2fa(self, state): """If an entity should have 2FA checked.""" # pylint: disable=no-self-use return True async def async_report_state(self, message, agent_user_id: str): """Send a state report to Google.""" raise NotImplementedError async def async_report_state_all(self, message): """Send a state report to Google for all previously synced users.""" jobs = [ self.async_report_state(message, agent_user_id) for agent_user_id in self._store.agent_user_ids ] await gather(*jobs) @callback def async_enable_report_state(self): """Enable proactive mode.""" # Circular dep # pylint: disable=import-outside-toplevel from .report_state import async_enable_report_state if self._unsub_report_state is None: self._unsub_report_state = async_enable_report_state(self.hass, self) @callback def async_disable_report_state(self): """Disable report state.""" if self._unsub_report_state is not None: self._unsub_report_state() self._unsub_report_state = None async def async_sync_entities(self, agent_user_id: str): """Sync all entities to Google.""" # Remove any pending sync self._google_sync_unsub.pop(agent_user_id, lambda: None)() status = await self._async_request_sync_devices(agent_user_id) if status == HTTPStatus.NOT_FOUND: await self.async_disconnect_agent_user(agent_user_id) return status async def async_sync_entities_all(self): """Sync all entities to Google for all registered agents.""" res = await gather( *( self.async_sync_entities(agent_user_id) for agent_user_id in self._store.agent_user_ids ) ) return max(res, default=204) @callback def async_schedule_google_sync(self, agent_user_id: str): """Schedule a sync.""" async def _schedule_callback(_now): """Handle a scheduled sync callback.""" self._google_sync_unsub.pop(agent_user_id, None) await self.async_sync_entities(agent_user_id) self._google_sync_unsub.pop(agent_user_id, lambda: None)() self._google_sync_unsub[agent_user_id] = async_call_later( self.hass, SYNC_DELAY, _schedule_callback ) @callback def async_schedule_google_sync_all(self): """Schedule a sync for all registered agents.""" for agent_user_id in self._store.agent_user_ids: self.async_schedule_google_sync(agent_user_id) async def _async_request_sync_devices(self, agent_user_id: str) -> int: """Trigger a sync with Google. Return value is the HTTP status code of the sync request. """ raise NotImplementedError async def async_connect_agent_user(self, agent_user_id: str): """Add an synced and known agent_user_id. Called when a completed sync response have been sent to Google. """ self._store.add_agent_user_id(agent_user_id) async def async_disconnect_agent_user(self, agent_user_id: str): """Turn off report state and disable further state reporting. Called when the user disconnects their account from Google. """ self._store.pop_agent_user_id(agent_user_id) @callback def async_enable_local_sdk(self): """Enable the local SDK.""" if (webhook_id := self.local_sdk_webhook_id) is None: return try: webhook.async_register( self.hass, DOMAIN, "Local Support", webhook_id, self._handle_local_webhook, ) except ValueError: _LOGGER.info("Webhook handler is already defined!") return self._local_sdk_active = True @callback def async_disable_local_sdk(self): """Disable the local SDK.""" if not self._local_sdk_active: return webhook.async_unregister(self.hass, self.local_sdk_webhook_id) self._local_sdk_active = False async def _handle_local_webhook(self, hass, webhook_id, request): """Handle an incoming local SDK message.""" # Circular dep # pylint: disable=import-outside-toplevel from . import smart_home payload = await request.json() if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug("Received local message:\n%s\n", pprint.pformat(payload)) if not self.enabled: return json_response(smart_home.turned_off_response(payload)) result = await smart_home.async_handle_message( self.hass, self, self.local_sdk_user_id, payload, SOURCE_LOCAL ) if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug("Responding to local message:\n%s\n", pprint.pformat(result)) return json_response(result) class GoogleConfigStore: """A configuration store for google assistant.""" _STORAGE_VERSION = 1 _STORAGE_KEY = DOMAIN def __init__(self, hass): """Initialize a configuration store.""" self._hass = hass self._store = Store(hass, self._STORAGE_VERSION, self._STORAGE_KEY) self._data = {STORE_AGENT_USER_IDS: {}} @property def agent_user_ids(self): """Return a list of connected agent user_ids.""" return self._data[STORE_AGENT_USER_IDS] @callback def add_agent_user_id(self, agent_user_id): """Add an agent user id to store.""" if agent_user_id not in self._data[STORE_AGENT_USER_IDS]: self._data[STORE_AGENT_USER_IDS][agent_user_id] = {} self._store.async_delay_save(lambda: self._data, 1.0) @callback def pop_agent_user_id(self, agent_user_id): """Remove agent user id from store.""" if agent_user_id in self._data[STORE_AGENT_USER_IDS]: self._data[STORE_AGENT_USER_IDS].pop(agent_user_id, None) self._store.async_delay_save(lambda: self._data, 1.0) async def async_load(self): """Store current configuration to disk.""" if data := await self._store.async_load(): self._data = data class RequestData: """Hold data associated with a particular request.""" def __init__( self, config: AbstractConfig, user_id: str, source: str, request_id: str, devices: list[dict] | None, ) -> None: """Initialize the request data.""" self.config = config self.source = source self.request_id = request_id self.context = Context(user_id=user_id) self.devices = devices @property def is_local_request(self): """Return if this is a local request.""" return self.source == SOURCE_LOCAL def get_google_type(domain, device_class): """Google type based on domain and device class.""" typ = DEVICE_CLASS_TO_GOOGLE_TYPES.get((domain, device_class)) return typ if typ is not None else DOMAIN_TO_GOOGLE_TYPES[domain] class GoogleEntity: """Adaptation of Entity expressed in Google's terms.""" def __init__( self, hass: HomeAssistant, config: AbstractConfig, state: State ) -> None: """Initialize a Google entity.""" self.hass = hass self.config = config self.state = state self._traits = None @property def entity_id(self): """Return entity ID.""" return self.state.entity_id @callback def traits(self): """Return traits for entity.""" if self._traits is not None: return self._traits state = self.state domain = state.domain attributes = state.attributes features = attributes.get(ATTR_SUPPORTED_FEATURES, 0) if not isinstance(features, int): _LOGGER.warning( "Entity %s contains invalid supported_features value %s", self.entity_id, features, ) return [] device_class = state.attributes.get(ATTR_DEVICE_CLASS) self._traits = [ Trait(self.hass, state, self.config) for Trait in trait.TRAITS if Trait.supported(domain, features, device_class, attributes) ] return self._traits @callback def should_expose(self): """If entity should be exposed.""" return self.config.should_expose(self.state) @callback def should_expose_local(self) -> bool: """Return if the entity should be exposed locally.""" return ( self.should_expose() and get_google_type( self.state.domain, self.state.attributes.get(ATTR_DEVICE_CLASS) ) not in NOT_EXPOSE_LOCAL and not self.might_2fa() ) @callback def is_supported(self) -> bool: """Return if the entity is supported by Google.""" return bool(self.traits()) @callback def might_2fa(self) -> bool: """Return if the entity might encounter 2FA.""" if not self.config.should_2fa(self.state): return False return self.might_2fa_traits() @callback def might_2fa_traits(self) -> bool: """Return if the entity might encounter 2FA based on just traits.""" state = self.state domain = state.domain features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) device_class = state.attributes.get(ATTR_DEVICE_CLASS) return any( trait.might_2fa(domain, features, device_class) for trait in self.traits() ) async def sync_serialize(self, agent_user_id): """Serialize entity for a SYNC response. https://developers.google.com/actions/smarthome/create-app#actiondevicessync """ state = self.state entity_config = self.config.entity_config.get(state.entity_id, {}) name = (entity_config.get(CONF_NAME) or state.name).strip() domain = state.domain device_class = state.attributes.get(ATTR_DEVICE_CLASS) entity_entry, device_entry = await _get_entity_and_device( self.hass, state.entity_id ) traits = self.traits() device_type = get_google_type(domain, device_class) device = { "id": state.entity_id, "name": {"name": name}, "attributes": {}, "traits": [trait.name for trait in traits], "willReportState": self.config.should_report_state, "type": device_type, } # use aliases if aliases := entity_config.get(CONF_ALIASES): device["name"]["nicknames"] = [name] + aliases if self.config.is_local_sdk_active and self.should_expose_local(): device["otherDeviceIds"] = [{"deviceId": self.entity_id}] device["customData"] = { "webhookId": self.config.local_sdk_webhook_id, "httpPort": self.hass.http.server_port, "httpSSL": self.hass.config.api.use_ssl, "uuid": await self.hass.helpers.instance_id.async_get(), "baseUrl": get_url(self.hass, prefer_external=True), "proxyDeviceId": agent_user_id, } for trt in traits: device["attributes"].update(trt.sync_attributes()) if room := entity_config.get(CONF_ROOM_HINT): device["roomHint"] = room else: area = await _get_area(self.hass, entity_entry, device_entry) if area and area.name: device["roomHint"] = area.name if device_info := await _get_device_info(device_entry): device["deviceInfo"] = device_info return device @callback def query_serialize(self): """Serialize entity for a QUERY response. https://developers.google.com/actions/smarthome/create-app#actiondevicesquery """ state = self.state if state.state == STATE_UNAVAILABLE: return {"online": False} attrs = {"online": True} for trt in self.traits(): deep_update(attrs, trt.query_attributes()) return attrs @callback def reachable_device_serialize(self): """Serialize entity for a REACHABLE_DEVICE response.""" return {"verificationId": self.entity_id} async def execute(self, data, command_payload): """Execute a command. https://developers.google.com/actions/smarthome/create-app#actiondevicesexecute """ command = command_payload["command"] params = command_payload.get("params", {}) challenge = command_payload.get("challenge", {}) executed = False for trt in self.traits(): if trt.can_execute(command, params): await trt.execute(command, data, params, challenge) executed = True break if not executed: raise SmartHomeError( ERR_FUNCTION_NOT_SUPPORTED, f"Unable to execute {command} for {self.state.entity_id}", ) @callback def async_update(self): """Update the entity with latest info from Home Assistant.""" self.state = self.hass.states.get(self.entity_id) if self._traits is None: return for trt in self._traits: trt.state = self.state def deep_update(target, source): """Update a nested dictionary with another nested dictionary.""" for key, value in source.items(): if isinstance(value, Mapping): target[key] = deep_update(target.get(key, {}), value) else: target[key] = value return target @callback def async_get_entities(hass, config) -> list[GoogleEntity]: """Return all entities that are supported by Google.""" entities = [] for state in hass.states.async_all(): if state.entity_id in CLOUD_NEVER_EXPOSED_ENTITIES: continue entity = GoogleEntity(hass, config, state) if entity.is_supported(): entities.append(entity) return entities
{ "content_hash": "57039adf7250ebfdbaf8d124c684c2ee", "timestamp": "", "source": "github", "line_count": 608, "max_line_length": 87, "avg_line_length": 31.43421052631579, "alnum_prop": 0.6095646714106321, "repo_name": "home-assistant/home-assistant", "id": "238ee8d957648b1b3fee274e83c4327ea2667522", "size": "19112", "binary": false, "copies": "2", "ref": "refs/heads/dev", "path": "homeassistant/components/google_assistant/helpers.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "20557383" }, { "name": "Shell", "bytes": "6671" } ], "symlink_target": "" }
/* lp_solve.cpp : Defines the entry point for the DLL. */ #include "lp_solveDLL.h" BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; }
{ "content_hash": "765b0c7702286c0eca2ae2a7327a5904", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 57, "avg_line_length": 18, "alnum_prop": 0.5357142857142857, "repo_name": "mattkrick/node-lp_solve", "id": "598a3241f2b5f8beaf70dfd863a54332e09720cb", "size": "252", "binary": false, "copies": "17", "ref": "refs/heads/master", "path": "deps/lp_solve/lp_solve_5.5/lp_solveDLL.c", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "167109" }, { "name": "JavaScript", "bytes": "36071" }, { "name": "Python", "bytes": "616" } ], "symlink_target": "" }
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { LayoutWithDirectionComponent } from './layout-with-direction.component'; describe('LayoutWithDirectionComponent', () => { let component: LayoutWithDirectionComponent; let fixture: ComponentFixture<LayoutWithDirectionComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ LayoutWithDirectionComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(LayoutWithDirectionComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
{ "content_hash": "159d5ff3e1be6f9a54640044311cca1b", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 81, "avg_line_length": 28.84, "alnum_prop": 0.710124826629681, "repo_name": "angular/flex-layout", "id": "b7dc381d9a2792aa489a3171bd285a380530360d", "size": "721", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "projects/apps/demo-app/src/app/layout/layout-with-direction/layout-with-direction.component.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "29731" }, { "name": "JavaScript", "bytes": "12174" }, { "name": "SCSS", "bytes": "14513" }, { "name": "Shell", "bytes": "9293" }, { "name": "TypeScript", "bytes": "660907" } ], "symlink_target": "" }
<?php namespace App\Http\Controllers\Product; use Illuminate\Http\Request; use AvoRed\Framework\Database\Contracts\ProductModelInterface; use AvoRed\Review\Database\Contracts\ProductReviewModelInterface; use App\Http\Controllers\Controller; class ProductController extends Controller { /** * @var \AvoRed\Framework\Database\Repository\ProductRepository */ protected $productRepository; /** * @var \AvoRed\Review\Database\Repository\ProductReviewRepository */ protected $productReviewRepository; /** * home controller construct. */ public function __construct( ProductModelInterface $productRepository, ProductReviewModelInterface $productReviewRepository ) { $this->productRepository = $productRepository; $this->productReviewRepository = $productReviewRepository; } /** * Show the application dashboard. * @return \Illuminate\Contracts\Support\Renderable */ public function show($slug) { $product = $this->productRepository->findBySlug($slug); $reviews = $this->productReviewRepository->getAllReviewsByProductId($product->id); $product->images; return view('product.show') ->with(compact('product', 'reviews')); } }
{ "content_hash": "46c0c94f873a8e7d393051412dc44e48", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 90, "avg_line_length": 28.711111111111112, "alnum_prop": 0.6919504643962848, "repo_name": "mage2/laravel-ecommerce", "id": "994d497b60db673d127f7a1dc1035007bbbcd600", "size": "1292", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Http/Controllers/Product/ProductController.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "38449" }, { "name": "HTML", "bytes": "205073" }, { "name": "JavaScript", "bytes": "263892" }, { "name": "PHP", "bytes": "453424" } ], "symlink_target": "" }
oppia.directive('imageWithRegionsEditor', [ '$sce', 'UrlInterpolationService', 'AlertsService', '$document', 'ContextService', 'AssetsBackendApiService', 'OBJECT_EDITOR_URL_PREFIX', function($sce, UrlInterpolationService, AlertsService, $document, ContextService, AssetsBackendApiService, OBJECT_EDITOR_URL_PREFIX) { return { restrict: 'E', scope: { value: '=' }, templateUrl: UrlInterpolationService.getExtensionResourceUrl( '/objects/templates/image_with_regions_editor_directive.html'), controller: [ '$scope', '$element', '$uibModal', function($scope, $element, $uibModal) { $scope.alwaysEditable = true; // Dynamically defines the CSS style for the region rectangle. $scope.getRegionStyle = function(index) { if (index === $scope.selectedRegion) { return 'fill: #00f; opacity: 0.5; stroke: #00d'; } else { return 'fill: white; opacity: 0.5; stroke: #ddd'; } }; // Dynamically defines the CSS style for the region trash icon. $scope.getRegionTrashStyle = function(index) { if (index === $scope.selectedRegion) { return 'fill: #eee; opacity: 0.7'; } else { return 'fill: #333; opacity: 0.7'; } }; // Dynamically defines the CSS style for the region label. $scope.getRegionLabelStyle = function(index) { var commonStyles = 'font-size: 14px; pointer-events: none;'; if (index === $scope.selectedRegion) { return commonStyles + ' fill: #eee; visibility: hidden;'; } else { return commonStyles + ' fill: #333; visibility: visible;'; } }; // Dynamically defines the CSS style for the region label text input. $scope.getRegionLabelEditorStyle = function() { if ($scope.selectedRegion === null) { return 'display: none'; } var area = cornerAndDimensionsFromRegionArea( $scope.value.labeledRegions[ $scope.selectedRegion].region.area); return 'left: ' + (area.x + 6) + 'px; ' + 'top: ' + (area.y + 26) + 'px; ' + 'width: ' + (area.width - 12) + 'px;'; }; $scope.initializeEditor = function() { // All coordinates have origin at top-left, // increasing in x to the right and increasing in y down // Current mouse position in SVG coordinates $scope.mouseX = 0; $scope.mouseY = 0; // Original mouse click position for rectangle drawing. $scope.originalMouseX = 0; $scope.originalMouseY = 0; // Original position and dimensions for dragged rectangle. $scope.originalRectArea = { x: 0, y: 0, width: 0, height: 0 }; // Coordinates for currently drawn rectangle (when user is dragging) $scope.rectX = 0; $scope.rectY = 0; $scope.rectWidth = 0; $scope.rectHeight = 0; // Is user currently drawing a new region? $scope.userIsCurrentlyDrawing = false; // Is user currently dragging an existing region? $scope.userIsCurrentlyDragging = false; // Is user currently resizing an existing region? $scope.userIsCurrentlyResizing = false; // The horizontal direction along which user resize occurs. // 1 -> Left -1 -> Right 0 -> No resize $scope.xDirection = 0; // The vertical direction along which user resize occurs. // 1 -> Top -1 -> Bottom 0 -> No resize $scope.yDirection = 0; // Flags to check whether the direction changes while resizing. $scope.yDirectionToggled = false; $scope.xDirectionToggled = false; // A boolean that is set whenever the cursor moves out of the // rectangular region while resizing. $scope.movedOutOfRegion = false; // The region along borders that will display the resize cursor. $scope.resizableBorderWidthPx = 10; // Dimensions of original image. $scope.originalImageWidth = 0; $scope.originalImageHeight = 0; // Index of region currently hovered over. $scope.hoveredRegion = null; // Index of region currently selected. $scope.selectedRegion = null; // Message to displaye when there is an error. $scope.errorText = ''; }; $scope.initializeEditor(); // Calculates the dimensions of the image, assuming that the width // of the image is scaled down to fit the svg element if necessary. var _calculateImageDimensions = function() { var svgElement = $($element).find( '.oppia-image-with-regions-editor-svg'); var displayedImageWidth = Math.min( svgElement.width(), $scope.originalImageWidth); var scalingRatio = displayedImageWidth / $scope.originalImageWidth; // Note that scalingRatio may be NaN if $scope.originalImageWidth is // zero. var displayedImageHeight = ( $scope.originalImageWidth === 0 ? 0.0 : $scope.originalImageHeight * scalingRatio); return { width: displayedImageWidth, height: displayedImageHeight }; }; // Use these two functions to get the calculated image width and // height. $scope.getImageWidth = function() { return _calculateImageDimensions().width; }; $scope.getImageHeight = function() { return _calculateImageDimensions().height; }; $scope.getPreviewUrl = function(imageUrl) { return AssetsBackendApiService.getImageUrlForPreview( ContextService.getExplorationId(), encodeURIComponent(imageUrl)); }; // Called when the image is changed to calculate the required // width and height, especially for large images. $scope.$watch('value.imagePath', function(newVal) { if (newVal !== '') { // Loads the image in hanging <img> tag so as to get the // width and height. $('<img/>').attr('src', $scope.getPreviewUrl(newVal)).on( 'load', function() { $scope.originalImageWidth = this.width; $scope.originalImageHeight = this.height; $scope.$apply(); } ); } }); var hasDuplicates = function(originalArray) { var array = originalArray.slice(0).sort(); for (var i = 1; i < array.length; i++) { if (array[i - 1] === array[i]) { return true; } } return false; }; $scope.regionLabelGetterSetter = function(index) { return function(label) { if (angular.isDefined(label)) { $scope.value.labeledRegions[index].label = label; var labels = $scope.value.labeledRegions.map( function(region) { return region.label; } ); if (hasDuplicates(labels)) { $scope.errorText = 'Warning: Label "' + label + '" already ' + 'exists! Please use a different label.'; } else { $scope.errorText = ''; } } return $scope.value.labeledRegions[index].label; }; }; var convertCoordsToFraction = function(coords, dimensions) { return [coords[0] / dimensions[0], coords[1] / dimensions[1]]; }; // Convert to and from region area (which is stored as a fraction of // image width and height) and actual width and height. var regionAreaFromCornerAndDimensions = function( x, y, width, height) { return [ convertCoordsToFraction( [x, y], [$scope.getImageWidth(), $scope.getImageHeight()] ), convertCoordsToFraction( [x + width, y + height], [$scope.getImageWidth(), $scope.getImageHeight()] ) ]; }; var cornerAndDimensionsFromRegionArea = function(area) { return { x: area[0][0] * $scope.getImageWidth(), y: area[0][1] * $scope.getImageHeight(), width: (area[1][0] - area[0][0]) * $scope.getImageWidth(), height: (area[1][1] - area[0][1]) * $scope.getImageHeight() }; }; var resizeRegion = function() { var labeledRegions = $scope.value.labeledRegions; var resizedRegion = labeledRegions[$scope.selectedRegion].region; var deltaX = $scope.mouseX - $scope.originalMouseX; var deltaY = $scope.mouseY - $scope.originalMouseY; var x = $scope.originalRectArea.x; var y = $scope.originalRectArea.y; var width = $scope.originalRectArea.width; var height = $scope.originalRectArea.height; var newWidth = width - $scope.xDirection * deltaX; var newHeight = height - $scope.yDirection * deltaY; // The distance between where the mouse was first clicked to // initiate the resize action and the left-most x co-ordinate of // rectangle. var marginX = Math.abs( $scope.originalRectArea.x - $scope.originalMouseX); // The distance between where the mouse was first clicked to // initiate the resize action and the top-most y co-ordinate of // rectangle. var marginY = Math.abs( $scope.originalRectArea.y - $scope.originalMouseY); if (newHeight <= 0 && !$scope.yDirectionToggled) { $scope.yDirectionToggled = true; } else if (newHeight >= 0 && $scope.yDirectionToggled) { $scope.yDirectionToggled = false; } if ($scope.yDirection === 1) { y += $scope.yDirectionToggled ? (height + marginY) : deltaY; } else if ($scope.yDirection === -1) { y += $scope.yDirectionToggled * (deltaY + marginY); } if (newWidth <= 0 && !$scope.xDirectionToggled) { $scope.xDirectionToggled = true; } else if (newWidth >= 0 && $scope.xDirectionToggled) { $scope.xDirectionToggled = false; } if ($scope.xDirection === 1) { x += $scope.xDirectionToggled ? (width + marginX) : deltaX; } else if ($scope.xDirection === -1) { x += $scope.xDirectionToggled * (deltaX + marginX); } // Whenever the direction changes the value of newHeight and // newWidth computed is negative, hence the absolute value is taken. resizedRegion.area = regionAreaFromCornerAndDimensions( x, y, Math.abs(newWidth), Math.abs(newHeight)); }; $scope.onSvgMouseMove = function(evt) { var svgElement = $($element).find( '.oppia-image-with-regions-editor-svg'); $scope.mouseX = evt.pageX - svgElement.offset().left; $scope.mouseY = evt.pageY - svgElement.offset().top; if ($scope.userIsCurrentlyDrawing) { $scope.rectX = Math.min($scope.originalMouseX, $scope.mouseX); $scope.rectY = Math.min($scope.originalMouseY, $scope.mouseY); $scope.rectWidth = Math.abs( $scope.originalMouseX - $scope.mouseX); $scope.rectHeight = Math.abs( $scope.originalMouseY - $scope.mouseY); } else if ($scope.userIsCurrentlyDragging) { var labeledRegions = $scope.value.labeledRegions; var draggedRegion = labeledRegions[$scope.selectedRegion].region; var deltaX = $scope.mouseX - $scope.originalMouseX; var deltaY = $scope.mouseY - $scope.originalMouseY; var newX1 = $scope.originalRectArea.x + deltaX; var newY1 = $scope.originalRectArea.y + deltaY; var newX2 = newX1 + $scope.originalRectArea.width; var newY2 = newY1 + $scope.originalRectArea.height; if (newX1 < 0) { newX1 = 0; newX2 = $scope.originalRectArea.width; } if (newY1 < 0) { newY1 = 0; newY2 = $scope.originalRectArea.height; } if (newX2 > $scope.getImageWidth()) { newX2 = $scope.getImageWidth(); newX1 = newX2 - $scope.originalRectArea.width; } if (newY2 > $scope.getImageHeight()) { newY2 = $scope.getImageHeight(); newY1 = newY2 - $scope.originalRectArea.height; } draggedRegion.area = regionAreaFromCornerAndDimensions( newX1, newY1, $scope.originalRectArea.width, $scope.originalRectArea.height ); } else if ($scope.userIsCurrentlyResizing) { resizeRegion(); } }; $scope.onSvgMouseDown = function(evt) { evt.preventDefault(); $scope.originalMouseX = $scope.mouseX; $scope.originalMouseY = $scope.mouseY; if ($scope.hoveredRegion === null) { $scope.rectWidth = $scope.rectHeight = 0; $scope.userIsCurrentlyDrawing = true; } }; $scope.onSvgMouseUp = function() { if ($scope.hoveredRegion === null) { $scope.selectedRegion = null; } if ($scope.yDirectionToggled) { $scope.yDirection = ($scope.yDirection === 1) ? -1 : 1; } if ($scope.xDirectionToggled) { $scope.xDirection = ($scope.xDirection === 1) ? -1 : 1; } if ($scope.movedOutOfRegion) { $scope.xDirection = 0; $scope.yDirection = 0; } if ($scope.userIsCurrentlyDrawing) { if ($scope.rectWidth !== 0 && $scope.rectHeight !== 0) { var labels = $scope.value.labeledRegions.map( function(region) { return region.label; } ); // Searches numbers starting from 1 to find a valid label // that doesn't overlap with currently existing labels. var newLabel = null; for (var i = 1; i <= labels.length + 1; i++) { var candidateLabel = 'Region' + i.toString(); if (labels.indexOf(candidateLabel) === -1) { newLabel = candidateLabel; break; } } var newRegion = { label: newLabel, region: { regionType: 'Rectangle', area: regionAreaFromCornerAndDimensions( $scope.rectX, $scope.rectY, $scope.rectWidth, $scope.rectHeight ) } }; $scope.value.labeledRegions.push(newRegion); $scope.selectedRegion = ( $scope.value.labeledRegions.length - 1); } } $scope.userIsCurrentlyDrawing = false; $scope.userIsCurrentlyDragging = false; $scope.userIsCurrentlyResizing = false; $scope.movedOutOfRegion = false; $scope.yDirectionToggled = false; $scope.xDirectionToggled = false; }; $scope.onMouseoverRegion = function(index) { if ($scope.hoveredRegion === null) { $scope.hoveredRegion = index; } $scope.movedOutOfRegion = false; }; $scope.onMouseMoveRegion = function() { if ( $scope.userIsCurrentlyDragging || $scope.userIsCurrentlyResizing) { return; } region = cornerAndDimensionsFromRegionArea( $scope.value.labeledRegions[ $scope.hoveredRegion].region.area); if (!$scope.xDirectionToggled && !$scope.yDirectionToggled) { if ($scope.mouseY <= region.y + $scope.resizableBorderWidthPx) { $scope.yDirection = 1; } else if ( $scope.mouseY >= region.height + region.y - $scope.resizableBorderWidthPx) { $scope.yDirection = -1; } else { $scope.yDirection = 0; } if ($scope.mouseX <= region.x + $scope.resizableBorderWidthPx) { $scope.xDirection = 1; } else if ( $scope.mouseX >= region.width + region.x - $scope.resizableBorderWidthPx) { $scope.xDirection = -1; } else { $scope.xDirection = 0; } } }; $scope.onMouseoutRegion = function(index) { if ($scope.hoveredRegion === index) { $scope.hoveredRegion = null; } if (!$scope.userIsCurrentlyResizing) { $scope.xDirection = 0; $scope.yDirection = 0; } $scope.movedOutOfRegion = true; }; $scope.onMousedownRegion = function() { if ($scope.xDirection || $scope.yDirection) { $scope.userIsCurrentlyResizing = true; } else { $scope.userIsCurrentlyDragging = true; } $scope.selectedRegion = $scope.hoveredRegion; $scope.originalRectArea = cornerAndDimensionsFromRegionArea( $scope.value.labeledRegions[ $scope.hoveredRegion].region.area ); }; $scope.regionLabelEditorMouseUp = function() { $scope.userIsCurrentlyDragging = false; $scope.userIsCurrentlyResizing = false; }; $scope.getCursorStyle = function() { var xDirectionCursor = ''; var yDirectionCursor = ''; if ($scope.xDirection || $scope.yDirection) { // User is resizing, so we figure out the direction. if ( ($scope.xDirection === 1 && !$scope.xDirectionToggled) || ($scope.xDirection === -1 && $scope.xDirectionToggled)) { xDirectionCursor = 'w'; } else if ( ($scope.xDirection === -1 && !$scope.xDirectionToggled) || ($scope.xDirection === 1 && $scope.xDirectionToggled)) { xDirectionCursor = 'e'; } else { xDirectionCursor = ''; } if ( ($scope.yDirection === 1 && !$scope.yDirectionToggled) || ($scope.yDirection === -1 && $scope.yDirectionToggled)) { yDirectionCursor = 'n'; } else if ( ($scope.yDirection === -1 && !$scope.yDirectionToggled) || ($scope.yDirection === 1 && $scope.yDirectionToggled)) { yDirectionCursor = 's'; } else { yDirectionCursor = ''; } return yDirectionCursor + xDirectionCursor + '-resize'; } else if ($scope.hoveredRegion !== null) { // User is not resizing but cursor is over a region. return 'pointer'; } return 'crosshair'; }; $scope.resetEditor = function() { $uibModal.open({ templateUrl: UrlInterpolationService.getExtensionResourceUrl( '/objects/templates/' + 'image_with_regions_reset_confirmation_directive.html'), backdrop: 'static', keyboard: false, controller: [ '$scope', '$uibModalInstance', function($scope, $uibModalInstance) { $scope.cancel = function() { $uibModalInstance.dismiss(); }; $scope.confirmClear = function() { $uibModalInstance.close(); }; }] }).result.then(function() { $scope.value.imagePath = ''; $scope.value.labeledRegions = []; $scope.initializeEditor(); }); }; $scope.deleteRegion = function(index) { if ($scope.selectedRegion === index) { $scope.selectedRegion = null; } else if ($scope.selectedRegion > index) { $scope.selectedRegion--; } if ($scope.hoveredRegion === index) { $scope.hoveredRegion = null; } else if ($scope.hoveredRegion > index) { $scope.hoveredRegion--; } $scope.value.labeledRegions.splice(index, 1); }; } ] }; } ]);
{ "content_hash": "7e3fb4bc57cc5c992a446c7a4d048fa1", "timestamp": "", "source": "github", "line_count": 514, "max_line_length": 80, "avg_line_length": 42.66147859922179, "alnum_prop": 0.5093031740240788, "repo_name": "AllanYangZhou/oppia", "id": "58261fa702ca592562142916a0e01ce6348a210b", "size": "22773", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "extensions/objects/templates/ImageWithRegionsEditor.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "82690" }, { "name": "HTML", "bytes": "1128088" }, { "name": "JavaScript", "bytes": "3945933" }, { "name": "Python", "bytes": "4888439" }, { "name": "Shell", "bytes": "50051" } ], "symlink_target": "" }
interface AutoNumericOptions { aSep?: string dGroup?: number aDec?: string altDec?: string aSign?: string pSign?: "p" | "s" vMin?: number vMax?: number mDec?: number mRound?: "S" | "A" | "s" | "a" | "B" | "U" | "D" | "C" | "F" | "CHF" aPad?: boolean nBracket?: string wEmpty?: "empty" | "zero" | "sign" lZero?: "allow" | "deny" | "keep" aForm?: boolean anDefault?: string } interface Serialized { name: string value: string } type AutoNumericMethod = "init" | "destroy" | "update" | "set" | "get" | "getString" | "getArray" | "getSettings" interface JQuery { autoNumeric(): JQuery autoNumeric(options: AutoNumericOptions): JQuery autoNumeric(method: AutoNumericMethod, options?: AutoNumericOptions): JQuery | string | Serialized[] | AutoNumericOptions autoNumeric(method: "init", options?: AutoNumericOptions): JQuery autoNumeric(method: "destroy"): JQuery autoNumeric(method: "update", options: AutoNumericOptions): JQuery autoNumeric(method: "set", value: string): JQuery autoNumeric(method: "get"): string autoNumeric(method: "getString"): string autoNumeric(method: "getArray"): Serialized[] autoNumeric(method: "getSettings"): AutoNumericOptions }
{ "content_hash": "43022480e3f44678888d3def60ff043e", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 78, "avg_line_length": 29.75609756097561, "alnum_prop": 0.6745901639344263, "repo_name": "xhrist14n/admin_libs", "id": "2ee5b38f8a783ecdbc3635b622b41864b13ee2d0", "size": "1220", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "bower_components/autoNumeric/typings.d.ts", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "118" }, { "name": "Shell", "bytes": "139" } ], "symlink_target": "" }
package com.bhatt.ramani.svnitevents; import android.content.Context; import android.database.DataSetObserver; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.Arrays; import java.util.Comparator; public class SimpleSectionedListAdapter extends BaseAdapter { private boolean mValid = true; private int mSectionResourceId; private LayoutInflater mLayoutInflater; private ListAdapter mBaseAdapter; private SparseArray<Section> mSections = new SparseArray<Section>(); public static class Section { int firstPosition; int sectionedPosition; CharSequence title; public Section(int firstPosition, CharSequence title) { this.firstPosition = firstPosition; this.title = title; } public CharSequence getTitle() { return title; } } public SimpleSectionedListAdapter(Context context, int sectionResourceId, ListAdapter baseAdapter) { mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mSectionResourceId = sectionResourceId; mBaseAdapter = baseAdapter; mBaseAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { mValid = !mBaseAdapter.isEmpty(); notifyDataSetChanged(); } @Override public void onInvalidated() { mValid = false; notifyDataSetInvalidated(); } }); } public void setSections(Section[] sections) { mSections.clear(); Arrays.sort(sections, new Comparator<Section>() { @Override public int compare(Section o, Section o1) { return (o.firstPosition == o1.firstPosition) ? 0 : ((o.firstPosition < o1.firstPosition) ? -1 : 1); } }); int offset = 0; // offset positions for the headers we're adding for (Section section : sections) { section.sectionedPosition = section.firstPosition + offset; mSections.append(section.sectionedPosition, section); ++offset; } notifyDataSetChanged(); } public int positionToSectionedPosition(int position) { int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).firstPosition > position) { break; } ++offset; } return position + offset; } public int sectionedPositionToPosition(int sectionedPosition) { if (isSectionHeaderPosition(sectionedPosition)) { return ListView.INVALID_POSITION; } int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).sectionedPosition > sectionedPosition) { break; } --offset; } return sectionedPosition + offset; } public boolean isSectionHeaderPosition(int position) { return mSections.get(position) != null; } @Override public int getCount() { return (mValid ? mBaseAdapter.getCount() + mSections.size() : 0); } @Override public Object getItem(int position) { return isSectionHeaderPosition(position) ? mSections.get(position) : mBaseAdapter.getItem(sectionedPositionToPosition(position)); } @Override public long getItemId(int position) { return isSectionHeaderPosition(position) ? Integer.MAX_VALUE - mSections.indexOfKey(position) : mBaseAdapter.getItemId(sectionedPositionToPosition(position)); } @Override public int getItemViewType(int position) { return isSectionHeaderPosition(position) ? getViewTypeCount() - 1 : mBaseAdapter.getItemViewType(position); } @Override public boolean isEnabled(int position) { //noinspection SimplifiableConditionalExpression return isSectionHeaderPosition(position) ? false : mBaseAdapter.isEnabled(sectionedPositionToPosition(position)); } @Override public int getViewTypeCount() { return mBaseAdapter.getViewTypeCount() + 1; // the section headings } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean hasStableIds() { return mBaseAdapter.hasStableIds(); } @Override public boolean isEmpty() { return mBaseAdapter.isEmpty(); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isSectionHeaderPosition(position)) { TextView view = (TextView) convertView; if (view == null) { view = (TextView) mLayoutInflater.inflate(mSectionResourceId, parent, false); } view.setText(mSections.get(position).title); return view; } else { return mBaseAdapter.getView(sectionedPositionToPosition(position), convertView, parent); } } }
{ "content_hash": "ab4d8304b14d8500fef07fd71c19f85e", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 101, "avg_line_length": 30.21978021978022, "alnum_prop": 0.612909090909091, "repo_name": "jdramani/SVNIT_events_app", "id": "99f124c5e75cafe7d96642936cb8cf58c9cea76d", "size": "6095", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Event/src/main/java/com/bhatt/ramani/svnitevents/SimpleSectionedListAdapter.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "279753" }, { "name": "Python", "bytes": "816" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>Lighthouse: lapack/dsysvx.f File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="tabs.css" rel="stylesheet" type="text/css" /> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <!--<div id="titlearea"> </div>--> <!-- end header part --> <!-- Generated by Doxygen 1.8.2 --> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_42b7da8b2ebcfce3aea4b69198a0a9ad.html">lapack</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#func-members">Functions/Subroutines</a> </div> <div class="headertitle"> <div class="title">dsysvx.f File Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions/Subroutines</h2></td></tr> <tr class="memitem:a183787a5a4cb471abe442815b0e44b35"><td class="memItemLeft" align="right" valign="top">subroutine&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="dsysvx_8f.html#a183787a5a4cb471abe442815b0e44b35">dsysvx</a> (FACT, UPLO, N, NRHS, A, LDA, AF, LDAF, IPIV, B, LDB, X, LDX, RCOND, FERR, BERR, WORK, LWORK, IWORK, INFO)</td></tr> <tr class="memdesc:a183787a5a4cb471abe442815b0e44b35"><td class="mdescLeft">&#160;</td><td class="mdescRight"><b> DSYSVX computes the solution to system of linear equations A * X = B for SY matrices</b> <a href="#a183787a5a4cb471abe442815b0e44b35"></a><br/></td></tr> <tr class="separator:a183787a5a4cb471abe442815b0e44b35"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Function/Subroutine Documentation</h2> <a class="anchor" id="a183787a5a4cb471abe442815b0e44b35"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">subroutine dsysvx </td> <td>(</td> <td class="paramtype">character&#160;</td> <td class="paramname"><em>FACT</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">character&#160;</td> <td class="paramname"><em>UPLO</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>N</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>NRHS</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( lda, * )&#160;</td> <td class="paramname"><em>A</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>LDA</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( ldaf, * )&#160;</td> <td class="paramname"><em>AF</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>LDAF</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer, dimension( * )&#160;</td> <td class="paramname"><em>IPIV</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( ldb, * )&#160;</td> <td class="paramname"><em>B</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>LDB</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( ldx, * )&#160;</td> <td class="paramname"><em>X</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>LDX</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision&#160;</td> <td class="paramname"><em>RCOND</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( * )&#160;</td> <td class="paramname"><em>FERR</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( * )&#160;</td> <td class="paramname"><em>BERR</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( * )&#160;</td> <td class="paramname"><em>WORK</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>LWORK</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer, dimension( * )&#160;</td> <td class="paramname"><em>IWORK</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>INFO</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p><b> DSYSVX computes the solution to system of linear equations A * X = B for SY matrices</b> </p> Download DSYSVX + dependencies <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dsysvx.f"> [TGZ]</a> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dsysvx.f"> [ZIP]</a> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dsysvx.f"> [TXT]</a> <dl class="section user"><dt>Purpose: </dt><dd><pre class="fragment"> DSYSVX uses the diagonal pivoting factorization to compute the solution to a real system of linear equations A * X = B, where A is an N-by-N symmetric matrix and X and B are N-by-NRHS matrices. Error bounds on the solution and a condition estimate are also provided.</pre> </dd></dl> <dl class="section user"><dt>Description: </dt><dd><pre class="fragment"> The following steps are performed: 1. If FACT = 'N', the diagonal pivoting method is used to factor A. The form of the factorization is A = U * D * U**T, if UPLO = 'U', or A = L * D * L**T, if UPLO = 'L', where U (or L) is a product of permutation and unit upper (lower) triangular matrices, and D is symmetric and block diagonal with 1-by-1 and 2-by-2 diagonal blocks. 2. If some D(i,i)=0, so that D is exactly singular, then the routine returns with INFO = i. Otherwise, the factored form of A is used to estimate the condition number of the matrix A. If the reciprocal of the condition number is less than machine precision, INFO = N+1 is returned as a warning, but the routine still goes on to solve for X and compute error bounds as described below. 3. The system of equations is solved for X using the factored form of A. 4. Iterative refinement is applied to improve the computed solution matrix and calculate error bounds and backward error estimates for it.</pre> </dd></dl> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramdir">[in]</td><td class="paramname">FACT</td><td><pre class="fragment"> FACT is CHARACTER*1 Specifies whether or not the factored form of A has been supplied on entry. = 'F': On entry, AF and IPIV contain the factored form of A. AF and IPIV will not be modified. = 'N': The matrix A will be copied to AF and factored.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">UPLO</td><td><pre class="fragment"> UPLO is CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">N</td><td><pre class="fragment"> N is INTEGER The number of linear equations, i.e., the order of the matrix A. N &gt;= 0.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">NRHS</td><td><pre class="fragment"> NRHS is INTEGER The number of right hand sides, i.e., the number of columns of the matrices B and X. NRHS &gt;= 0.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">A</td><td><pre class="fragment"> A is DOUBLE PRECISION array, dimension (LDA,N) The symmetric matrix A. If UPLO = 'U', the leading N-by-N upper triangular part of A contains the upper triangular part of the matrix A, and the strictly lower triangular part of A is not referenced. If UPLO = 'L', the leading N-by-N lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">LDA</td><td><pre class="fragment"> LDA is INTEGER The leading dimension of the array A. LDA &gt;= max(1,N).</pre></td></tr> <tr><td class="paramdir">[in,out]</td><td class="paramname">AF</td><td><pre class="fragment"> AF is DOUBLE PRECISION array, dimension (LDAF,N) If FACT = 'F', then AF is an input argument and on entry contains the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A = U*D*U**T or A = L*D*L**T as computed by DSYTRF. If FACT = 'N', then AF is an output argument and on exit returns the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A = U*D*U**T or A = L*D*L**T.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">LDAF</td><td><pre class="fragment"> LDAF is INTEGER The leading dimension of the array AF. LDAF &gt;= max(1,N).</pre></td></tr> <tr><td class="paramdir">[in,out]</td><td class="paramname">IPIV</td><td><pre class="fragment"> IPIV is INTEGER array, dimension (N) If FACT = 'F', then IPIV is an input argument and on entry contains details of the interchanges and the block structure of D, as determined by DSYTRF. If IPIV(k) &gt; 0, then rows and columns k and IPIV(k) were interchanged and D(k,k) is a 1-by-1 diagonal block. If UPLO = 'U' and IPIV(k) = IPIV(k-1) &lt; 0, then rows and columns k-1 and -IPIV(k) were interchanged and D(k-1:k,k-1:k) is a 2-by-2 diagonal block. If UPLO = 'L' and IPIV(k) = IPIV(k+1) &lt; 0, then rows and columns k+1 and -IPIV(k) were interchanged and D(k:k+1,k:k+1) is a 2-by-2 diagonal block. If FACT = 'N', then IPIV is an output argument and on exit contains details of the interchanges and the block structure of D, as determined by DSYTRF.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">B</td><td><pre class="fragment"> B is DOUBLE PRECISION array, dimension (LDB,NRHS) The N-by-NRHS right hand side matrix B.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">LDB</td><td><pre class="fragment"> LDB is INTEGER The leading dimension of the array B. LDB &gt;= max(1,N).</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">X</td><td><pre class="fragment"> X is DOUBLE PRECISION array, dimension (LDX,NRHS) If INFO = 0 or INFO = N+1, the N-by-NRHS solution matrix X.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">LDX</td><td><pre class="fragment"> LDX is INTEGER The leading dimension of the array X. LDX &gt;= max(1,N).</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">RCOND</td><td><pre class="fragment"> RCOND is DOUBLE PRECISION The estimate of the reciprocal condition number of the matrix A. If RCOND is less than the machine precision (in particular, if RCOND = 0), the matrix is singular to working precision. This condition is indicated by a return code of INFO &gt; 0.</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">FERR</td><td><pre class="fragment"> FERR is DOUBLE PRECISION array, dimension (NRHS) The estimated forward error bound for each solution vector X(j) (the j-th column of the solution matrix X). If XTRUE is the true solution corresponding to X(j), FERR(j) is an estimated upper bound for the magnitude of the largest element in (X(j) - XTRUE) divided by the magnitude of the largest element in X(j). The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">BERR</td><td><pre class="fragment"> BERR is DOUBLE PRECISION array, dimension (NRHS) The componentwise relative backward error of each solution vector X(j) (i.e., the smallest relative change in any element of A or B that makes X(j) an exact solution).</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">WORK</td><td><pre class="fragment"> WORK is DOUBLE PRECISION array, dimension (MAX(1,LWORK)) On exit, if INFO = 0, WORK(1) returns the optimal LWORK.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">LWORK</td><td><pre class="fragment"> LWORK is INTEGER The length of WORK. LWORK &gt;= max(1,3*N), and for best performance, when FACT = 'N', LWORK &gt;= max(1,3*N,N*NB), where NB is the optimal blocksize for DSYTRF. If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA.</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">IWORK</td><td><pre class="fragment"> IWORK is INTEGER array, dimension (N)</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">INFO</td><td><pre class="fragment"> INFO is INTEGER = 0: successful exit &lt; 0: if INFO = -i, the i-th argument had an illegal value &gt; 0: if INFO = i, and i is &lt;= N: D(i,i) is exactly zero. The factorization has been completed but the factor D is exactly singular, so the solution and error bounds could not be computed. RCOND = 0 is returned. = N+1: D is nonsingular, but RCOND is less than machine precision, meaning that the matrix is singular to working precision. Nevertheless, the solution and error bounds are computed because there are a number of situations where the computed solution can be more accurate than the value of RCOND would suggest.</pre> </td></tr> </table> </dd> </dl> <dl class="section author"><dt>Author</dt><dd>Univ. of Tennessee </dd> <dd> Univ. of California Berkeley </dd> <dd> Univ. of Colorado Denver </dd> <dd> NAG Ltd. </dd></dl> <dl class="section date"><dt>Date</dt><dd>April 2012 </dd></dl> </div> </div> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Jul 14 2014 18:28:49 for Lighthouse by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.2 </small></address> </body> </html>
{ "content_hash": "62723319e443a829373baf6a2d488a79", "timestamp": "", "source": "github", "line_count": 340, "max_line_length": 364, "avg_line_length": 51.15882352941176, "alnum_prop": 0.5873864550994596, "repo_name": "LighthouseHPC/lighthouse", "id": "ee05cbae4b0c20a84c069dee0b786136cc25c58d", "size": "17394", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Dlighthouse/media/Doxygen/docs/html/dsysvx_8f.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
Enables two-way synchronization with remote database. **NOTE: This addon is still in alpha development** ### Install ``` npm install dexie --save npm install dexie-observable --save npm install dexie-syncable --save ``` ### Use ```js import Dexie from 'dexie'; import 'dexie-syncable'; // will import dexie-observable as well. // Use Dexie as normally - but you can also register your sync protocols though // Dexie.Syncable.registerSyncProtocol() api as well as using the db.syncable api // as documented here. ``` ### Dependency Tree * **Dexie.Syncable.js** * [Dexie.Observable.js](https://github.com/dfahlander/Dexie.js/wiki/Dexie.Observable.js) * [Dexie.js](https://github.com/dfahlander/Dexie.js/wiki/Dexie.js) * [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) * _An implementation of [ISyncProtocol](https://github.com/dfahlander/Dexie.js/wiki/Dexie.Syncable.ISyncProtocol)_ ### Tutorial #### 1. Include Required Sources In your HTML, make sure to include Dexie.js, Dexie.Observable.js, Dexie.Syncable.js and an implementation of [ISyncProtocol](https://github.com/dfahlander/Dexie.js/wiki/Dexie.Syncable.ISyncProtocol). <html><head> <script src="dexie.min.js"></script> <script src="dexie-observable.min.js"></script> <script src="dexie-syncable.min.js"></script> <script src="WebSocketSyncProtocol.js"></script> <!-- Example implementation of ISyncProtocol --> ... </head><body> </body></html> #### 2. Use UUID based Primary Keys ($$) Two way replication requires not to use auto-incremented keys if any sync node should be able to create objects no matter offline or online. Dexie.Syncable comes with a new syntax when defining your store schemas: the double-dollar prefix ($$). Similary to the ++ prefix in Dexie (meaining auto-incremented primary key), the double-dollar prefix means that the key will be given a universally unique identifier (UUID), in string format (For example "9cc6768c-358b-4d21-ac4d-58cc0fddd2d6"). var db = new Dexie("MySyncedDB"); db.version(1).stores({ friends: "$$oid,name,shoeSize", pets: "$$oid,name,kind" }); #### 3. Connect to Server You must specify the URL of the server you want to keep in-sync with. This has to be done once in the entire database life-time, but doing it on every startup is ok as well, since it wont affect already connected URLs. // This example uses the WebSocketSyncProtocol included in earlier steps. db.syncable.connect ("websocket", "https://syncserver.com/sync"); db.syncable.on('statusChanged', function (newStatus, url) { console.log ("Sync Status changed: " + Dexie.Syncable.StatusTexts[newStatus]); }); #### 4. Use Your Database Query and modify your database as if it was a simple Dexie instance. Any changes will be replicated to server and and change on server or other window will replicate back to you. db.transaction('rw', db.friends, function (friends) { friends.add({name: "Arne", shoeSize: 47}); friends.where(shoeSize).above(40).each(function (friend) { console.log("Friend with shoeSize over 40: " + friend.name); }); }); _NOTE: Transactions only provide the Atomicity part of the [ACID](http://en.wikipedia.org/wiki/ACID) properties when using 2-way syncronization. This is due to that the syncronization phase may result in that another change could override the changes. However, it's still meaningfull to use the transaction() since method for atomicity. Atomicity is guaranteed not only locally but also when synced to the server, meaning that a part of the changes will never commit on the server until all changes from the transaction has been synced. In practice, you cannot increment a counter in the database (for example) and expect it to be consistent, but you can be guaranteed that if you add a sequence of objects, all or none of them will replicate._ ### API Reference #### Static Members [Dexie.Syncable.registerSyncProtocol (name, protocolInstance)](https://github.com/dfahlander/Dexie.js/wiki/Dexie.Syncable.registerSyncProtocol()) Define how to replicate changes with your type of server. [Dexie.Syncable.Statuses](https://github.com/dfahlander/Dexie.js/wiki/Dexie.Syncable.Statuses) Enum of possible sync statuses, such as OFFLINE, CONNECTING, ONLINE and ERROR. [Dexie.Syncable.StatusTexts](https://github.com/dfahlander/Dexie.js/wiki/Dexie.Syncable.StatusTexts) Text lookup for status numbers #### Non-Static Methods and Events [db.syncable.connect (protocol, url, options)](https://github.com/dfahlander/Dexie.js/wiki/db.syncable.connect()) Create a presistend a two-way sync connection with given URL. [db.syncable.disconnect (url)](https://github.com/dfahlander/Dexie.js/wiki/db.syncable.disconnect()) Stop syncing with given URL but keep revision states until next connect. [db.syncable.delete(url)](https://github.com/dfahlander/Dexie.js/wiki/db.syncable.delete()) Delete all states and change queue for given URL [db.syncable.list()](https://github.com/dfahlander/Dexie.js/wiki/db.syncable.list()) List the URLs of each remote node we have a state saved for. [db.syncable.on('statusChanged')](https://github.com/dfahlander/Dexie.js/wiki/db.syncable.on('statusChanged')) Event triggered when sync status changes. [db.syncable.setFilter ([criteria], filter)](https://github.com/dfahlander/Dexie.js/wiki/db.syncable.setFilter()) Ignore certain objects from being synced defined by given filter. [db.syncable.getStatus (url)](https://github.com/dfahlander/Dexie.js/wiki/db.syncable.getStatus()) Get sync status for given URL. ### Source [Dexie.Syncable.js](https://github.com/dfahlander/Dexie.js/blob/master/addons/Dexie.Syncable/src/Dexie.Syncable.js) ### Description Dexie.Syncable enables syncronization with a remote database (of almost any kind). It has it's own API [ISyncProtocol](Dexie.Syncable.ISyncProtocol). The [ISyncProtocol](https://github.com/dfahlander/Dexie.js/wiki/Dexie.Syncable.ISyncProtocol) is pretty straight-forward to implement. The implementation of that API defines how client- and server- changes are transported between local and remote nodes. The API support both poll-patterns (such as ajax calls) and direct reaction pattern (such as WebSocket or long-polling methods). See samples below for each pattern. ### Sample [ISyncProtocol](Dexie.Syncable.ISyncProtocol) Implementations * [AjaxSyncProtocol.js](https://github.com/dfahlander/Dexie.js/blob/master/samples/remote-sync/ajax/AjaxSyncProtocol.js) * [WebSocketSyncProtocol.js](https://github.com/dfahlander/Dexie.js/blob/master/samples/remote-sync/websocket/WebSocketSyncProtocol.js) ### Sample Sync Servers * [WebSocketSyncServer.js](https://github.com/dfahlander/Dexie.js/blob/master/samples/remote-sync/websocket/WebSocketSyncServer.js)
{ "content_hash": "f1feffe8674b807e3de1c8923b9bea1f", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 744, "avg_line_length": 53.6796875, "alnum_prop": 0.7512734681996798, "repo_name": "intermittent-fasting/intermittent-fasting", "id": "b50282b0fc4d89e347eacd159df170c89372e3a1", "size": "6892", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/assets/js/bower/dexie/addons/Dexie.Syncable/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5183" }, { "name": "HTML", "bytes": "11200" }, { "name": "JavaScript", "bytes": "6754396" }, { "name": "Makefile", "bytes": "690" }, { "name": "Shell", "bytes": "2715" } ], "symlink_target": "" }
from odoo import api, models from odoo.tools.translate import _ PARAMS = [ ("web_debranding.new_name", _("Software")), ("web_debranding.new_title", _("Software")), ("web_debranding.new_website", "example.com"), ("web_debranding.new_documentation_website", ""), ("web_debranding.favicon_url", ""), ("web_debranding.send_publisher_warranty_url", "0"), ("web_debranding.icon_url", ""), ("web_debranding.apple_touch_icon_url", ""), ] def get_debranding_parameters_env(env): res = {} for param, default in PARAMS: value = env["ir.config_parameter"].sudo().get_param(param, default) res[param] = value.strip() return res class IrConfigParameter(models.Model): _inherit = "ir.config_parameter" @api.model def get_debranding_parameters(self): return get_debranding_parameters_env(self.env) @api.model def create_debranding_parameters(self): for param, default in PARAMS: if not self.env["ir.config_parameter"].sudo().get_param(param): self.env["ir.config_parameter"].sudo().set_param(param, default or " ")
{ "content_hash": "1d572db3a5b57ab6f5d8abcdba43dd20", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 87, "avg_line_length": 32.285714285714285, "alnum_prop": 0.6389380530973451, "repo_name": "it-projects-llc/misc-addons", "id": "50e1ba9f1e278b0224cdf58e7ab1207c822baea0", "size": "1616", "binary": false, "copies": "1", "ref": "refs/heads/13.0", "path": "web_debranding/models/ir_config_parameter.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14551" }, { "name": "HTML", "bytes": "130934" }, { "name": "JavaScript", "bytes": "407608" }, { "name": "Python", "bytes": "414883" } ], "symlink_target": "" }
from __future__ import unicode_literals from django import forms from django.contrib import admin from django.contrib.auth import get_user_model from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from reviewers import review_group_name from reviewers.models import Review, Reviewer from .actions import export_as_csv_action class ReviewAdminForm(forms.ModelForm): class Meta: model = Review fields = "__all__" def __init__(self, *args, **kwargs): super(ReviewAdminForm, self).__init__(*args, **kwargs) self.fields["user"].queryset = get_user_model().objects.filter( Q(groups__name=review_group_name) | Q(is_superuser=True) ) def clean(self): cleaned_data = super(ReviewAdminForm, self).clean() user = cleaned_data.get("user") proposal = cleaned_data.get("proposal") if user == proposal.speaker.user: raise forms.ValidationError("You can not asign a review to its author!") @admin.register(Review) class ReviewAdmin(admin.ModelAdmin): list_display = ["id", "proposal", "user", "relevance", "interest", "newness", "get_avg", "conflict", "finished", "created"] list_filter = ["proposal", "user", "conflict", "finished"] actions = [ export_as_csv_action("CSV Export", fields=[ "id", "proposal", "user", "relevance", "interest", "newness", "avg_property", "conflict", "finished", "created", ]) ] form = ReviewAdminForm def get_avg(self, instance): return instance.avg() get_avg.short_description = _("Media") @admin.register(Reviewer) class ReviewerAdmin(admin.ModelAdmin): list_display = ["id", "user", "get_reviews", "created"] def get_reviews(self, instance): return instance.reviews_count() get_reviews.short_description = _("Revisiones")
{ "content_hash": "6b8376410b797a5b94250e3adf571ab3", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 116, "avg_line_length": 29.115942028985508, "alnum_prop": 0.6122448979591837, "repo_name": "olea/PyConES-2016", "id": "97b079425220fd30d9ad23ffd4f5b0af07b3ef95", "size": "2033", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "pycones/reviewers/admin.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "142786" }, { "name": "HTML", "bytes": "88272" }, { "name": "JavaScript", "bytes": "677" }, { "name": "Python", "bytes": "304958" }, { "name": "Shell", "bytes": "488" } ], "symlink_target": "" }
In this folder, we keep our _fuzzers_ (bits of code that takes a randomized input and executes code randomly, focusing on specific APIs). For example, we have a codec fuzzer which takes a mutated png/jpeg or similar file and attempts to turn it into an `SkImage`. We also have a canvas fuzzer which takes in a random set of bytes and turns them into calls on `SkCanvas`. ## Executables These fuzzers are packaged in two different ways (see //BUILD.gn). There is a `fuzz` executable that contains all fuzzers and is a convenient way to reproduce fuzzer-reported bugs. There are also single fuzzer executables containing exactly one fuzzer, which are convenient to build with [libfuzzer](https://llvm.org/docs/LibFuzzer.html). See [../site/dev/testing/fuzz.md] for more information on building and running fuzzers using the `fuzz` executable. ## Continuous Running We fuzz Skia using [OSS-Fuzz](https://github.com/google/oss-fuzz), which in turn uses fuzzing engines such as libfuzzer, afl-fuzz, hong-fuzz, and others to fuzz Skia. OSS-fuzz will automatically [file and close bugs](https://bugs.chromium.org/p/oss-fuzz/issues/list?q=label:Proj-skia) when it finds issues. There is a [Skia folder](https://github.com/google/oss-fuzz/tree/master/projects/skia) in the OSS-Fuzz repo that we make changes to when we want to add/remove/change the fuzzers that are automatically run. [This](https://google.github.io/oss-fuzz/getting-started/new-project-guide/#testing-locally) describes how to test the OSS-Fuzz build and fuzzers locally using Docker. When enabling a fuzzer in OSS-Fuzz, we typically need to follow these steps: 1. *Add a seed corpus to `gs://skia-fuzzer/oss-fuzz/` (in the [skia-public project](https://console.cloud.google.com/storage/browser/skia-fuzzer?project=skia-public)). Make sure the corpus file is public-readable. It is easiest to add this permission via the web UI. This is done by granting the allUsers "name" the Reader role to the zip file. See the infra team if you do not have access to this bucket. 2. *Update [the Dockerfile](https://github.com/google/oss-fuzz/blob/master/projects/skia/Dockerfile) to download the seed corpus to the build image. 3. Update [build.sh](https://github.com/google/oss-fuzz/blob/628264df27f53cc60fcb27406a2da05d2197c025/projects/skia/build.sh#L99) to build the desired fuzzer target and move it into $OUT. If there is a seed corpus, move it into $OUT and make sure it is the same name as the fuzzer executable with `_seed_corpus.zip` as a suffix. *For fuzzers who depend strongly on the format of the randomized data, e.g. image decoding, SkSL parsing. These are called _binary fuzzers_, as opposed to _API fuzzers_. Example PRs for adding fuzzers: [binary](https://github.com/google/oss-fuzz/pull/4108), [API](https://github.com/google/oss-fuzz/pull/5657) There is also an [OSS-fuzz folder](https://github.com/google/oss-fuzz/tree/master/projects/skcms) set up for the [skcms repo](https://skia.googlesource.com/skcms/). The build process is similar, except instead of compiling using GN targets, the build.sh script compiles the fuzz executables directly. ### OSS-Fuzz dashboard <https://oss-fuzz.com/fuzzer-stats> is useful to see metrics on how our fuzzers are running. It shows things like executions per second (higher is better), edge coverage percent per fuzzer, what percent of fuzzing runs end in OOM/timeout/crash, the entire corpus of fuzzed inputs (corpus_backup), etc. Contact aarya@ to get permission to view this dashboard if necessary. Here are some example dashboards: - [Per Fuzzer summary for all Skia fuzzers driven by libFuzzer](https://oss-fuzz.com/fuzzer-stats?group_by=by-fuzzer&date_start=2021-08-16&date_end=2021-08-22&fuzzer=libFuzzer&job=libfuzzer_asan_skia&project=skia) - [Five day summary of sksl2glsl driven by afl-fuzz](https://oss-fuzz.com/fuzzer-stats?group_by=by-day&date_start=2021-08-16&date_end=2021-08-22&fuzzer=afl_skia_sksl2glsl&job=afl_asan_skia&project=skia) That dashboard also has a Coverage Report. Even though it appears the Coverage report is per fuzzer, the reports always show the aggregated coverage from all fuzzers. [Example coverage report from 2021 Aug 22](https://storage.googleapis.com/oss-fuzz-coverage/skia/reports/20210822/linux/report.html) ## See Also - [Creating a binary fuzzer](https://docs.google.com/document/d/1QDX0o8yDdmhbjoudNsXc66iuRXRF5XNNqGnzDzX7c2I/edit) - [Creating an API fuzzer](https://docs.google.com/document/d/1e3ikXO7SwoBsbsi1MF06vydXRlXvYalVORaiUuOXk2Y/edit)
{ "content_hash": "ce526409fa799dd3a5e7ba7ee34f7dcd", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 214, "avg_line_length": 68.13432835820896, "alnum_prop": 0.7743702081051479, "repo_name": "aosp-mirror/platform_external_skia", "id": "43a9234533d9661afa88893f7205441c17090375", "size": "4574", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "fuzz/README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "12716940" }, { "name": "Batchfile", "bytes": "904" }, { "name": "C", "bytes": "620774" }, { "name": "C#", "bytes": "4683" }, { "name": "C++", "bytes": "27394853" }, { "name": "GLSL", "bytes": "67013" }, { "name": "Go", "bytes": "80137" }, { "name": "HTML", "bytes": "1002516" }, { "name": "Java", "bytes": "32794" }, { "name": "JavaScript", "bytes": "51666" }, { "name": "Lex", "bytes": "4372" }, { "name": "Lua", "bytes": "70974" }, { "name": "Makefile", "bytes": "2295" }, { "name": "Objective-C", "bytes": "35223" }, { "name": "Objective-C++", "bytes": "34410" }, { "name": "PHP", "bytes": "120845" }, { "name": "Python", "bytes": "1002226" }, { "name": "Shell", "bytes": "49974" } ], "symlink_target": "" }
{% extends "base.html" %} {% load centinela_column %} {% load centinela_socialshare %} {% load staticfiles %} {% load addclass %} {% block title %} Artist - {{ block.super }} {% endblock %} {% block content %} <div class="banner container-fluid col-md-10 col-md-offset-1" style=""> {% include "centinela/banners.html" %} </div> {% if site.LATERAL_BAR == 'LEFT' %} <div id="lateral" class="col-md-3 col-sm-12"> {% get_more_read %} {% get_lateral_widgets %} </div> {% endif %} <div id="main" class="col-md-7 col-md-offset-1 col-xs-12" itemscope itemtype="http://schema.org/newsArticle"> {% include "centinela/nav_sections.html" %} <h2 itemprop="headline">Registro de Artista</h2> <hr class="feature-divider>"> <form class="form" action="" method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.errors }} {% for field in form %} <div class="form-group"> {{ field.label_tag }} {{ field.errors}} {% if field.help_text %} <p class="help-block">{{ field.help_text }}</p> {% endif %} {{ field|addclass:'form-control' }} </div> {% endfor %} <input class="btn btn-success" type="submit" value="Registrar" /> </form> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- sky3 adaptable prospectiva --> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7406359102676080" data-ad-slot="2169856764" data-ad-format="auto"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} </div> {% if site.LATERAL_BAR == 'RIGHT' %} <div id="lateral" class="col-md-3 col-sm-12"> {% get_more_read %} {% get_lateral_widgets %} </div> {% endif %} {% endblock %}
{ "content_hash": "76844a2e3a650f8c3c9d1c13bdf8d9c6", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 109, "avg_line_length": 30.677419354838708, "alnum_prop": 0.5862250262881178, "repo_name": "esbozos/megax", "id": "7d6cfc902874ae1cdb048efcadeaa2594471ac67", "size": "1902", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "centinela_cms/megaXID/templates/megaXID/artist_form.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "293304" }, { "name": "HTML", "bytes": "27807" }, { "name": "JavaScript", "bytes": "4448" }, { "name": "Python", "bytes": "45198" } ], "symlink_target": "" }
<?php namespace Eliurkis\Crud\FieldTypes; class Foreign { public static function prepare($name, $options = [], $value = null, $properties = []) { // Define the total of columns $colsSize = 12 / $properties['config']['cols']; $html = '<div class="row i-checks">'; foreach ($options as $key => $option) { $uniqueId = uniqid('opt', true).md5(mt_rand(1, 1000)); $html .= '<div class="col-md-'.$colsSize.' col-xs-12">'. \Form::checkbox($name.'[]', $key, in_array($key, (array) $value), ['id' => $uniqueId]). \Form::label($uniqueId, $option). '</div>'; } $html .= '</div>'; return $html; } }
{ "content_hash": "1c02eef8a00dce254916b55aa53ef041", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 103, "avg_line_length": 29.84, "alnum_prop": 0.48525469168900803, "repo_name": "eliurkis/crud", "id": "aa026dafd4ba9198db6ec300a8465a703f07d9f4", "size": "746", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/FieldTypes/Foreign.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "12253" }, { "name": "PHP", "bytes": "35695" } ], "symlink_target": "" }
package org.springframework.security.config.http; import java.util.*; import javax.servlet.Filter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.web.DefaultSecurityFilterChain; import org.springframework.security.web.FilterChainProxy; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.ExceptionTranslationFilter; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import org.springframework.security.web.authentication.AnonymousAuthenticationFilter; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.context.SecurityContextPersistenceFilter; import org.springframework.security.web.jaasapi.JaasApiIntegrationFilter; import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter; import org.springframework.security.web.session.SessionManagementFilter; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.AnyRequestMatcher; public class DefaultFilterChainValidator implements FilterChainProxy.FilterChainValidator { private final Log logger = LogFactory.getLog(getClass()); public void validate(FilterChainProxy fcp) { for (SecurityFilterChain filterChain : fcp.getFilterChains()) { checkLoginPageIsntProtected(fcp, filterChain.getFilters()); checkFilterStack(filterChain.getFilters()); } checkPathOrder(new ArrayList<>(fcp.getFilterChains())); checkForDuplicateMatchers(new ArrayList<>( fcp.getFilterChains())); } private void checkPathOrder(List<SecurityFilterChain> filterChains) { // Check that the universal pattern is listed at the end, if at all Iterator<SecurityFilterChain> chains = filterChains.iterator(); while (chains.hasNext()) { RequestMatcher matcher = ((DefaultSecurityFilterChain) chains.next()) .getRequestMatcher(); if (AnyRequestMatcher.INSTANCE.equals(matcher) && chains.hasNext()) { throw new IllegalArgumentException( "A universal match pattern ('/**') is defined " + " before other patterns in the filter chain, causing them to be ignored. Please check the " + "ordering in your <security:http> namespace or FilterChainProxy bean configuration"); } } } private void checkForDuplicateMatchers(List<SecurityFilterChain> chains) { while (chains.size() > 1) { DefaultSecurityFilterChain chain = (DefaultSecurityFilterChain) chains .remove(0); for (SecurityFilterChain test : chains) { if (chain.getRequestMatcher().equals( ((DefaultSecurityFilterChain) test).getRequestMatcher())) { throw new IllegalArgumentException( "The FilterChainProxy contains two filter chains using the" + " matcher " + chain.getRequestMatcher() + ". If you are using multiple <http> namespace " + "elements, you must use a 'pattern' attribute to define the request patterns to which they apply."); } } } } @SuppressWarnings({ "unchecked" }) private <F extends Filter> F getFilter(Class<F> type, List<Filter> filters) { for (Filter f : filters) { if (type.isAssignableFrom(f.getClass())) { return (F) f; } } return null; } /** * Checks the filter list for possible errors and logs them */ private void checkFilterStack(List<Filter> filters) { checkForDuplicates(SecurityContextPersistenceFilter.class, filters); checkForDuplicates(UsernamePasswordAuthenticationFilter.class, filters); checkForDuplicates(SessionManagementFilter.class, filters); checkForDuplicates(BasicAuthenticationFilter.class, filters); checkForDuplicates(SecurityContextHolderAwareRequestFilter.class, filters); checkForDuplicates(JaasApiIntegrationFilter.class, filters); checkForDuplicates(ExceptionTranslationFilter.class, filters); checkForDuplicates(FilterSecurityInterceptor.class, filters); } private void checkForDuplicates(Class<? extends Filter> clazz, List<Filter> filters) { for (int i = 0; i < filters.size(); i++) { Filter f1 = filters.get(i); if (clazz.isAssignableFrom(f1.getClass())) { // Found the first one, check remaining for another for (int j = i + 1; j < filters.size(); j++) { Filter f2 = filters.get(j); if (clazz.isAssignableFrom(f2.getClass())) { logger.warn("Possible error: Filters at position " + i + " and " + j + " are both " + "instances of " + clazz.getName()); return; } } } } } /* * Checks for the common error of having a login page URL protected by the security * interceptor */ private void checkLoginPageIsntProtected(FilterChainProxy fcp, List<Filter> filterStack) { ExceptionTranslationFilter etf = getFilter(ExceptionTranslationFilter.class, filterStack); if (etf == null || !(etf.getAuthenticationEntryPoint() instanceof LoginUrlAuthenticationEntryPoint)) { return; } String loginPage = ((LoginUrlAuthenticationEntryPoint) etf .getAuthenticationEntryPoint()).getLoginFormUrl(); logger.info("Checking whether login URL '" + loginPage + "' is accessible with your configuration"); FilterInvocation loginRequest = new FilterInvocation(loginPage, "POST"); List<Filter> filters = null; try { filters = fcp.getFilters(loginPage); } catch (Exception e) { // May happen legitimately if a filter-chain request matcher requires more // request data than that provided // by the dummy request used when creating the filter invocation. logger.info("Failed to obtain filter chain information for the login page. Unable to complete check."); } if (filters == null || filters.isEmpty()) { logger.debug("Filter chain is empty for the login page"); return; } if (getFilter(DefaultLoginPageGeneratingFilter.class, filters) != null) { logger.debug("Default generated login page is in use"); return; } FilterSecurityInterceptor fsi = getFilter(FilterSecurityInterceptor.class, filters); FilterInvocationSecurityMetadataSource fids = fsi.getSecurityMetadataSource(); Collection<ConfigAttribute> attributes = fids.getAttributes(loginRequest); if (attributes == null) { logger.debug("No access attributes defined for login page URL"); if (fsi.isRejectPublicInvocations()) { logger.warn("FilterSecurityInterceptor is configured to reject public invocations." + " Your login page may not be accessible."); } return; } AnonymousAuthenticationFilter anonPF = getFilter( AnonymousAuthenticationFilter.class, filters); if (anonPF == null) { logger.warn("The login page is being protected by the filter chain, but you don't appear to have" + " anonymous authentication enabled. This is almost certainly an error."); return; } // Simulate an anonymous access with the supplied attributes. AnonymousAuthenticationToken token = new AnonymousAuthenticationToken("key", anonPF.getPrincipal(), anonPF.getAuthorities()); try { fsi.getAccessDecisionManager().decide(token, loginRequest, attributes); } catch (AccessDeniedException e) { logger.warn("Anonymous access to the login page doesn't appear to be enabled. This is almost certainly " + "an error. Please check your configuration allows unauthenticated access to the configured " + "login page. (Simulated access was rejected: " + e + ")"); } catch (Exception e) { // May happen legitimately if a filter-chain request matcher requires more // request data than that provided // by the dummy request used when creating the filter invocation. See SEC-1878 logger.info( "Unable to check access to the login page to determine if anonymous access is allowed. This might be an error, but can happen under normal circumstances.", e); } } }
{ "content_hash": "79cb08d0d08ee3c4c77ce1e9637400e1", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 160, "avg_line_length": 40.79904306220096, "alnum_prop": 0.757945350064501, "repo_name": "kazuki43zoo/spring-security", "id": "4442b39728365fa047faa42e50341cc68d8e3da7", "size": "9147", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "config/src/main/java/org/springframework/security/config/http/DefaultFilterChainValidator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "3441" }, { "name": "Groovy", "bytes": "482315" }, { "name": "HTML", "bytes": "114" }, { "name": "Java", "bytes": "7728590" }, { "name": "JavaScript", "bytes": "10" }, { "name": "PLSQL", "bytes": "3180" }, { "name": "Python", "bytes": "129" }, { "name": "Shell", "bytes": "439" }, { "name": "XSLT", "bytes": "2344" } ], "symlink_target": "" }
// // Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /// <reference path='services.ts' /> /* @internal */ let debugObjectHost = (function (this: any) { return this; })(); // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ /* tslint:disable:no-in-operator */ /* @internal */ namespace ts { export interface ScriptSnapshotShim { /** Gets a portion of the script snapshot specified by [start, end). */ getText(start: number, end: number): string; /** Gets the length of this script snapshot. */ getLength(): number; /** * Returns a JSON-encoded value of the type: * { span: { start: number; length: number }; newLength: number } * * Or undefined value if there was no change. */ getChangeRange(oldSnapshot: ScriptSnapshotShim): string; /** Releases all resources held by this script snapshot */ dispose?(): void; } export interface Logger { log(s: string): void; trace(s: string): void; error(s: string): void; } /** Public interface of the host of a language service shim instance.*/ export interface LanguageServiceShimHost extends Logger { getCompilationSettings(): string; /** Returns a JSON-encoded value of the type: string[] */ getScriptFileNames(): string; getScriptKind?(fileName: string): ScriptKind; getScriptVersion(fileName: string): string; getScriptSnapshot(fileName: string): ScriptSnapshotShim; getLocalizedDiagnosticMessages(): string; getCancellationToken(): HostCancellationToken; getCurrentDirectory(): string; getDirectories(path: string): string; getDefaultLibFileName(options: string): string; getNewLine?(): string; getProjectVersion?(): string; useCaseSensitiveFileNames?(): boolean; getTypeRootsVersion?(): number; readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; readFile(path: string, encoding?: string): string; fileExists(path: string): boolean; getModuleResolutionsForFile?(fileName: string): string; getTypeReferenceDirectiveResolutionsForFile?(fileName: string): string; directoryExists(directoryName: string): boolean; } /** Public interface of the core-services host instance used in managed side */ export interface CoreServicesShimHost extends Logger { directoryExists(directoryName: string): boolean; fileExists(fileName: string): boolean; getCurrentDirectory(): string; getDirectories(path: string): string; /** * Returns a JSON-encoded value of the type: string[] * * @param exclude A JSON encoded string[] containing the paths to exclude * when enumerating the directory. */ readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; /** * Read arbitary text files on disk, i.e. when resolution procedure needs the content of 'package.json' to determine location of bundled typings for node modules */ readFile(fileName: string): string; realpath?(path: string): string; trace(s: string): void; useCaseSensitiveFileNames?(): boolean; } /// /// Pre-processing /// // Note: This is being using by the host (VS) and is marshaled back and forth. // When changing this make sure the changes are reflected in the managed side as well export interface IFileReference { path: string; position: number; length: number; } /** Public interface of a language service instance shim. */ export interface ShimFactory { registerShim(shim: Shim): void; unregisterShim(shim: Shim): void; } export interface Shim { dispose(_dummy: any): void; } export interface LanguageServiceShim extends Shim { languageService: LanguageService; dispose(_dummy: any): void; refresh(throwOnError: boolean): void; cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): string; getSemanticDiagnostics(fileName: string): string; getCompilerOptionsDiagnostics(): string; getSyntacticClassifications(fileName: string, start: number, length: number): string; getSemanticClassifications(fileName: string, start: number, length: number): string; getEncodedSyntacticClassifications(fileName: string, start: number, length: number): string; getEncodedSemanticClassifications(fileName: string, start: number, length: number): string; getCompletionsAtPosition(fileName: string, position: number): string; getCompletionEntryDetails(fileName: string, position: number, entryName: string): string; getQuickInfoAtPosition(fileName: string, position: number): string; getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string; getBreakpointStatementAtPosition(fileName: string, position: number): string; getSignatureHelpItems(fileName: string, position: number): string; /** * Returns a JSON-encoded value of the type: * { canRename: boolean, localizedErrorMessage: string, displayName: string, fullDisplayName: string, kind: string, kindModifiers: string, triggerSpan: { start; length } } */ getRenameInfo(fileName: string, position: number): string; /** * Returns a JSON-encoded value of the type: * { fileName: string, textSpan: { start: number, length: number } }[] */ findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string; /** * Returns a JSON-encoded value of the type: * { fileName: string; textSpan: { start: number; length: number}; kind: string; name: string; containerKind: string; containerName: string } * * Or undefined value if no definition can be found. */ getDefinitionAtPosition(fileName: string, position: number): string; /** * Returns a JSON-encoded value of the type: * { fileName: string; textSpan: { start: number; length: number}; kind: string; name: string; containerKind: string; containerName: string } * * Or undefined value if no definition can be found. */ getTypeDefinitionAtPosition(fileName: string, position: number): string; /** * Returns a JSON-encoded value of the type: * { fileName: string; textSpan: { start: number; length: number}; }[] */ getImplementationAtPosition(fileName: string, position: number): string; /** * Returns a JSON-encoded value of the type: * { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean, isDefinition?: boolean }[] */ getReferencesAtPosition(fileName: string, position: number): string; /** * Returns a JSON-encoded value of the type: * { definition: <encoded>; references: <encoded>[] }[] */ findReferences(fileName: string, position: number): string; /** * @deprecated * Returns a JSON-encoded value of the type: * { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[] */ getOccurrencesAtPosition(fileName: string, position: number): string; /** * Returns a JSON-encoded value of the type: * { fileName: string; highlights: { start: number; length: number, isDefinition: boolean }[] }[] * * @param fileToSearch A JSON encoded string[] containing the file names that should be * considered when searching. */ getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string; /** * Returns a JSON-encoded value of the type: * { name: string; kind: string; kindModifiers: string; containerName: string; containerKind: string; matchKind: string; fileName: string; textSpan: { start: number; length: number}; } [] = []; */ getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): string; /** * Returns a JSON-encoded value of the type: * { text: string; kind: string; kindModifiers: string; bolded: boolean; grayed: boolean; indent: number; spans: { start: number; length: number; }[]; childItems: <recursive use of this type>[] } [] = []; */ getNavigationBarItems(fileName: string): string; /** Returns a JSON-encoded value of the type ts.NavigationTree. */ getNavigationTree(fileName: string): string; /** * Returns a JSON-encoded value of the type: * { textSpan: { start: number, length: number }; hintSpan: { start: number, length: number }; bannerText: string; autoCollapse: boolean } [] = []; */ getOutliningSpans(fileName: string): string; getTodoComments(fileName: string, todoCommentDescriptors: string): string; getBraceMatchingAtPosition(fileName: string, position: number): string; getIndentationAtPosition(fileName: string, position: number, options: string/*Services.EditorOptions*/): string; getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string; getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string; getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string; /** * Returns JSON-encoded value of the type TextInsertion. */ getDocCommentTemplateAtPosition(fileName: string, position: number): string; /** * Returns JSON-encoded boolean to indicate whether we should support brace location * at the current position. * E.g. we don't want brace completion inside string-literals, comments, etc. */ isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): string; getEmitOutput(fileName: string): string; getEmitOutputObject(fileName: string): EmitOutput; } export interface ClassifierShim extends Shim { getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string; getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string; } export interface CoreServicesShim extends Shim { getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string; getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): string; getTSConfigFileInfo(fileName: string, sourceText: IScriptSnapshot): string; getDefaultCompilationSettings(): string; discoverTypings(discoverTypingsJson: string): string; } function logInternalError(logger: Logger, err: Error) { if (logger) { logger.log("*INTERNAL ERROR* - Exception in typescript services: " + err.message); } } class ScriptSnapshotShimAdapter implements IScriptSnapshot { constructor(private scriptSnapshotShim: ScriptSnapshotShim) { } public getText(start: number, end: number): string { return this.scriptSnapshotShim.getText(start, end); } public getLength(): number { return this.scriptSnapshotShim.getLength(); } public getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange { const oldSnapshotShim = <ScriptSnapshotShimAdapter>oldSnapshot; const encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim); // TODO: should this be '==='? if (encoded == null) { return null; } const decoded: { span: { start: number; length: number; }; newLength: number; } = JSON.parse(encoded); return createTextChangeRange( createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); } public dispose(): void { // if scriptSnapshotShim is a COM object then property check becomes method call with no arguments // 'in' does not have this effect if ("dispose" in this.scriptSnapshotShim) { this.scriptSnapshotShim.dispose(); } } } export class LanguageServiceShimHostAdapter implements LanguageServiceHost { private files: string[]; private loggingEnabled = false; private tracingEnabled = false; public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModule[]; public resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[]; public directoryExists: (directoryName: string) => boolean; constructor(private shimHost: LanguageServiceShimHost) { // if shimHost is a COM object then property check will become method call with no arguments. // 'in' does not have this effect. if ("getModuleResolutionsForFile" in this.shimHost) { this.resolveModuleNames = (moduleNames: string[], containingFile: string) => { const resolutionsInFile = <MapLike<string>>JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile)); return map(moduleNames, name => { const result = getProperty(resolutionsInFile, name); return result ? { resolvedFileName: result, extension: extensionFromPath(result), isExternalLibraryImport: false } : undefined; }); }; } if ("directoryExists" in this.shimHost) { this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName); } if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) { this.resolveTypeReferenceDirectives = (typeDirectiveNames: string[], containingFile: string) => { const typeDirectivesForFile = <MapLike<ResolvedTypeReferenceDirective>>JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile)); return map(typeDirectiveNames, name => getProperty(typeDirectivesForFile, name)); }; } } public log(s: string): void { if (this.loggingEnabled) { this.shimHost.log(s); } } public trace(s: string): void { if (this.tracingEnabled) { this.shimHost.trace(s); } } public error(s: string): void { this.shimHost.error(s); } public getProjectVersion(): string { if (!this.shimHost.getProjectVersion) { // shimmed host does not support getProjectVersion return undefined; } return this.shimHost.getProjectVersion(); } public getTypeRootsVersion(): number { if (!this.shimHost.getTypeRootsVersion) { return 0; } return this.shimHost.getTypeRootsVersion(); } public useCaseSensitiveFileNames(): boolean { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; } public getCompilationSettings(): CompilerOptions { const settingsJson = this.shimHost.getCompilationSettings(); // TODO: should this be '==='? if (settingsJson == null || settingsJson == "") { throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); } return <CompilerOptions>JSON.parse(settingsJson); } public getScriptFileNames(): string[] { const encoded = this.shimHost.getScriptFileNames(); return this.files = JSON.parse(encoded); } public getScriptSnapshot(fileName: string): IScriptSnapshot { const scriptSnapshot = this.shimHost.getScriptSnapshot(fileName); return scriptSnapshot && new ScriptSnapshotShimAdapter(scriptSnapshot); } public getScriptKind(fileName: string): ScriptKind { if ("getScriptKind" in this.shimHost) { return this.shimHost.getScriptKind(fileName); } else { return ScriptKind.Unknown; } } public getScriptVersion(fileName: string): string { return this.shimHost.getScriptVersion(fileName); } public getLocalizedDiagnosticMessages(): any { const diagnosticMessagesJson = this.shimHost.getLocalizedDiagnosticMessages(); if (diagnosticMessagesJson == null || diagnosticMessagesJson == "") { return null; } try { return JSON.parse(diagnosticMessagesJson); } catch (e) { this.log(e.description || "diagnosticMessages.generated.json has invalid JSON format"); return null; } } public getCancellationToken(): HostCancellationToken { const hostCancellationToken = this.shimHost.getCancellationToken(); return new ThrottledCancellationToken(hostCancellationToken); } public getCurrentDirectory(): string { return this.shimHost.getCurrentDirectory(); } public getDirectories(path: string): string[] { return JSON.parse(this.shimHost.getDirectories(path)); } public getDefaultLibFileName(options: CompilerOptions): string { return this.shimHost.getDefaultLibFileName(JSON.stringify(options)); } public readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[], depth?: number): string[] { const pattern = getFileMatcherPatterns(path, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); return JSON.parse(this.shimHost.readDirectory( path, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth )); } public readFile(path: string, encoding?: string): string { return this.shimHost.readFile(path, encoding); } public fileExists(path: string): boolean { return this.shimHost.fileExists(path); } } /** A cancellation that throttles calls to the host */ class ThrottledCancellationToken implements HostCancellationToken { // Store when we last tried to cancel. Checking cancellation can be expensive (as we have // to marshall over to the host layer). So we only bother actually checking once enough // time has passed. private lastCancellationCheckTime = 0; constructor(private hostCancellationToken: HostCancellationToken) { } public isCancellationRequested(): boolean { const time = timestamp(); const duration = Math.abs(time - this.lastCancellationCheckTime); if (duration > 10) { // Check no more than once every 10 ms. this.lastCancellationCheckTime = time; return this.hostCancellationToken.isCancellationRequested(); } return false; } } export class CoreServicesShimHostAdapter implements ParseConfigHost, ModuleResolutionHost { public directoryExists: (directoryName: string) => boolean; public realpath: (path: string) => string; public useCaseSensitiveFileNames: boolean; constructor(private shimHost: CoreServicesShimHost) { this.useCaseSensitiveFileNames = this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; if ("directoryExists" in this.shimHost) { this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName); } if ("realpath" in this.shimHost) { this.realpath = path => this.shimHost.realpath(path); } } public readDirectory(rootDir: string, extensions: string[], exclude: string[], include: string[], depth?: number): string[] { // Wrap the API changes for 2.0 release. This try/catch // should be removed once TypeScript 2.0 has shipped. try { const pattern = getFileMatcherPatterns(rootDir, exclude, include, this.shimHost.useCaseSensitiveFileNames(), this.shimHost.getCurrentDirectory()); return JSON.parse(this.shimHost.readDirectory( rootDir, JSON.stringify(extensions), JSON.stringify(pattern.basePaths), pattern.excludePattern, pattern.includeFilePattern, pattern.includeDirectoryPattern, depth )); } catch (e) { const results: string[] = []; for (const extension of extensions) { for (const file of this.readDirectoryFallback(rootDir, extension, exclude)) { if (!contains(results, file)) { results.push(file); } } } return results; } } public fileExists(fileName: string): boolean { return this.shimHost.fileExists(fileName); } public readFile(fileName: string): string { return this.shimHost.readFile(fileName); } private readDirectoryFallback(rootDir: string, extension: string, exclude: string[]) { return JSON.parse(this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude))); } public getDirectories(path: string): string[] { return JSON.parse(this.shimHost.getDirectories(path)); } } function simpleForwardCall(logger: Logger, actionDescription: string, action: () => any, logPerformance: boolean): any { let start: number; if (logPerformance) { logger.log(actionDescription); start = timestamp(); } const result = action(); if (logPerformance) { const end = timestamp(); logger.log(`${actionDescription} completed in ${end - start} msec`); if (typeof result === "string") { let str = result; if (str.length > 128) { str = str.substring(0, 128) + "..."; } logger.log(` result.length=${str.length}, result='${JSON.stringify(str)}'`); } } return result; } function forwardJSONCall(logger: Logger, actionDescription: string, action: () => any, logPerformance: boolean): string { return <string>forwardCall(logger, actionDescription, /*returnJson*/ true, action, logPerformance); } function forwardCall<T>(logger: Logger, actionDescription: string, returnJson: boolean, action: () => T, logPerformance: boolean): T | string { try { const result = simpleForwardCall(logger, actionDescription, action, logPerformance); return returnJson ? JSON.stringify({ result }) : result; } catch (err) { if (err instanceof OperationCanceledException) { return JSON.stringify({ canceled: true }); } logInternalError(logger, err); err.description = actionDescription; return JSON.stringify({ error: err }); } } class ShimBase implements Shim { constructor(private factory: ShimFactory) { factory.registerShim(this); } public dispose(_dummy: any): void { this.factory.unregisterShim(this); } } export function realizeDiagnostics(diagnostics: Diagnostic[], newLine: string): { message: string; start: number; length: number; category: string; code: number; }[] { return diagnostics.map(d => realizeDiagnostic(d, newLine)); } function realizeDiagnostic(diagnostic: Diagnostic, newLine: string): { message: string; start: number; length: number; category: string; code: number; } { return { message: flattenDiagnosticMessageText(diagnostic.messageText, newLine), start: diagnostic.start, length: diagnostic.length, /// TODO: no need for the tolowerCase call category: DiagnosticCategory[diagnostic.category].toLowerCase(), code: diagnostic.code }; } class LanguageServiceShimObject extends ShimBase implements LanguageServiceShim { private logger: Logger; private logPerformance = false; constructor(factory: ShimFactory, private host: LanguageServiceShimHost, public languageService: LanguageService) { super(factory); this.logger = this.host; } public forwardJSONCall(actionDescription: string, action: () => any): string { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); } /// DISPOSE /** * Ensure (almost) deterministic release of internal Javascript resources when * some external native objects holds onto us (e.g. Com/Interop). */ public dispose(dummy: any): void { this.logger.log("dispose()"); this.languageService.dispose(); this.languageService = null; // force a GC if (debugObjectHost && debugObjectHost.CollectGarbage) { debugObjectHost.CollectGarbage(); this.logger.log("CollectGarbage()"); } this.logger = null; super.dispose(dummy); } /// REFRESH /** * Update the list of scripts known to the compiler */ public refresh(throwOnError: boolean): void { this.forwardJSONCall( `refresh(${throwOnError})`, () => <any>null ); } public cleanupSemanticCache(): void { this.forwardJSONCall( "cleanupSemanticCache()", () => { this.languageService.cleanupSemanticCache(); return <any>null; }); } private realizeDiagnostics(diagnostics: Diagnostic[]): { message: string; start: number; length: number; category: string; }[] { const newLine = getNewLineOrDefaultFromHost(this.host); return ts.realizeDiagnostics(diagnostics, newLine); } public getSyntacticClassifications(fileName: string, start: number, length: number): string { return this.forwardJSONCall( `getSyntacticClassifications('${fileName}', ${start}, ${length})`, () => this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length)) ); } public getSemanticClassifications(fileName: string, start: number, length: number): string { return this.forwardJSONCall( `getSemanticClassifications('${fileName}', ${start}, ${length})`, () => this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length)) ); } public getEncodedSyntacticClassifications(fileName: string, start: number, length: number): string { return this.forwardJSONCall( `getEncodedSyntacticClassifications('${fileName}', ${start}, ${length})`, // directly serialize the spans out to a string. This is much faster to decode // on the managed side versus a full JSON array. () => convertClassifications(this.languageService.getEncodedSyntacticClassifications(fileName, createTextSpan(start, length))) ); } public getEncodedSemanticClassifications(fileName: string, start: number, length: number): string { return this.forwardJSONCall( `getEncodedSemanticClassifications('${fileName}', ${start}, ${length})`, // directly serialize the spans out to a string. This is much faster to decode // on the managed side versus a full JSON array. () => convertClassifications(this.languageService.getEncodedSemanticClassifications(fileName, createTextSpan(start, length))) ); } public getSyntacticDiagnostics(fileName: string): string { return this.forwardJSONCall( `getSyntacticDiagnostics('${fileName}')`, () => { const diagnostics = this.languageService.getSyntacticDiagnostics(fileName); return this.realizeDiagnostics(diagnostics); }); } public getSemanticDiagnostics(fileName: string): string { return this.forwardJSONCall( `getSemanticDiagnostics('${fileName}')`, () => { const diagnostics = this.languageService.getSemanticDiagnostics(fileName); return this.realizeDiagnostics(diagnostics); }); } public getCompilerOptionsDiagnostics(): string { return this.forwardJSONCall( "getCompilerOptionsDiagnostics()", () => { const diagnostics = this.languageService.getCompilerOptionsDiagnostics(); return this.realizeDiagnostics(diagnostics); }); } /// QUICKINFO /** * Computes a string representation of the type at the requested position * in the active file. */ public getQuickInfoAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getQuickInfoAtPosition('${fileName}', ${position})`, () => this.languageService.getQuickInfoAtPosition(fileName, position) ); } /// NAMEORDOTTEDNAMESPAN /** * Computes span information of the name or dotted name at the requested position * in the active file. */ public getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string { return this.forwardJSONCall( `getNameOrDottedNameSpan('${fileName}', ${startPos}, ${endPos})`, () => this.languageService.getNameOrDottedNameSpan(fileName, startPos, endPos) ); } /** * STATEMENTSPAN * Computes span information of statement at the requested position in the active file. */ public getBreakpointStatementAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getBreakpointStatementAtPosition('${fileName}', ${position})`, () => this.languageService.getBreakpointStatementAtPosition(fileName, position) ); } /// SIGNATUREHELP public getSignatureHelpItems(fileName: string, position: number): string { return this.forwardJSONCall( `getSignatureHelpItems('${fileName}', ${position})`, () => this.languageService.getSignatureHelpItems(fileName, position) ); } /// GOTO DEFINITION /** * Computes the definition location and file for the symbol * at the requested position. */ public getDefinitionAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getDefinitionAtPosition('${fileName}', ${position})`, () => this.languageService.getDefinitionAtPosition(fileName, position) ); } /// GOTO Type /** * Computes the definition location of the type of the symbol * at the requested position. */ public getTypeDefinitionAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getTypeDefinitionAtPosition('${fileName}', ${position})`, () => this.languageService.getTypeDefinitionAtPosition(fileName, position) ); } /// GOTO Implementation /** * Computes the implementation location of the symbol * at the requested position. */ public getImplementationAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getImplementationAtPosition('${fileName}', ${position})`, () => this.languageService.getImplementationAtPosition(fileName, position) ); } public getRenameInfo(fileName: string, position: number): string { return this.forwardJSONCall( `getRenameInfo('${fileName}', ${position})`, () => this.languageService.getRenameInfo(fileName, position) ); } public findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): string { return this.forwardJSONCall( `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`, () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments) ); } /// GET BRACE MATCHING public getBraceMatchingAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getBraceMatchingAtPosition('${fileName}', ${position})`, () => this.languageService.getBraceMatchingAtPosition(fileName, position) ); } public isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): string { return this.forwardJSONCall( `isValidBraceCompletionAtPosition('${fileName}', ${position}, ${openingBrace})`, () => this.languageService.isValidBraceCompletionAtPosition(fileName, position, openingBrace) ); } /// GET SMART INDENT public getIndentationAtPosition(fileName: string, position: number, options: string /*Services.EditorOptions*/): string { return this.forwardJSONCall( `getIndentationAtPosition('${fileName}', ${position})`, () => { const localOptions: EditorOptions = JSON.parse(options); return this.languageService.getIndentationAtPosition(fileName, position, localOptions); }); } /// GET REFERENCES public getReferencesAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getReferencesAtPosition('${fileName}', ${position})`, () => this.languageService.getReferencesAtPosition(fileName, position) ); } public findReferences(fileName: string, position: number): string { return this.forwardJSONCall( `findReferences('${fileName}', ${position})`, () => this.languageService.findReferences(fileName, position) ); } public getOccurrencesAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getOccurrencesAtPosition('${fileName}', ${position})`, () => this.languageService.getOccurrencesAtPosition(fileName, position) ); } public getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string { return this.forwardJSONCall( `getDocumentHighlights('${fileName}', ${position})`, () => { const results = this.languageService.getDocumentHighlights(fileName, position, JSON.parse(filesToSearch)); // workaround for VS document highlighting issue - keep only items from the initial file const normalizedName = normalizeSlashes(fileName).toLowerCase(); return filter(results, r => normalizeSlashes(r.fileName).toLowerCase() === normalizedName); }); } /// COMPLETION LISTS /** * Get a string based representation of the completions * to provide at the given source position and providing a member completion * list if requested. */ public getCompletionsAtPosition(fileName: string, position: number) { return this.forwardJSONCall( `getCompletionsAtPosition('${fileName}', ${position})`, () => this.languageService.getCompletionsAtPosition(fileName, position) ); } /** Get a string based representation of a completion list entry details */ public getCompletionEntryDetails(fileName: string, position: number, entryName: string) { return this.forwardJSONCall( `getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`, () => this.languageService.getCompletionEntryDetails(fileName, position, entryName) ); } public getFormattingEditsForRange(fileName: string, start: number, end: number, options: string/*Services.FormatCodeOptions*/): string { return this.forwardJSONCall( `getFormattingEditsForRange('${fileName}', ${start}, ${end})`, () => { const localOptions: ts.FormatCodeOptions = JSON.parse(options); return this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); }); } public getFormattingEditsForDocument(fileName: string, options: string/*Services.FormatCodeOptions*/): string { return this.forwardJSONCall( `getFormattingEditsForDocument('${fileName}')`, () => { const localOptions: ts.FormatCodeOptions = JSON.parse(options); return this.languageService.getFormattingEditsForDocument(fileName, localOptions); }); } public getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: string/*Services.FormatCodeOptions*/): string { return this.forwardJSONCall( `getFormattingEditsAfterKeystroke('${fileName}', ${position}, '${key}')`, () => { const localOptions: ts.FormatCodeOptions = JSON.parse(options); return this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); } public getDocCommentTemplateAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( `getDocCommentTemplateAtPosition('${fileName}', ${position})`, () => this.languageService.getDocCommentTemplateAtPosition(fileName, position) ); } /// NAVIGATE TO /** Return a list of symbols that are interesting to navigate to */ public getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): string { return this.forwardJSONCall( `getNavigateToItems('${searchValue}', ${maxResultCount}, ${fileName})`, () => this.languageService.getNavigateToItems(searchValue, maxResultCount, fileName) ); } public getNavigationBarItems(fileName: string): string { return this.forwardJSONCall( `getNavigationBarItems('${fileName}')`, () => this.languageService.getNavigationBarItems(fileName) ); } public getNavigationTree(fileName: string): string { return this.forwardJSONCall( `getNavigationTree('${fileName}')`, () => this.languageService.getNavigationTree(fileName) ); } public getOutliningSpans(fileName: string): string { return this.forwardJSONCall( `getOutliningSpans('${fileName}')`, () => this.languageService.getOutliningSpans(fileName) ); } public getTodoComments(fileName: string, descriptors: string): string { return this.forwardJSONCall( `getTodoComments('${fileName}')`, () => this.languageService.getTodoComments(fileName, JSON.parse(descriptors)) ); } /// Emit public getEmitOutput(fileName: string): string { return this.forwardJSONCall( `getEmitOutput('${fileName}')`, () => this.languageService.getEmitOutput(fileName) ); } public getEmitOutputObject(fileName: string): any { return forwardCall( this.logger, `getEmitOutput('${fileName}')`, /*returnJson*/ false, () => this.languageService.getEmitOutput(fileName), this.logPerformance); } } function convertClassifications(classifications: Classifications): { spans: string, endOfLineState: EndOfLineState } { return { spans: classifications.spans.join(","), endOfLineState: classifications.endOfLineState }; } class ClassifierShimObject extends ShimBase implements ClassifierShim { public classifier: Classifier; private logPerformance = false; constructor(factory: ShimFactory, private logger: Logger) { super(factory); this.classifier = createClassifier(); } public getEncodedLexicalClassifications(text: string, lexState: EndOfLineState, syntacticClassifierAbsent?: boolean): string { return forwardJSONCall(this.logger, "getEncodedLexicalClassifications", () => convertClassifications(this.classifier.getEncodedLexicalClassifications(text, lexState, syntacticClassifierAbsent)), this.logPerformance); } /// COLORIZATION public getClassificationsForLine(text: string, lexState: EndOfLineState, classifyKeywordsInGenerics?: boolean): string { const classification = this.classifier.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics); let result = ""; for (const item of classification.entries) { result += item.length + "\n"; result += item.classification + "\n"; } result += classification.finalLexState; return result; } } class CoreServicesShimObject extends ShimBase implements CoreServicesShim { private logPerformance = false; constructor(factory: ShimFactory, public logger: Logger, private host: CoreServicesShimHostAdapter) { super(factory); } private forwardJSONCall(actionDescription: string, action: () => any): any { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); } public resolveModuleName(fileName: string, moduleName: string, compilerOptionsJson: string): string { return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => { const compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson); const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host); return { resolvedFileName: result.resolvedModule ? result.resolvedModule.resolvedFileName : undefined, failedLookupLocations: result.failedLookupLocations }; }); } public resolveTypeReferenceDirective(fileName: string, typeReferenceDirective: string, compilerOptionsJson: string): string { return this.forwardJSONCall(`resolveTypeReferenceDirective(${fileName})`, () => { const compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson); const result = resolveTypeReferenceDirective(typeReferenceDirective, normalizeSlashes(fileName), compilerOptions, this.host); return { resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined, primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true, failedLookupLocations: result.failedLookupLocations }; }); } public getPreProcessedFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string { return this.forwardJSONCall( `getPreProcessedFileInfo('${fileName}')`, () => { // for now treat files as JavaScript const result = preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true); return { referencedFiles: this.convertFileReferences(result.referencedFiles), importedFiles: this.convertFileReferences(result.importedFiles), ambientExternalModules: result.ambientExternalModules, isLibFile: result.isLibFile, typeReferenceDirectives: this.convertFileReferences(result.typeReferenceDirectives) }; }); } public getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string { return this.forwardJSONCall( `getAutomaticTypeDirectiveNames('${compilerOptionsJson}')`, () => { const compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson); return getAutomaticTypeDirectiveNames(compilerOptions, this.host); } ); } private convertFileReferences(refs: FileReference[]): IFileReference[] { if (!refs) { return undefined; } const result: IFileReference[] = []; for (const ref of refs) { result.push({ path: normalizeSlashes(ref.fileName), position: ref.pos, length: ref.end - ref.pos }); } return result; } public getTSConfigFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string { return this.forwardJSONCall( `getTSConfigFileInfo('${fileName}')`, () => { const text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); const result = parseConfigFileTextToJson(fileName, text); if (result.error) { return { options: {}, typingOptions: {}, files: [], raw: {}, errors: [realizeDiagnostic(result.error, "\r\n")] }; } const normalizedFileName = normalizeSlashes(fileName); const configFile = parseJsonConfigFileContent(result.config, this.host, getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { options: configFile.options, typingOptions: configFile.typingOptions, files: configFile.fileNames, raw: configFile.raw, errors: realizeDiagnostics(configFile.errors, "\r\n") }; }); } public getDefaultCompilationSettings(): string { return this.forwardJSONCall( "getDefaultCompilationSettings()", () => getDefaultCompilerOptions() ); } public discoverTypings(discoverTypingsJson: string): string { const getCanonicalFileName = createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false); return this.forwardJSONCall("discoverTypings()", () => { const info = <DiscoverTypingsInfo>JSON.parse(discoverTypingsJson); return ts.JsTyping.discoverTypings( this.host, info.fileNames, toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName), toPath(info.safeListPath, info.safeListPath, getCanonicalFileName), info.packageNameToTypingLocation, info.typingOptions, info.unresolvedImports); }); } } export class TypeScriptServicesFactory implements ShimFactory { private _shims: Shim[] = []; private documentRegistry: DocumentRegistry; /* * Returns script API version. */ public getServicesVersion(): string { return servicesVersion; } public createLanguageServiceShim(host: LanguageServiceShimHost): LanguageServiceShim { try { if (this.documentRegistry === undefined) { this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } const hostAdapter = new LanguageServiceShimHostAdapter(host); const languageService = createLanguageService(hostAdapter, this.documentRegistry); return new LanguageServiceShimObject(this, host, languageService); } catch (err) { logInternalError(host, err); throw err; } } public createClassifierShim(logger: Logger): ClassifierShim { try { return new ClassifierShimObject(this, logger); } catch (err) { logInternalError(logger, err); throw err; } } public createCoreServicesShim(host: CoreServicesShimHost): CoreServicesShim { try { const adapter = new CoreServicesShimHostAdapter(host); return new CoreServicesShimObject(this, <Logger>host, adapter); } catch (err) { logInternalError(<Logger>host, err); throw err; } } public close(): void { // Forget all the registered shims this._shims = []; this.documentRegistry = undefined; } public registerShim(shim: Shim): void { this._shims.push(shim); } public unregisterShim(shim: Shim): void { for (let i = 0, n = this._shims.length; i < n; i++) { if (this._shims[i] === shim) { delete this._shims[i]; return; } } throw new Error("Invalid operation"); } } // Here we expose the TypeScript services as an external module // so that it may be consumed easily like a node module. declare var module: any; if (typeof module !== "undefined" && module.exports) { module.exports = ts; } } /* tslint:enable:no-in-operator */ /* tslint:enable:no-null */ /// TODO: this is used by VS, clean this up on both sides of the interface /* @internal */ namespace TypeScript.Services { export const TypeScriptServicesFactory = ts.TypeScriptServicesFactory; } /* tslint:disable:no-unused-variable */ // 'toolsVersion' gets consumed by the managed side, so it's not unused. // TODO: it should be moved into a namespace though. /* @internal */ const toolsVersion = "2.1"; /* tslint:enable:no-unused-variable */
{ "content_hash": "8e46bf14e212a4880390fd20d160a170", "timestamp": "", "source": "github", "line_count": 1271, "max_line_length": 212, "avg_line_length": 43.597954366640444, "alnum_prop": 0.5919730027249923, "repo_name": "jeremyepling/TypeScript", "id": "a3b99f81158c9c83d1046fc72f7a43c3fa5deecf", "size": "55413", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/services/shims.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "945" }, { "name": "HTML", "bytes": "4843" }, { "name": "JavaScript", "bytes": "85" }, { "name": "PowerShell", "bytes": "2855" }, { "name": "TypeScript", "bytes": "23854064" } ], "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.8/phpunit.xsd" backupGlobals="false" colors="true" bootstrap="../../vendor/autoload.php" > <php> <ini name="error_reporting" value="-1" /> </php> <testsuites> <testsuite name="Doctrine DBAL Test Suite"> <directory>../Doctrine/Tests/DBAL</directory> </testsuite> </testsuites> <groups> <exclude> <group>performance</group> <group>locking_functional</group> </exclude> </groups> </phpunit>
{ "content_hash": "6787120c3dee73c6200da6c657d4c6b7", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 81, "avg_line_length": 28.541666666666668, "alnum_prop": 0.5795620437956205, "repo_name": "AlexDpy/dbal", "id": "6c22315150c83c04d26ba33e19e92c9d526db923", "size": "685", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "tests/travis/sqlite.travis.xml", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "2299486" }, { "name": "Shell", "bytes": "757" } ], "symlink_target": "" }
<?php $this->breadcrumbs=array( 'Banner Categories'=>array('manage'), 'Create', ); ?> <div class="form"> <?php echo $this->renderPartial('_form', array('model'=>$model)); ?> </div>
{ "content_hash": "48c0d6af67d97efcee872523e9c7a5d4", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 69, "avg_line_length": 15.916666666666666, "alnum_prop": 0.5968586387434555, "repo_name": "oMMuCo/HPTT-FT-UGM-Official-Website", "id": "ce90332ae10d399892d16923df74278e9d568396", "size": "514", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "protected/modules/banner/views/o/category/admin_add.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "215" }, { "name": "Batchfile", "bytes": "380" }, { "name": "CSS", "bytes": "132697" }, { "name": "JavaScript", "bytes": "467209" }, { "name": "PHP", "bytes": "2531774" }, { "name": "SQLPL", "bytes": "245758" } ], "symlink_target": "" }
set -e # This script is the entrypoint to the libbeat Docker container. This will # verify that the Elasticsearch and Redis environment variables are set # and that Elasticsearch is running before executing the command provided # to the docker container. # Read parameters from the environment and validate them. checkHost() { if [ -z "$$1" ]; then echo >&2 'Error: missing required $1 environment variable' echo >&2 ' Did you forget to -e $1=... ?' exit 1 fi } readParams() { checkHost "ES_HOST" checkHost "REDIS_HOST" checkHost "LS_HOST" # Use default ports if not specified. : ${ES_PORT:=9200} : ${REDIS_PORT:=6379} : ${LS_TCP_PORT:=12345} } es_url() { local auth auth="" if [ -n "$ES_USER" ]; then auth="$ES_USER" if [ -n "$ES_PASS" ]; then auth="$auth:$ES_PASS" fi auth="$auth@" fi if [ $SHIELD == "true" ]; then code=$(curl --write-out "%{http_code}\n" --silent --output /dev/null "http://${ES_HOST}:${ES_PORT}/") if [ $code != 401 ]; then echo "Shield does not seem to be running" exit 1 fi fi echo "http://${auth}${ES_HOST}:${ES_PORT}" } # Wait for elasticsearch to start. It requires that the status be either # green or yellow. waitForElasticsearch() { echo -n "Waiting on elasticsearch($(es_url)) to start." for ((i=1;i<=60;i++)) do health=$(curl --silent "$(es_url)/_cat/health" | awk '{print $4}') if [[ "$health" == "green" ]] || [[ "$health" == "yellow" ]] then echo echo "Elasticsearch is ready!" return 0 fi ((i++)) echo -n '.' sleep 1 done echo echo >&2 'Elasticsearch is not running or is not healthy.' echo >&2 "Address: $(es_url)" echo >&2 "$health" exit 1 } waitForLogstash() { echo -n "Waiting for logstash(${LS_HOST}:${LS_TCP_PORT}) to start." for ((i=1; i<=90; i++)) do if nc -vz ${LS_HOST} ${LS_TCP_PORT} 2>/dev/null; then echo echo "Logstash is ready!" return 0 fi ((i++)) echo -n '.' sleep 1 done echo echo >&2 'Logstash is not available' echo >&2 "Address: ${LS_HOST}:${LS_TCP_PORT} and ${LS_HOST}:${LS_TLS_PORT}" } waitForKafka() { echo -n "Waiting for kafka(${KAFKA_HOST}:${KAFKA_PORT}) to start." for ((i=1; i<=90; i++)) do if nc -vz ${KAFKA_HOST} ${KAFKA_PORT} 2>/dev/null; then echo echo "Kafka is ready!" return 0 fi ((i++)) echo -n '.' sleep 1 done echo echo >&2 'Kafka is not available' echo >&2 "Address: ${KAFKA_HOST}:${KAFKA_PORT}" } # Main readParams waitForElasticsearch waitForLogstash waitForKafka exec "$@"
{ "content_hash": "e33c68fd452179f641411a46372e389f", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 109, "avg_line_length": 23.341666666666665, "alnum_prop": 0.5512317029632274, "repo_name": "ninjasftw/libertyproxybeat", "id": "ed51711e86a40acc90da245ae9839d85ff41955f", "size": "2813", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/github.com/elastic/beats/libbeat/scripts/docker-entrypoint.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "10091" }, { "name": "Makefile", "bytes": "1640" } ], "symlink_target": "" }
A simple threading library for JavaScript. Provides a simple API enabling concurrent execution of tasks in a separate threads, and allowing easy management of these threads. Please see the main `README.md` file for example of basic usage. ### Overview #### thread (namespace) The thread namespace holds the other objects, as well as several utility methods used throughout the library. #### thread.message (namespace) The message namespace holds methods to encode and send messages to Threads, or receive and decode messages from Threads. #### thread.Task (class) The Task class is an externally controllable Promise that also holds the information to be sent to the Thread (function, arguments, scope, etc). #### thread.Thread (class) The Thread class is a wrapper around a Web Worker, which provides methods to control its behavior, thereby emulating a standard (e.g. Java) Thread object. #### thread.Pool (class) The thread Pool class manages a collection of Threads. Provides methods to concurrently run tasks without having to create the necessary threads or distribute the tasks. ### Extras Thread.js is copyright (c) 2015 Daniel Peykov (<[email protected]>). Feel free to send any questions, comments, suggestions, or angry letters my way, but do remember that this project was simply an attempt at practicing my JavaScript coding with a non-trivial problem. Thread.js is available free under the MIT License. See the `LICENSE.md` file for more details.
{ "content_hash": "832636907ba87039d99c53dc5469032e", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 199, "avg_line_length": 42.285714285714285, "alnum_prop": 0.7797297297297298, "repo_name": "dpeykov/thread.js", "id": "89689fe1a3aeeb2726085030d82fd54b6f7dff0b", "size": "1494", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "281278" } ], "symlink_target": "" }
require File.dirname(__FILE__) + '/../test_helper' context "Existing Theme Resources" do fixtures :sites def setup prepare_theme_fixtures end specify "should count correct assets" do assert_equal 3, sites(:first).resources.size assert_equal 0, sites(:hostess).resources.size end specify "should carry theme reference" do assert_equal sites(:first).theme.path, sites(:first).resources.theme.path end specify "should add resource" do f = sites(:hostess).resources.write 'foo.css' assert_equal (sites(:hostess).attachment_path + 'stylesheets/foo.css'), f assert !f.file? end specify "should add and create resource" do f = sites(:hostess).resources.write 'foo.css', 'foo' assert_equal (sites(:hostess).attachment_path + 'stylesheets/foo.css'), f assert_equal 'foo', f.read assert f.file? end end context "Resource" do def setup @resources = Resources.new @resources.stubs(:theme).returns(stub(:path => '')) end specify "should return correct content type for Pathname" do exts = %w(.js .css .png .jpg .jpeg .gif .swf) types = %w(text/javascript text/css image/png image/jpeg image/jpeg image/gif application/x-shockwave-flash) exts.each_with_index do |ext, i| assert_equal types[i], @resources.content_type(Pathname.new("foo#{ext}")) end end specify "should return correct full path for filename" do paths = Hash.new { 'images' } paths['.js'] = 'javascripts' paths['.css'] = 'stylesheets' %w(.js .css .png .jpg .jpeg .gif .swf).each do |ext| assert_equal "#{paths[ext]}/foo#{ext}", @resources["foo#{ext}"] end end end
{ "content_hash": "92628d05ab80f041b492ee7b5027c4db", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 112, "avg_line_length": 30.2, "alnum_prop": 0.6688741721854304, "repo_name": "port49/dialogues.port49.com", "id": "173271ae5d1a5899c6c81f0296446cea9a4e8f8b", "size": "1661", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "test/unit/resource_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "37972" }, { "name": "Ruby", "bytes": "435566" } ], "symlink_target": "" }
<?php /** * @package A simple ORM that performs basic CRUD operations * @author Surajudeen AKANDE <[email protected]> * @license MIT <https://opensource.org/licenses/MIT> * @link http://www.github.com/andela-sakande * */ namespace Sirolad\Entities; use Sirolad\Potato; /** * Extends the main class as an entity * */ class Bicycle extends Potato { }
{ "content_hash": "60fdc7bcade011efe6807d98b724b1d4", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 60, "avg_line_length": 18.6, "alnum_prop": 0.7096774193548387, "repo_name": "andela-sakande/potatoORM", "id": "23b196c65138b42e66742f2e91f97d792f44413e", "size": "372", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Entities/Bicycle.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "23620" } ], "symlink_target": "" }
This directory provides examples for the SWI-Prolog built-in predicates as well as the library. Examples are [PlDoc](https://www.swi-prolog.org/pldoc/doc_for?object=section(%27packages/pldoc.html%27)) ([markdown](https://www.markdownguide.org/basic-syntax/)) files with the following properties: - The file extension is `.md`. - The file name can be the predicate name, optionally followed by the arity, e.g., `append3.md` or `halt.md`. Without an arity it associates to a predicate with the same name, regardless of the arity. An example identified this way is the _primary_ example, is displayed as first and always visible. - They optionally have a title. The title is identified using a level-1 markdown title, as below. It must be first. ``` # Using append/3 for splitting lists ``` - Examples can have subsections using level-2 or level-3 section headers. - Code blocks are supposed to contain either valid program snippets or queries, surrounded by markdown code markup for [fenced code blocks](https://www.markdownguide.org/extended-syntax/#fenced-code-blocks), i.e. three backticks or three tildes. Queries are identified through the presence of `?-` e.g., ``?- member(X, [1,2,3]).``. If the next term looks like an answer is is ignored for indexing. Code blocks are cross-referenced and used to bind the example to predicates. - Markdown text is analysed for _predicate indicators_, linking the example to the referenced predicates. Examples are ordered according to the list below. Further versions may use more advanced ordering. 1. file name 2. reference in the title 3. appearing as query 4. called in some code block 5. reference in the running text. ## Style guide - Keep examples short - Do not try to document the predicate as the documentation is already present. ## Future This is a first prototype. Some ideas: - Get examples from a [Discourse](https://swi-prolog.discourse.group/) _Category_ rather than git? - Embed SWISH, similar to [LPN with SWISH](https://lpn.swi-prolog.org) - Show/highlight the fragment of an example that refers to the predicate. - Use HTML coloring of the code fragments with linking.
{ "content_hash": "e262048bbc9a01588a5e76efa512d67c", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 128, "avg_line_length": 38.32203389830509, "alnum_prop": 0.7266696152145069, "repo_name": "TeamSPoon/logicmoo_workspace", "id": "8e01a320c6a3140f16c41ff1b0c0fa05ffd1402e", "size": "2284", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packs_web/plweb/examples/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "342" }, { "name": "C", "bytes": "1" }, { "name": "C++", "bytes": "1" }, { "name": "CSS", "bytes": "126627" }, { "name": "HTML", "bytes": "839172" }, { "name": "Java", "bytes": "11116" }, { "name": "JavaScript", "bytes": "238700" }, { "name": "PHP", "bytes": "42253" }, { "name": "Perl 6", "bytes": "23" }, { "name": "Prolog", "bytes": "440882" }, { "name": "PureBasic", "bytes": "1334" }, { "name": "Rich Text Format", "bytes": "3436542" }, { "name": "Roff", "bytes": "42" }, { "name": "Shell", "bytes": "61603" }, { "name": "TeX", "bytes": "99504" } ], "symlink_target": "" }
from __future__ import print_function import time import re import sys from google.appengine.ext import db def iterate(query, callback=lambda x: x, batch_size=1000, verbose=True): """Utility for iterating over a query, applying the callback to each row.""" start = time.time() count = 0 results = query.fetch(batch_size) while results: rstart = time.time() for row in results: output = callback(row) if output: print(output) count += 1 if verbose: print('%s rows processed in %.1fs' % (count, time.time() - rstart)) print('total time: %.1fs' % (time.time() - start)) results = query.with_cursor(query.cursor()).fetch(batch_size) callback() print('total rows: %s, total time: %.1fs' % (count, time.time() - start)) def dangling_pic(pic): """Filter for photos with no referencing person.""" ppl = pic.person_set.fetch(100) if not ppl: return pic.key().id() ids = [] def dangling_pic_list(pic): """Track photos with no referencing person.""" if pic and not pic.person_set.count(): ids.append(pic.key().id())
{ "content_hash": "bc20b0d1787d6d065a8b60b3bc244218", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 80, "avg_line_length": 31.864864864864863, "alnum_prop": 0.6030534351145038, "repo_name": "gimite/personfinder", "id": "8e8655181f8d21549fe42fb78f00ae2504851933", "size": "1777", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/iterate.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "21011" }, { "name": "Dockerfile", "bytes": "1428" }, { "name": "HTML", "bytes": "4527" }, { "name": "JavaScript", "bytes": "90402" }, { "name": "Python", "bytes": "1768355" }, { "name": "Shell", "bytes": "30308" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <title>Pages</title> <meta property="og:title" content="Pages" /> <meta name="twitter:title" content="Pages" /> <meta name="author" content="davor badrov"/> <link href='https://davorbadrov.github.io/img/favicon.ico' rel='icon' type='image/x-icon'/> <meta property="og:image" content="https://davorbadrov.github.io/img/avatar-icon.png" /> <meta name="twitter:image" content="https://davorbadrov.github.io/img/avatar-icon.png" /> <meta name="twitter:card" content="summary" /> <meta property="og:url" content="https://davorbadrov.github.io/page/" /> <meta property="og:type" content="website" /> <meta property="og:site_name" content="Davor Badrov" /> <meta name="generator" content="Hugo 0.23" /> <link rel="canonical" href="https://davorbadrov.github.io/page/" /> <link rel="alternate" href="https://davorbadrov.github.io/index.xml" type="application/rss+xml" title="Davor Badrov"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css" integrity="sha384-wITovz90syo1dJWVh32uuETPVEtGigN07tkttEqPv+uR2SE/mbQcG7ATL28aI9H0" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="https://davorbadrov.github.io/css/main.css" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" /> <link rel="stylesheet" href="https://davorbadrov.github.io/css/pygment_highlights.css" /> <link rel="stylesheet" href="https://davorbadrov.github.io/css/highlight.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/photoswipe.min.css" integrity="sha256-sCl5PUOGMLfFYctzDW3MtRib0ctyUvI9Qsmq2wXOeBY=" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/default-skin/default-skin.min.css" integrity="sha256-BFeI1V+Vh1Rk37wswuOYn5lsTcaU96hGaI7OUVCLjPc=" crossorigin="anonymous" /> <div class="pswp" tabindex="-1" role="dialog" aria-hidden="true"> <div class="pswp__bg"></div> <div class="pswp__scroll-wrap"> <div class="pswp__container"> <div class="pswp__item"></div> <div class="pswp__item"></div> <div class="pswp__item"></div> </div> <div class="pswp__ui pswp__ui--hidden"> <div class="pswp__top-bar"> <div class="pswp__counter"></div> <button class="pswp__button pswp__button--close" title="Close (Esc)"></button> <button class="pswp__button pswp__button--share" title="Share"></button> <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button> <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button> <div class="pswp__preloader"> <div class="pswp__preloader__icn"> <div class="pswp__preloader__cut"> <div class="pswp__preloader__donut"></div> </div> </div> </div> </div> <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap"> <div class="pswp__share-tooltip"></div> </div> <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"> </button> <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"> </button> <div class="pswp__caption"> <div class="pswp__caption__center"></div> </div> </div> </div> </div> </head> <body> <nav class="navbar navbar-default navbar-fixed-top navbar-custom"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="https://davorbadrov.github.io/">Davor Badrov</a> </div> <div class="collapse navbar-collapse" id="main-navbar"> <ul class="nav navbar-nav navbar-right"> <li> <a title="Home" href="/">Home</a> </li> <li> <a title="Blog" href="/blog/">Blog</a> </li> <li> <a title="Snippets" href="/snippets/">Snippets</a> </li> <li> <a title="About" href="/about/">About</a> </li> </ul> </div> <div class="avatar-container"> <div class="avatar-img-border"> <a title="Davor Badrov" href="https://davorbadrov.github.io/"> <img class="avatar-img" src="https://davorbadrov.github.io/img/avatar-icon.png" alt="Davor Badrov" /> </a> </div> </div> </div> </nav> <header class="header-section "> <div class="intro-header no-img"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="page-heading"> <h1>Pages</h1> <hr class="small"> </div> </div> </div> </div> </div> </header> <div class="container" role="main"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="posts-list"> <article class="post-preview"> <a href="https://davorbadrov.github.io/about-me/"> <h2 class="post-title">About me</h2> </a> <p class="post-meta"> Posted on June 19, 2017 </p> <div class="post-entry"> I&rsquo;m a full stack engineer currently stationed in Zagreb, Croatia. My main stack is based on JavaScript, these days it&rsquo;s React and Node. I&rsquo;m part of a team working for Kanban (knb.io) where we are developing cool things for both startups and enterprises. I&rsquo;m always looking for freelancing opportunities and fun projects to work on. You can check my resume on LinkedIn. To list the skills &amp; technologies which I&rsquo;m familiar with: React, Node, Hapi. <a href="https://davorbadrov.github.io/about-me/" class="post-read-more">[Read More]</a> </div> </article> </div> </div> </div> </div> <footer> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <ul class="list-inline text-center footer-links"> <li> <a href="mailto:[email protected]" title="Email me"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-envelope fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a href="https://github.com/davorbadrov" title="GitHub"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-github fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a href="https://linkedin.com/in/davor-badrov-670b0312b" title="LinkedIn"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-linkedin fa-stack-1x fa-inverse"></i> </span> </a> </li> </ul> <p class="credits copyright text-muted"> davor badrov &nbsp;&bull;&nbsp; 2017 &nbsp;&bull;&nbsp; <a href="https://davorbadrov.github.io/">Davor Badrov</a> </p> <p class="credits theme-by text-muted"> <a href="http://gohugo.io">Hugo v0.23</a> powered &nbsp;&bull;&nbsp; Theme by <a href="http://deanattali.com/beautiful-jekyll/">Beautiful Jekyll</a> adapted to <a href="https://github.com/halogenica/beautifulhugo">Beautiful Hugo</a> </p> </div> </div> </div> </footer> <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.js" integrity="sha384-/y1Nn9+QQAipbNQWU65krzJralCnuOasHncUFXGkdwntGeSvQicrYkiUBwsgUqc1" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/contrib/auto-render.min.js" integrity="sha384-dq1/gEHSxPZQ7DdrM82ID4YVol9BYyU7GbWlIwnwyPzotpoc57wDw/guX8EaYGPx" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src="https://davorbadrov.github.io/js/main.js"></script> <script src="https://davorbadrov.github.io/js/highlight.min.js"></script> <script> hljs.initHighlightingOnLoad(); </script> <script> renderMathInElement(document.body); </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/photoswipe.min.js" integrity="sha256-UplRCs9v4KXVJvVY+p+RSo5Q4ilAUXh7kpjyIP5odyc=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.1/photoswipe-ui-default.min.js" integrity="sha256-PWHOlUzc96pMc8ThwRIXPn8yH4NOLu42RQ0b9SpnpFk=" crossorigin="anonymous"></script> <script src="https://davorbadrov.github.io/js/load-photoswipe.js"></script> </body> </html>
{ "content_hash": "afe71d2754aaed4276528597fab25edb", "timestamp": "", "source": "github", "line_count": 272, "max_line_length": 289, "avg_line_length": 39.42279411764706, "alnum_prop": 0.5965681245919985, "repo_name": "davorbadrov/davorbadrov.github.io", "id": "91639acbba1e1b21785846a1a2ff71a2a810a7e8", "size": "10723", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "page/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22504" }, { "name": "HTML", "bytes": "450497" }, { "name": "JavaScript", "bytes": "6729" } ], "symlink_target": "" }
package org.spongepowered.api.block.tile.data; /** * An enumeration of all possible {@link BannerPatternShape}s in vanilla minecraft. */ public final class BannerPatternShapes { public static final BannerPatternShape BASE = null; public static final BannerPatternShape SQUARE_BOTTOM_LEFT = null; public static final BannerPatternShape SQUARE_BOTTOM_RIGHT = null; public static final BannerPatternShape SQUARE_TOP_LEFT = null; public static final BannerPatternShape SQUARE_TOP_RIGHT = null; public static final BannerPatternShape STRIPE_BOTTOM = null; public static final BannerPatternShape STRIPE_TOP = null; public static final BannerPatternShape STRIPE_LEFT = null; public static final BannerPatternShape STRIPE_RIGHT = null; public static final BannerPatternShape STRIPE_CENTER = null; public static final BannerPatternShape STRIPE_MIDDLE = null; public static final BannerPatternShape STRIPE_DOWNRIGHT = null; public static final BannerPatternShape STRIPE_DOWNLEFT = null; public static final BannerPatternShape STRIPE_SMALL = null; public static final BannerPatternShape CROSS = null; public static final BannerPatternShape STRAIGHT_CROSS = null; public static final BannerPatternShape TRIANGLE_BOTTOM = null; public static final BannerPatternShape TRIANGLE_TOP = null; public static final BannerPatternShape TRIANGLES_BOTTOM = null; public static final BannerPatternShape TRIANGLES_TOP = null; public static final BannerPatternShape DIAGONAL_LEFT = null; public static final BannerPatternShape DIAGONAL_RIGHT = null; public static final BannerPatternShape DIAGONAL_LEFT_MIRROR = null; public static final BannerPatternShape DIAGONAL_RIGHT_MIRROR = null; public static final BannerPatternShape CIRCLE_MIDDLE = null; public static final BannerPatternShape RHOMBUS_MIDDLE = null; public static final BannerPatternShape HALF_VERTICAL = null; public static final BannerPatternShape HALF_HORIZONTAL = null; public static final BannerPatternShape HALF_VERTICAL_MIRROR = null; public static final BannerPatternShape HALF_HORIZONTAL_MIRROR = null; public static final BannerPatternShape BORDER = null; public static final BannerPatternShape CURLY_BORDER = null; public static final BannerPatternShape CREEPER = null; public static final BannerPatternShape GRADIENT = null; public static final BannerPatternShape GRADIENT_UP = null; public static final BannerPatternShape BRICKS = null; public static final BannerPatternShape SKULL = null; public static final BannerPatternShape FLOWER = null; public static final BannerPatternShape MOJANG = null; private BannerPatternShapes() { } /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ public static boolean isFlowerPot() { return false; } }
{ "content_hash": "6d14ae7ad33121617da280a4b6f35244", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 83, "avg_line_length": 47.967213114754095, "alnum_prop": 0.7648667122351333, "repo_name": "SpongeHistory/SpongeAPI-History", "id": "0d605722ddc5e0c211fb6fc710a5363bb5940a2d", "size": "4176", "binary": false, "copies": "1", "ref": "refs/heads/hotfix/instance-checks", "path": "src/main/java/org/spongepowered/api/block/tile/data/BannerPatternShapes.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2422487" }, { "name": "Shell", "bytes": "77" } ], "symlink_target": "" }
<?php /** * @see Zend_Feed_Writer_Renderer_RendererAbstract */ #require_once 'Zend/Feed/Writer/Renderer/RendererAbstract.php'; #require_once 'Zend/Feed/Writer/Renderer/Feed/Atom/Source.php'; /** @see Zend_Xml_Security */ #require_once 'Zend/Xml/Security.php'; /** * @category Zend * @package Zend_Feed_Writer * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Feed_Writer_Renderer_Entry_Atom extends Zend_Feed_Writer_Renderer_RendererAbstract implements Zend_Feed_Writer_Renderer_RendererInterface { /** * Constructor * * @param Zend_Feed_Writer_Entry $container * @return void */ public function __construct (Zend_Feed_Writer_Entry $container) { parent::__construct($container); } /** * Render atom entry * * @return Zend_Feed_Writer_Renderer_Entry_Atom */ public function render() { $this->_dom = new DOMDocument('1.0', $this->_container->getEncoding()); $this->_dom->formatOutput = true; $entry = $this->_dom->createElementNS(Zend_Feed_Writer::NAMESPACE_ATOM_10, 'entry'); $this->_dom->appendChild($entry); $this->_setSource($this->_dom, $entry); $this->_setTitle($this->_dom, $entry); $this->_setDescription($this->_dom, $entry); $this->_setDateCreated($this->_dom, $entry); $this->_setDateModified($this->_dom, $entry); $this->_setLink($this->_dom, $entry); $this->_setId($this->_dom, $entry); $this->_setAuthors($this->_dom, $entry); $this->_setEnclosure($this->_dom, $entry); $this->_setContent($this->_dom, $entry); $this->_setCategories($this->_dom, $entry); foreach ($this->_extensions as $ext) { $ext->setType($this->getType()); $ext->setRootElement($this->getRootElement()); $ext->setDomDocument($this->getDomDocument(), $entry); $ext->render(); } return $this; } /** * Set entry title * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setTitle(DOMDocument $dom, DOMElement $root) { if(!$this->getDataContainer()->getTitle()) { #require_once 'Zend/Feed/Exception.php'; $message = 'Atom 1.0 entry elements MUST contain exactly one' . ' atom:title element but a title has not been set'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; } else { $this->_exceptions[] = $exception; return; } } $title = $dom->createElement('title'); $root->appendChild($title); $title->setAttribute('type', 'html'); $cdata = $dom->createCDATASection($this->getDataContainer()->getTitle()); $title->appendChild($cdata); } /** * Set entry description * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setDescription(DOMDocument $dom, DOMElement $root) { if(!$this->getDataContainer()->getDescription()) { return; // unless src content or base64 } $subtitle = $dom->createElement('summary'); $root->appendChild($subtitle); $subtitle->setAttribute('type', 'html'); $cdata = $dom->createCDATASection( $this->getDataContainer()->getDescription() ); $subtitle->appendChild($cdata); } /** * Set date entry was modified * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setDateModified(DOMDocument $dom, DOMElement $root) { if(!$this->getDataContainer()->getDateModified()) { #require_once 'Zend/Feed/Exception.php'; $message = 'Atom 1.0 entry elements MUST contain exactly one' . ' atom:updated element but a modification date has not been set'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; } else { $this->_exceptions[] = $exception; return; } } $updated = $dom->createElement('updated'); $root->appendChild($updated); $text = $dom->createTextNode( $this->getDataContainer()->getDateModified()->get(Zend_Date::ISO_8601) ); $updated->appendChild($text); } /** * Set date entry was created * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setDateCreated(DOMDocument $dom, DOMElement $root) { if (!$this->getDataContainer()->getDateCreated()) { return; } $el = $dom->createElement('published'); $root->appendChild($el); $text = $dom->createTextNode( $this->getDataContainer()->getDateCreated()->get(Zend_Date::ISO_8601) ); $el->appendChild($text); } /** * Set entry authors * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setAuthors(DOMDocument $dom, DOMElement $root) { $authors = $this->_container->getAuthors(); if ((!$authors || empty($authors))) { /** * This will actually trigger an Exception at the feed level if * a feed level author is not set. */ return; } foreach ($authors as $data) { $author = $this->_dom->createElement('author'); $name = $this->_dom->createElement('name'); $author->appendChild($name); $root->appendChild($author); $text = $dom->createTextNode($data['name']); $name->appendChild($text); if (array_key_exists('email', $data)) { $email = $this->_dom->createElement('email'); $author->appendChild($email); $text = $dom->createTextNode($data['email']); $email->appendChild($text); } if (array_key_exists('uri', $data)) { $uri = $this->_dom->createElement('uri'); $author->appendChild($uri); $text = $dom->createTextNode($data['uri']); $uri->appendChild($text); } } } /** * Set entry enclosure * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setEnclosure(DOMDocument $dom, DOMElement $root) { $data = $this->_container->getEnclosure(); if ((!$data || empty($data))) { return; } $enclosure = $this->_dom->createElement('link'); $enclosure->setAttribute('rel', 'enclosure'); if (isset($data['type'])) { $enclosure->setAttribute('type', $data['type']); } if (isset($data['length'])) { $enclosure->setAttribute('length', $data['length']); } $enclosure->setAttribute('href', $data['uri']); $root->appendChild($enclosure); } protected function _setLink(DOMDocument $dom, DOMElement $root) { if(!$this->getDataContainer()->getLink()) { return; } $link = $dom->createElement('link'); $root->appendChild($link); $link->setAttribute('rel', 'alternate'); $link->setAttribute('type', 'text/html'); $link->setAttribute('href', $this->getDataContainer()->getLink()); } /** * Set entry identifier * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setId(DOMDocument $dom, DOMElement $root) { if(!$this->getDataContainer()->getId() && !$this->getDataContainer()->getLink()) { #require_once 'Zend/Feed/Exception.php'; $message = 'Atom 1.0 entry elements MUST contain exactly one ' . 'atom:id element, or as an alternative, we can use the same ' . 'value as atom:link however neither a suitable link nor an ' . 'id have been set'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; } else { $this->_exceptions[] = $exception; return; } } if (!$this->getDataContainer()->getId()) { $this->getDataContainer()->setId( $this->getDataContainer()->getLink()); } if (!Zend_Uri::check($this->getDataContainer()->getId()) && !preg_match("#^urn:[a-zA-Z0-9][a-zA-Z0-9\-]{1,31}:([a-zA-Z0-9\(\)\+\,\.\:\=\@\;\$\_\!\*\-]|%[0-9a-fA-F]{2})*#", $this->getDataContainer()->getId() ) && !$this->_validateTagUri($this->getDataContainer()->getId())) { #require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Atom 1.0 IDs must be a valid URI/IRI'); } $id = $dom->createElement('id'); $root->appendChild($id); $text = $dom->createTextNode($this->getDataContainer()->getId()); $id->appendChild($text); } /** * Validate a URI using the tag scheme (RFC 4151) * * @param string $id * @return bool */ protected function _validateTagUri($id) { if (preg_match('/^tag:(?<name>.*),(?<date>\d{4}-?\d{0,2}-?\d{0,2}):(?<specific>.*)(.*:)*$/', $id, $matches)) { $dvalid = false; $nvalid = false; $date = $matches['date']; $d6 = strtotime($date); if ((strlen($date) == 4) && $date <= date('Y')) { $dvalid = true; } elseif ((strlen($date) == 7) && ($d6 < strtotime("now"))) { $dvalid = true; } elseif ((strlen($date) == 10) && ($d6 < strtotime("now"))) { $dvalid = true; } $validator = new Zend_Validate_EmailAddress; if ($validator->isValid($matches['name'])) { $nvalid = true; } else { $nvalid = $validator->isValid('info@' . $matches['name']); } return $dvalid && $nvalid; } return false; } /** * Set entry content * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setContent(DOMDocument $dom, DOMElement $root) { $content = $this->getDataContainer()->getContent(); if (!$content && !$this->getDataContainer()->getLink()) { #require_once 'Zend/Feed/Exception.php'; $message = 'Atom 1.0 entry elements MUST contain exactly one ' . 'atom:content element, or as an alternative, at least one link ' . 'with a rel attribute of "alternate" to indicate an alternate ' . 'method to consume the content.'; $exception = new Zend_Feed_Exception($message); if (!$this->_ignoreExceptions) { throw $exception; } else { $this->_exceptions[] = $exception; return; } } if (!$content) { return; } $element = $dom->createElement('content'); $element->setAttribute('type', 'xhtml'); $xhtmlElement = $this->_loadXhtml($content); $xhtml = $dom->importNode($xhtmlElement, true); $element->appendChild($xhtml); $root->appendChild($element); } /** * Load a HTML string and attempt to normalise to XML */ protected function _loadXhtml($content) { $xhtml = ''; if (class_exists('tidy', false)) { $tidy = new tidy; $config = array( 'output-xhtml' => true, 'show-body-only' => true, 'quote-nbsp' => false ); $encoding = str_replace('-', '', $this->getEncoding()); $tidy->parseString($content, $config, $encoding); $tidy->cleanRepair(); $xhtml = (string) $tidy; } else { $xhtml = $content; } $xhtml = preg_replace(array( "/(<[\/]?)([a-zA-Z]+)/" ), '$1xhtml:$2', $xhtml); $dom = new DOMDocument('1.0', $this->getEncoding()); $dom = Zend_Xml_Security::scan('<xhtml:div xmlns:xhtml="http://www.w3.org/1999/xhtml">' . $xhtml . '</xhtml:div>', $dom); return $dom->documentElement; } /** * Set entry cateories * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setCategories(DOMDocument $dom, DOMElement $root) { $categories = $this->getDataContainer()->getCategories(); if (!$categories) { return; } foreach ($categories as $cat) { $category = $dom->createElement('category'); $category->setAttribute('term', $cat['term']); if (isset($cat['label'])) { $category->setAttribute('label', $cat['label']); } else { $category->setAttribute('label', $cat['term']); } if (isset($cat['scheme'])) { $category->setAttribute('scheme', $cat['scheme']); } $root->appendChild($category); } } /** * Append Source element (Atom 1.0 Feed Metadata) * * @param DOMDocument $dom * @param DOMElement $root * @return void */ protected function _setSource(DOMDocument $dom, DOMElement $root) { $source = $this->getDataContainer()->getSource(); if (!$source) { return; } $renderer = new Zend_Feed_Writer_Renderer_Feed_Atom_Source($source); $renderer->setType($this->getType()); $element = $renderer->render()->getElement(); $imported = $dom->importNode($element, true); $root->appendChild($imported); } }
{ "content_hash": "fd98f2be04963b4a660c49cd0bb9db5e", "timestamp": "", "source": "github", "line_count": 430, "max_line_length": 119, "avg_line_length": 33.509302325581395, "alnum_prop": 0.5211326254424318, "repo_name": "tagalpha/library", "id": "ee4ce524e0065fee58588858b8884e0429369f04", "size": "15106", "binary": false, "copies": "27", "ref": "refs/heads/master", "path": "lib/Zend/Feed/Writer/Renderer/Entry/Atom.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "20063" }, { "name": "ApacheConf", "bytes": "8117" }, { "name": "Batchfile", "bytes": "1036" }, { "name": "CSS", "bytes": "1805855" }, { "name": "HTML", "bytes": "5531269" }, { "name": "JavaScript", "bytes": "1295882" }, { "name": "PHP", "bytes": "45317581" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Ruby", "bytes": "288" }, { "name": "Shell", "bytes": "19717" }, { "name": "XSLT", "bytes": "2066" } ], "symlink_target": "" }
mach_port_name_t ___lastRecievedPort; static CFRunLoopSourceRef ___signalRunLoopSource; CFRunLoopRef ___eventRunLoop; static dispatch_queue_t ___eventDeliveryQueue; void (^___eventCallBack)(GSEventRef); static void _ReceiveEvent(CFMachPortRef port, void *msg, CFIndex size, void *info); static void _PurpleEventSignalCallback(void *context); static void __PurpleEventCallback(GSEventRef event); void _GSAddRunLoopSourceForEventPort(mach_port_t p, CFStringRef mode, int64_t contextID) { CFMachPortContext context = (CFMachPortContext){ 1, (void *)contextID, NULL, NULL, NULL, }; CFMachPortRef port = CFMachPortCreateWithPort(NULL, p, _ReceiveEvent, &context, NULL); CFRunLoopSourceRef eventSource = CFMachPortCreateRunLoopSource(NULL, port, -1); CFRunLoopAddSource(___eventRunLoop, eventSource, mode); CFRelease(eventSource); } void _GSAddSourceForEventPort(mach_port_t eport, dispatch_queue_t queue, int64_t contextID) { if (queue != NULL) { dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_MACH_RECV, (mach_port_name_t)eport, 0, queue); dispatch_source_set_event_handler(source, ^{ mach_port_name_t port = (mach_port_name_t)dispatch_source_get_handle(source); if (port != 0) { ___lastRecievedPort = port; } _ReceiveEvent(NULL, NULL, 0, NULL); do { // __PurpleEventCallback(receivedEvent); if (GSEventQueueIsEmpty(GSEventQueueGetThreadLocalQueue())) { break; } } while (true); return; }); dispatch_resume(source); } else { _GSAddRunLoopSourceForEventPort(eport, kCFRunLoopCommonModes, contextID); _GSAddRunLoopSourceForEventPort(eport, kGSEventReceiveRunLoopMode, contextID); } } static void _ReceiveEvent(CFMachPortRef port, void *msg, CFIndex size, void *info) { CGEventRef event = CGEventCreateNextEvent((int64_t)info); if (event == NULL) { return; } GSEventRef gsEvent = GSEventCreateWithCGEvent(NULL, event); if (gsEvent == NULL) { return; } __PurpleEventCallback(gsEvent); } void __GSEventInitializeShared(dispatch_queue_t callbackQueue) { if (callbackQueue != NULL) { ___eventDeliveryQueue = callbackQueue; dispatch_retain(___eventDeliveryQueue); } else { ___eventRunLoop = CFRunLoopGetCurrent(); CFRetain(___eventRunLoop); } if (___eventRunLoop != NULL) { CFRunLoopSourceContext context = (CFRunLoopSourceContext){ .perform = _PurpleEventSignalCallback, }; ___signalRunLoopSource = CFRunLoopSourceCreate(NULL, -1, &context); CFRunLoopAddSource(___eventRunLoop, ___signalRunLoopSource, kCFRunLoopCommonModes); CFRunLoopAddSource(___eventRunLoop, ___signalRunLoopSource, kGSEventReceiveRunLoopMode); } } static void _PurpleEventSignalCallback(void *context) { __PurpleEventCallback(NULL); } static void __PurpleEventCallback(GSEventRef event) { if (event != NULL) { GSEventQueuePushEvent(event); } if (___lastRecievedPort != 0) { // CGEventRef recievedEvent = NULL; // while ((recievedEvent = CGEventCreateNextEvent()) != NULL) { // GSEventRef evt = GSEventCreateWithCGEvent(NULL, recievedEvent); // if (evt != NULL) { // GSEventQueuePushEvent(evt); // } // } } event = GSEventQueueGetCurrentEvent(); if (event == NULL) { goto fail; } if (___eventCallBack != NULL) { ___eventCallBack(event); } CFRelease(event); fail: GSEventQueuePopEvent(); if (___signalRunLoopSource != NULL) { CFRunLoopSourceSignal(___signalRunLoopSource); } }
{ "content_hash": "62c8915dad35a859d72231064f5cef59", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 119, "avg_line_length": 28.781512605042018, "alnum_prop": 0.7232116788321168, "repo_name": "NUIKit/GraphicsServices", "id": "2c76d8ec83795c95736026a71cba94e33efc841e", "size": "3655", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GraphicsServices/GSPrivate.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "18835" }, { "name": "Objective-C", "bytes": "4070" } ], "symlink_target": "" }
int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }
{ "content_hash": "b6c1264e388da405e565666e1647160e", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 90, "avg_line_length": 31.6, "alnum_prop": 0.6582278481012658, "repo_name": "TelerikAcademy/Mobile-Applications-with-iOS", "id": "076ba9902a557f3746b1067ce1975da3e0fb3bcc", "size": "348", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Resources/Archive-2015/12. CoreData-demos/CoreDataDemo2/main.m", "mode": "33188", "license": "mit", "language": [ { "name": "Groff", "bytes": "117000" }, { "name": "HTML", "bytes": "41632" }, { "name": "JavaScript", "bytes": "9696" }, { "name": "Objective-C", "bytes": "3516357" }, { "name": "Ruby", "bytes": "681" }, { "name": "Shell", "bytes": "24057" }, { "name": "Swift", "bytes": "42326" } ], "symlink_target": "" }
package de.unistuttgart.ipvs.as.flexmash.servlet.engine; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Base64; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.xml.soap.MessageFactory; import javax.xml.soap.MimeHeaders; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPConnection; import javax.xml.soap.SOAPConnectionFactory; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.soap.SOAPPart; /** * class to start the BPEL engine and deploy a process */ public class EngineProcessStarter { public static final String PATH = System.getenv("FLEXMASH")+"/files/"; /** * generates all necessary files to deploy a process on ApacheODE * * @param xml * the BPEl process as XML string */ public static void generateFiles(String xml) { generateBPELFile(xml); zipFiles(); deployZip(); } /** * generates a BPEL file from a BPEL XML string * * @param bpel * the BPEL XML string */ private static void generateBPELFile(String bpel) { Writer writer = null; try { // config file File file = new File("files/DataMashupProcess.bpel"); File dir = new File("files"); if (!dir.exists()) { dir.mkdir(); System.out.println("dir doesn't exist"); } else { System.out.println("dir exists"); } if (!file.exists()) { file.createNewFile(); System.out.println("bpelfile doesn't exist"); } else { System.out.println("bpelfile exists"); } writer = new BufferedWriter(new FileWriter(file.getAbsoluteFile())); writer.write(bpel); } catch (IOException ex) { System.out.println("IOException"); } finally { try { writer.close(); } catch (Exception ex) { } } } /** * packs all necessary deployment components in a ZIP file to be compatible * with the ApacheODE engine */ private static void zipFiles() { ZipOutputStream zipOutStream = null; FileInputStream bpelInStream = null; FileInputStream wsdlInStream = null; FileInputStream deployInStream = null; FileInputStream joinInStream = null; FileInputStream twitEInStream = null; FileInputStream sqlEInStream = null; FileInputStream twitFInStream = null; FileInputStream sqlFInStream = null; try { // paths config System.out.println(new File("test").getAbsolutePath()); zipOutStream = new ZipOutputStream(new FileOutputStream(PATH + "/DataMashupProcess.zip")); bpelInStream = new FileInputStream(PATH + "/DataMashupProcess.bpel"); wsdlInStream = new FileInputStream(PATH + "/DataMashupProcessArtifacts.wsdl"); deployInStream = new FileInputStream(PATH + "/deploy.xml"); joinInStream = new FileInputStream(PATH + "/Join.wsdl"); twitEInStream = new FileInputStream(PATH + "/TwitterEtractor.wsdl"); sqlEInStream = new FileInputStream(PATH + "/NYTRSSExtractor.wsdl"); twitFInStream = new FileInputStream(PATH + "/TwitterFilter.wsdl"); sqlFInStream = new FileInputStream(PATH + "/TwitterService.wsdl"); addToZipStream(bpelInStream, zipOutStream, PATH + "/DataMashupProcess.bpel"); addToZipStream(wsdlInStream, zipOutStream, PATH + "/DataMashupProcessArtifacts.wsdl"); addToZipStream(deployInStream, zipOutStream, PATH + "/deploy.xml"); addToZipStream(joinInStream, zipOutStream, PATH + "/Join.wsdl"); addToZipStream(twitEInStream, zipOutStream, PATH + "/TwitterEtractor.wsdl"); addToZipStream(sqlEInStream, zipOutStream, PATH + "/NYTRSSExtractor.wsdl"); addToZipStream(twitFInStream, zipOutStream, PATH + "/TwitterFilter.wsdl"); addToZipStream(sqlFInStream, zipOutStream, PATH + "/TwitterService.wsdl"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (bpelInStream != null) { try { bpelInStream.close(); } catch (IOException e) { } } if (wsdlInStream != null) { try { wsdlInStream.close(); } catch (IOException e) { } } if (deployInStream != null) { try { deployInStream.close(); } catch (IOException e) { } } if (zipOutStream != null) { try { zipOutStream.closeEntry(); zipOutStream.close(); } catch (IOException e) { } } } } /** * helper method to add data to a zip file * * @param in * the file as stream * @param out * the output stream * @param name * the name of the file * @throws IOException * this exception occurs if the file is not readable or damaged */ private static void addToZipStream(FileInputStream in, ZipOutputStream out, String name) throws IOException { int len; byte[] buffer = new byte[2048]; out.putNextEntry(new ZipEntry(new File(name).getName())); while ((len = in.read(buffer, 0, buffer.length)) > 0) { out.write(buffer, 0, len); } } /** * deploys the generated ZIP in the ApacheODE BPEL engine */ private static void deployZip() { try { // Create Connection SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection soapConnection = soapConnectionFactory.createConnection(); // SOAP Message String url = "http://localhost:8081/ode/processes/DeploymentService/deploy"; MessageFactory messageFactory = MessageFactory.newInstance(); SOAPMessage soapMessage = messageFactory.createMessage(); SOAPPart soapPart = soapMessage.getSOAPPart(); String serverURI = "http://www.apache.org/ode/pmapi"; // SOAP Envelope SOAPEnvelope envelope = soapPart.getEnvelope(); envelope.addNamespaceDeclaration("pmap", "http://www.apache.org/ode/pmapi"); envelope.addNamespaceDeclaration("dep", "http://www.apache.org/ode/deployapi"); // SOAP Body SOAPBody soapBody = envelope.getBody(); SOAPElement soapBodyElem = soapBody.addChildElement("deploy", "pmap"); SOAPElement soapBodyElemA = soapBodyElem.addChildElement("name"); soapBodyElemA.addTextNode("DataMashupProcess"); SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("package"); SOAPElement soapBodyElem2 = soapBodyElem1.addChildElement("zip", "dep"); Path zipFilePath = Paths.get(PATH + "/DataMashupProcess.zip"); byte[] zipFileData = Files.readAllBytes(zipFilePath); soapBodyElem2.addTextNode(Base64.getMimeEncoder().encodeToString(zipFileData)); MimeHeaders headers = soapMessage.getMimeHeaders(); headers.addHeader("SOAPAction", serverURI + "DataMashupProcessRequest"); soapMessage.saveChanges(); /* Print the request message */ System.out.print("Request SOAP Message:"); try { soapMessage.writeTo(System.out); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(); SOAPMessage soapResponse = soapConnection.call(soapMessage, url); // print SOAP Response System.out.print("Response SOAP Message:"); try { soapResponse.writeTo(System.out); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } soapConnection.close(); } catch (SOAPException e) { e.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
{ "content_hash": "4222b3bf1a6ed7b00005f11f04b513d7", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 110, "avg_line_length": 30.35483870967742, "alnum_prop": 0.702577045696068, "repo_name": "hirmerpl/FlexMash", "id": "2e94645755e93660a6f14e3ace704f719db649a8", "size": "7528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/de/unistuttgart/ipvs/as/flexmash/servlet/engine/EngineProcessStarter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "21436272" }, { "name": "HTML", "bytes": "14290" }, { "name": "Java", "bytes": "136935" }, { "name": "JavaScript", "bytes": "15376176" }, { "name": "PHP", "bytes": "144867" }, { "name": "Python", "bytes": "5010" }, { "name": "Ruby", "bytes": "15630" } ], "symlink_target": "" }
<?php declare(strict_types=1); /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <[email protected]> * Dariusz Rumiński <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Tests\Fixer\PhpUnit; use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; use PhpCsFixer\Tests\Test\AbstractFixerTestCase; /** * @author Dariusz Rumiński <[email protected]> * * @internal * * @covers \PhpCsFixer\Fixer\PhpUnit\PhpUnitStrictFixer */ final class PhpUnitStrictFixerTest extends AbstractFixerTestCase { /** * @dataProvider provideTestFixCases */ public function testFix(string $expected, ?string $input = null): void { $this->doTest($expected, $input); $this->fixer->configure(['assertions' => array_keys($this->getMethodsMap())]); $this->doTest($expected, $input); } public function provideTestFixCases(): array { $cases = [ ['<?php $self->foo();'], [self::generateTest('$self->foo();')], ]; foreach ($this->getMethodsMap() as $methodBefore => $methodAfter) { $cases[] = [self::generateTest("\$sth->{$methodBefore}(1, 1);")]; $cases[] = [self::generateTest("\$sth->{$methodAfter}(1, 1);")]; $cases[] = [self::generateTest("\$this->{$methodBefore}(1, 2, 'message', \$toMuch);")]; $cases[] = [ self::generateTest("\$this->{$methodAfter}(1, 2);"), self::generateTest("\$this->{$methodBefore}(1, 2);"), ]; $cases[] = [ self::generateTest("\$this->{$methodAfter}(1, 2); \$this->{$methodAfter}(1, 2);"), self::generateTest("\$this->{$methodBefore}(1, 2); \$this->{$methodBefore}(1, 2);"), ]; $cases[] = [ self::generateTest("\$this->{$methodAfter}(1, 2, 'description');"), self::generateTest("\$this->{$methodBefore}(1, 2, 'description');"), ]; $cases[] = [ self::generateTest("\$this->/*aaa*/{$methodAfter} \t /**bbb*/ ( /*ccc*/1 , 2);"), self::generateTest("\$this->/*aaa*/{$methodBefore} \t /**bbb*/ ( /*ccc*/1 , 2);"), ]; $cases[] = [ self::generateTest("\$this->{$methodAfter}(\$expectedTokens->count() + 10, \$tokens->count() ? 10 : 20 , 'Test');"), self::generateTest("\$this->{$methodBefore}(\$expectedTokens->count() + 10, \$tokens->count() ? 10 : 20 , 'Test');"), ]; $cases[] = [ self::generateTest("self::{$methodAfter}(1, 2);"), self::generateTest("self::{$methodBefore}(1, 2);"), ]; $cases[] = [ self::generateTest("static::{$methodAfter}(1, 2);"), self::generateTest("static::{$methodBefore}(1, 2);"), ]; $cases[] = [ self::generateTest("STATIC::{$methodAfter}(1, 2);"), self::generateTest("STATIC::{$methodBefore}(1, 2);"), ]; } return $cases; } /** * Only method calls with 2 or 3 arguments should be fixed. * * @dataProvider provideTestNoFixWithWrongNumberOfArgumentsCases */ public function testNoFixWithWrongNumberOfArguments(string $expected): void { $this->fixer->configure(['assertions' => array_keys($this->getMethodsMap())]); $this->doTest($expected); } public function provideTestNoFixWithWrongNumberOfArgumentsCases(): array { $cases = []; foreach ($this->getMethodsMap() as $candidate => $fix) { $cases[sprintf('do not change call to "%s" without arguments.', $candidate)] = [ self::generateTest(sprintf('$this->%s();', $candidate)), ]; foreach ([1, 4, 5, 10] as $argumentCount) { $cases[sprintf('do not change call to "%s" with #%d arguments.', $candidate, $argumentCount)] = [ self::generateTest( sprintf( '$this->%s(%s);', $candidate, substr(str_repeat('$a, ', $argumentCount), 0, -2) ) ), ]; } } return $cases; } public function testInvalidConfig(): void { $this->expectException(InvalidFixerConfigurationException::class); $this->expectExceptionMessageMatches('/^\[php_unit_strict\] Invalid configuration: The option "assertions" .*\.$/'); $this->fixer->configure(['assertions' => ['__TEST__']]); } /** * @requires PHP 7.3 * @dataProvider provideFix73Cases */ public function testFix73(string $expected, string $input): void { $this->doTest($expected, $input); } public function provideFix73Cases(): \Generator { foreach ($this->getMethodsMap() as $methodBefore => $methodAfter) { yield [ self::generateTest("static::{$methodAfter}(1, 2,);"), self::generateTest("static::{$methodBefore}(1, 2,);"), ]; yield [ self::generateTest("self::{$methodAfter}(1, \$a, '', );"), self::generateTest("self::{$methodBefore}(1, \$a, '', );"), ]; } } /** * @return array<string, string> */ private function getMethodsMap(): array { return [ 'assertAttributeEquals' => 'assertAttributeSame', 'assertAttributeNotEquals' => 'assertAttributeNotSame', 'assertEquals' => 'assertSame', 'assertNotEquals' => 'assertNotSame', ]; } private static function generateTest(string $content): string { return "<?php final class FooTest extends \\PHPUnit_Framework_TestCase {\n public function testSomething() {\n ".$content."\n }\n}\n"; } }
{ "content_hash": "0c4f8f67dae22f5844a7e0b642c3c460", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 155, "avg_line_length": 33.93370165745856, "alnum_prop": 0.5244220123738196, "repo_name": "Slamdunk/PHP-CS-Fixer", "id": "21b88a7e75ee35add3708d758fe4cc305e5027f5", "size": "6144", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Fixer/PhpUnit/PhpUnitStrictFixerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "5280" }, { "name": "PHP", "bytes": "9087062" }, { "name": "Shell", "bytes": "5394" } ], "symlink_target": "" }
yanmori2 ======== An editor for the Yanmori 2.fus file shipped with the Starship Corporation 0.15 alpha License ======= MIT license
{ "content_hash": "fca32f97c536a076cddee13a0eb92dc2", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 85, "avg_line_length": 15, "alnum_prop": 0.7037037037037037, "repo_name": "j6cubic/yanmori2", "id": "fbe5b43d85b562bb61843ad23b29f13d53e33fd2", "size": "135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "26254" } ], "symlink_target": "" }
// A good bit of this code was derived from the Three20 project // and was customized to work inside testandroidmap // // All modifications by testandroidmap are licensed under // the Apache License, Version 2.0 // // // Copyright 2009 Facebook // // 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. // #ifdef USE_TI_UIDASHBOARDVIEW #import <UIKit/UIKit.h> @class LauncherButton; @class LauncherItem; @protocol LauncherViewDelegate; @interface LauncherView : UIView<UIScrollViewDelegate> { @private id<LauncherViewDelegate> delegate; UIScrollView *scrollView; UIPageControl *pager; NSMutableArray *pages; NSMutableArray *buttons; NSInteger columnCount; NSInteger rowCount; LauncherButton *dragButton; NSTimer* editHoldTimer; NSTimer* springLoadTimer; UITouch* dragTouch; NSInteger positionOrigin; CGPoint dragOrigin; CGPoint touchOrigin; BOOL editing; BOOL springing; BOOL editable; } @property(nonatomic) NSInteger columnCount; @property(nonatomic) NSInteger rowCount; @property(nonatomic) NSInteger currentPageIndex; @property(nonatomic,assign) id<LauncherViewDelegate> delegate; @property(nonatomic,readonly) BOOL editing; @property(nonatomic,assign) BOOL editable; - (void)addItem:(LauncherItem*)item animated:(BOOL)animated; - (void)removeItem:(LauncherItem*)item animated:(BOOL)animated; - (void)beginEditing; - (void)endEditing; - (LauncherItem*)itemForIndex:(NSInteger)index; - (NSArray*)items; @end @protocol LauncherViewDelegate <NSObject> @optional - (void)launcherView:(LauncherView*)launcher didAddItem:(LauncherItem*)item; - (void)launcherView:(LauncherView*)launcher didRemoveItem:(LauncherItem*)item; - (void)launcherView:(LauncherView*)launcher willDragItem:(LauncherItem*)item; - (void)launcherView:(LauncherView*)launcher didDragItem:(LauncherItem*)item; - (void)launcherView:(LauncherView*)launcher didMoveItem:(LauncherItem*)item; - (void)launcherView:(LauncherView*)launcher didSelectItem:(LauncherItem*)item; - (void)launcherViewDidBeginEditing:(LauncherView*)launcher; - (void)launcherViewDidEndEditing:(LauncherView*)launcher; - (BOOL)launcherViewShouldWobble:(LauncherView*)launcher; @end #endif
{ "content_hash": "c4927f713921dd9f1a297e64792b784e", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 79, "avg_line_length": 27.255102040816325, "alnum_prop": 0.7798577311868214, "repo_name": "aaronksaunders/tidrop_commonjs", "id": "843d88f3c504216bc4912be6adf78cf25e636eff", "size": "2993", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/iphone/Classes/LauncherView.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "218519" }, { "name": "C++", "bytes": "57221" }, { "name": "JavaScript", "bytes": "6148" }, { "name": "Objective-C", "bytes": "2814505" } ], "symlink_target": "" }
# Copyright 2009, Jean-Michel Sizun # Copyright 2009 Frank Scholz <[email protected]> import os.path import time from twisted.internet import threads from twisted.web import server, static from twisted.web.error import PageRedirect from coherence.upnp.core.utils import ReverseProxyUriResource from twisted.internet import task from coherence.upnp.core import utils from coherence.upnp.core import DIDLLite from coherence.backend import BackendStore, BackendItem, Container, LazyContainer, \ AbstractBackendStore from coherence import log from urlparse import urlsplit import gdata.photos.service import gdata.media import gdata.geo DEFAULT_NAME = 'Picasa Web Albums' FEED_URI = 'http://picasaweb.google.com/data/feed/api/featured' class PicasaProxy(ReverseProxyUriResource): def __init__(self, uri): ReverseProxyUriResource.__init__(self, uri) def render(self, request): request.requestHeaders.removeHeader('referer') return ReverseProxyUriResource.render(self, request) class PicasaPhotoItem(BackendItem): def __init__(self, photo): BackendItem.__init__(self) #print photo self.photo = photo self.name = photo.summary.text if self.name is None: self.name = photo.title.text self.duration = None self.size = None self.mimetype = photo.content.type self.description = photo.summary.text self.date = None self.item = None self.photo_url = photo.content.src self.thumbnail_url = photo.media.thumbnail[0].url self.url = None self.location = PicasaProxy(self.photo_url) def replace_by(self, item): #print photo self.photo = item.photo self.name = photo.summary.text if self.name is None: self.name = photo.title.text self.mimetype = self.photo.content.type self.description = self.photo.summary.text self.photo_url = self.photo.content.src self.thumbnail_url = self.photo.media.thumbnail[0].url self.location = PicasaProxy(self.photo_url) return True def get_item(self): if self.item == None: upnp_id = self.get_id() upnp_parent_id = self.parent.get_id() self.item = DIDLLite.Photo(upnp_id, upnp_parent_id, self.name) res = DIDLLite.Resource(self.url, 'http-get:*:%s:*' % self.mimetype) self.item.res.append(res) self.item.childCount = 0 return self.item def get_path(self): return self.url def get_id(self): return self.storage_id class PicasaStore(AbstractBackendStore): logCategory = 'picasa_store' implements = ['MediaServer'] description = ('Picasa Web Albums', 'connects to the Picasa Web Albums service and exposes the featured photos and albums for a given user.', None) options = [{'option': 'name', 'text': 'Server Name:', 'type': 'string', 'default': 'my media', 'help': 'the name under this MediaServer shall show up with on other UPnP clients'}, {'option': 'version', 'text': 'UPnP Version:', 'type': 'int', 'default': 2, 'enum': (2, 1), 'help': 'the highest UPnP version this MediaServer shall support', 'level': 'advance'}, {'option': 'uuid', 'text': 'UUID Identifier:', 'type': 'string', 'help': 'the unique (UPnP) identifier for this MediaServer, usually automatically set', 'level': 'advance'}, {'option': 'refresh', 'text': 'Refresh period', 'type': 'string'}, {'option': 'login', 'text': 'User ID:', 'type': 'string', 'group': 'User Account'}, {'option': 'password', 'text': 'Password:', 'type': 'string', 'group': 'User Account'}, ] def __init__(self, server, **kwargs): AbstractBackendStore.__init__(self, server, **kwargs) self.name = kwargs.get('name', DEFAULT_NAME) self.refresh = int(kwargs.get('refresh', 60)) * 60 self.login = kwargs.get('userid', kwargs.get('login', '')) self.password = kwargs.get('password', '') rootContainer = Container(None, self.name) self.set_root_item(rootContainer) self.AlbumsContainer = LazyContainer(rootContainer, 'My Albums', None, self.refresh, self.retrieveAlbums) rootContainer.add_child(self.AlbumsContainer) self.FeaturedContainer = LazyContainer(rootContainer, 'Featured photos', None, self.refresh, self.retrieveFeaturedPhotos) rootContainer.add_child(self.FeaturedContainer) self.init_completed() def __repr__(self): return self.__class__.__name__ def upnp_init(self): self.current_connection_id = None if self.server: self.server.connection_manager_server.set_variable(0, 'SourceProtocolInfo', 'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,' 'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_SM;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,' 'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_MED;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,' 'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_LRG;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000,' 'http-get:*:image/jpeg:*,' 'http-get:*:image/gif:*,' 'http-get:*:image/png:*', default=True) self.wmc_mapping = {'16': self.get_root_id()} self.gd_client = gdata.photos.service.PhotosService() self.gd_client.email = self.login self.gd_client.password = self.password self.gd_client.source = 'Coherence UPnP backend' if len(self.login) > 0: d = threads.deferToThread(self.gd_client.ProgrammaticLogin) def retrieveAlbums(self, parent=None): albums = threads.deferToThread(self.gd_client.GetUserFeed) def gotAlbums(albums): if albums is None: print "Unable to retrieve albums" return for album in albums.entry: title = album.title.text album_id = album.gphoto_id.text item = LazyContainer(parent, title, album_id, self.refresh, self.retrieveAlbumPhotos, album_id=album_id) parent.add_child(item, external_id=album_id) def gotError(error): print "ERROR: %s" % error albums.addCallbacks(gotAlbums, gotError) return albums def retrieveFeedPhotos (self, parent=None, feed_uri=''): #print feed_uri photos = threads.deferToThread(self.gd_client.GetFeed, feed_uri) def gotPhotos(photos): if photos is None: print "Unable to retrieve photos for feed %s" % feed_uri return for photo in photos.entry: photo_id = photo.gphoto_id.text item = PicasaPhotoItem(photo) item.parent = parent parent.add_child(item, external_id=photo_id) def gotError(error): print "ERROR: %s" % error photos.addCallbacks(gotPhotos, gotError) return photos def retrieveAlbumPhotos (self, parent=None, album_id=''): album_feed_uri = '/data/feed/api/user/%s/albumid/%s?kind=photo' % (self.login, album_id) return self.retrieveFeedPhotos(parent, album_feed_uri) def retrieveFeaturedPhotos (self, parent=None): return self.retrieveFeedPhotos(parent, FEED_URI)
{ "content_hash": "e0cecfa306be90b5bcec2b1408ecb009", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 186, "avg_line_length": 40.61, "alnum_prop": 0.5886481162275302, "repo_name": "coherence-project/Coherence", "id": "ef2e903d16775a55ddacf749e27432d44eb04d62", "size": "8206", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "coherence/backends/picasa_storage.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "1305048" }, { "name": "Roff", "bytes": "712" }, { "name": "Shell", "bytes": "1569" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright ${year} Open Networking Foundation ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>${groupId}</groupId> <artifactId>${artifactId}</artifactId> <version>${version}</version> <packaging>bundle</packaging> <description>ONOS OSGi bundle archetype</description> <url>http://onosproject.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <onos.version>1.13.0-SNAPSHOT</onos.version> <!-- Uncomment to generate ONOS app from this module. <onos.app.name>org.foo.app</onos.app.name> <onos.app.title>Foo App</onos.app.title> <onos.app.origin>Foo, Inc.</onos.app.origin> <onos.app.category>default</onos.app.category> <onos.app.url>http://onosproject.org</onos.app.url> <onos.app.readme>ONOS OSGi bundle archetype.</onos.app.readme> --> </properties> <dependencies> <dependency> <groupId>org.onosproject</groupId> <artifactId>onos-api</artifactId> <version>${onos.version}</version> </dependency> <dependency> <groupId>org.onosproject</groupId> <artifactId>onlab-osgi</artifactId> <version>${onos.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.onosproject</groupId> <artifactId>onos-api</artifactId> <version>${onos.version}</version> <scope>test</scope> <classifier>tests</classifier> </dependency> <dependency> <groupId>org.apache.felix</groupId> <artifactId>org.apache.felix.scr.annotations</artifactId> <version>1.9.12</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>3.0.1</version> <extensions>true</extensions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-scr-plugin</artifactId> <version>1.21.0</version> <executions> <execution> <id>generate-scr-srcdescriptor</id> <goals> <goal>scr</goal> </goals> </execution> </executions> <configuration> <supportedProjectTypes> <supportedProjectType>bundle</supportedProjectType> <supportedProjectType>war</supportedProjectType> </supportedProjectTypes> </configuration> </plugin> <plugin> <groupId>org.onosproject</groupId> <artifactId>onos-maven-plugin</artifactId> <version>1.10</version> <executions> <execution> <id>cfg</id> <phase>generate-resources</phase> <goals> <goal>cfg</goal> </goals> </execution> <execution> <id>swagger</id> <phase>generate-sources</phase> <goals> <goal>swagger</goal> </goals> </execution> <execution> <id>app</id> <phase>package</phase> <goals> <goal>app</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
{ "content_hash": "05bb6ae9091462324716d186b8867a28", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 204, "avg_line_length": 37.15277777777778, "alnum_prop": 0.5134579439252337, "repo_name": "osinstom/onos", "id": "370ec4fac46a2bc030486f14c31a187750d8f162", "size": "5618", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/package/archetypes/bundle/src/main/resources/archetype-resources/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "233181" }, { "name": "HTML", "bytes": "119665" }, { "name": "Java", "bytes": "38529527" }, { "name": "JavaScript", "bytes": "3930281" }, { "name": "Makefile", "bytes": "1058" }, { "name": "P4", "bytes": "78664" }, { "name": "Python", "bytes": "227209" }, { "name": "Shell", "bytes": "4841" } ], "symlink_target": "" }
package trashday.ui.requests; import static org.junit.Assert.*; import java.time.LocalTime; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazon.speech.slu.Intent; import com.amazon.speech.slu.Slot; public class SlotTimeOfDayTest { /** Log object for this class */ private static final Logger log = LoggerFactory.getLogger(SlotTimeOfDayTest.class); /** Test Data */ private static Intent testIntent; /** Test Data */ private static Slot testSlotNormal; /** Test Data */ private static Map<String, Slot> testSlots; /** Test Data */ private SlotTimeOfDay testSlotTimeOfDay; @BeforeClass public static void setUpBeforeClass() throws Exception { testSlots = new HashMap<String, Slot>(); Slot.Builder builderSlot = Slot.builder(); testSlotNormal = builderSlot .withName("TimeOfDay") .withValue("14:50") .build(); testSlots.put("TimeOfDay", testSlotNormal); Intent.Builder builder = Intent.builder(); testIntent = builder .withName("MyIntentName") .withSlots(testSlots) .build(); log.info("setUpBeforeClass: testIntent={}", testIntent); } @Before public void setUp() throws Exception { testSlotTimeOfDay = new SlotTimeOfDay(testIntent); log.info("setUpBeforeClass: testSlotTimeOfDay={}", testSlotTimeOfDay); } @Test public void testGetSlot() { Slot expectedSlot = testSlotNormal; Slot actualSlot = testSlotTimeOfDay.getSlot(); assertEquals(expectedSlot, actualSlot); } @Test public void testGetName() { String expectedName = "TimeOfDay"; String actualName = testSlotTimeOfDay.getName(); assertEquals(expectedName, actualName); } @Test public void testGetDescription() { String expectedDescription = "Time Of Day"; String actualDescription = testSlotTimeOfDay.getDescription(); assertEquals(expectedDescription, actualDescription); } @Test public void testIsEmpty() { boolean expectedIsEmpty = false; boolean actualIsEmpty = testSlotTimeOfDay.isEmpty(); assertEquals(expectedIsEmpty, actualIsEmpty); } @Test public void testValidate() { // Validate for a "good" Slot in SlotTimeOfDay LocalTime expectedTimeOfDay = LocalTime.of(14, 50); testSlots.clear(); testSlots.put("TimeOfDay", Slot.builder().withName("TimeOfDay").withValue("14:50").build()); Intent intent = Intent.builder().withName("MyIntentName").withSlots(testSlots).build(); SlotTimeOfDay slotTimeOfDay = new SlotTimeOfDay(intent); LocalTime actualTimeOfDay = slotTimeOfDay.validate(); assertEquals(expectedTimeOfDay, actualTimeOfDay); // Validate for a "good" Slot in SlotTimeOfDay expectedTimeOfDay = LocalTime.of(7, 30); testSlots.clear(); testSlots.put("TimeOfDay", Slot.builder().withName("TimeOfDay").withValue("07:30").build()); intent = Intent.builder().withName("MyIntentName").withSlots(testSlots).build(); slotTimeOfDay = new SlotTimeOfDay(intent); actualTimeOfDay = slotTimeOfDay.validate(); assertEquals(expectedTimeOfDay, actualTimeOfDay); // Validate for a null Slot in SlotTimeOfDay expectedTimeOfDay = null; testSlots.clear(); testSlots.put("TimeOfDay", Slot.builder().withName("TimeOfDay").withValue(null).build()); intent = Intent.builder().withName("MyIntentName").withSlots(testSlots).build(); slotTimeOfDay = new SlotTimeOfDay(intent); actualTimeOfDay = slotTimeOfDay.validate(); assertEquals(expectedTimeOfDay, actualTimeOfDay); // Validate for a empty (whitespace only) Slot in SlotTimeOfDay expectedTimeOfDay = null; testSlots.clear(); testSlots.put("TimeOfDay", Slot.builder().withName("TimeOfDay").withValue(" ").build()); intent = Intent.builder().withName("MyIntentName").withSlots(testSlots).build(); slotTimeOfDay = new SlotTimeOfDay(intent); actualTimeOfDay = slotTimeOfDay.validate(); assertEquals(expectedTimeOfDay, actualTimeOfDay); // Validate for an unknown time zone name Slot in SlotTimeOfDay expectedTimeOfDay = null; testSlots.clear(); testSlots.put("TimeOfDay", Slot.builder().withName("TimeOfDay").withValue("garbage").build()); intent = Intent.builder().withName("MyIntentName").withSlots(testSlots).build(); slotTimeOfDay = new SlotTimeOfDay(intent); actualTimeOfDay = slotTimeOfDay.validate(); assertEquals(expectedTimeOfDay, actualTimeOfDay); } }
{ "content_hash": "6383986d149bc2cdb942ad3017ff97e0", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 96, "avg_line_length": 34.12307692307692, "alnum_prop": 0.7421100090171325, "repo_name": "jtbaldwin/Alexa-Trash-Day", "id": "5855b357e32d824cf02eec65fc268250299c75fc", "size": "4436", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/trashday/ui/requests/SlotTimeOfDayTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "30835" }, { "name": "HTML", "bytes": "8532502" }, { "name": "Java", "bytes": "955278" }, { "name": "JavaScript", "bytes": "23429" } ], "symlink_target": "" }
import { ColumnOptions } from "../options/ColumnOptions"; /** * Special type of column that is available only for MongoDB database. * Marks your entity's column to be an object id. */ export declare function ObjectIdColumn(options?: ColumnOptions): Function;
{ "content_hash": "6896b88d1c14481ae2720ff75d85b5dd", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 74, "avg_line_length": 43.666666666666664, "alnum_prop": 0.7557251908396947, "repo_name": "JacksonLee2019/CS341-VolunteerSchedule", "id": "a2fe093772081c1332a12a9c0b64dc648af1370b", "size": "262", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/typeorm/browser/decorator/columns/ObjectIdColumn.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "67" }, { "name": "HTML", "bytes": "13223" }, { "name": "JavaScript", "bytes": "1597" }, { "name": "TypeScript", "bytes": "30831" } ], "symlink_target": "" }
require File.dirname(__FILE__) + '/../../test_helper' require 'admin/users_controller' # Re-raise errors caught by the controller. class Admin::UsersController; def rescue_action(e) raise e end; end class Admin::UsersControllerTest < Test::Unit::TestCase fixtures :users, :sites, :memberships def setup @controller = Admin::UsersController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end def test_should_allow_site_admin login_as :arthur get :index assert_response :success end def test_should_restrict_site_member login_as :arthur, :hostess get :index assert_redirected_to :controller => 'account', :action => 'login' end def test_should_allow_site_member_to_view_profile login_as :arthur, :hostess get :show, :id => users(:arthur).id.to_s assert_response :success end def test_should_not_explode_on_index login_as :quentin get :index assert_response :success end def test_should_create_user login_as :quentin assert_difference User, :count do assert_difference Membership, :count do post :create, :user => { :login => 'bob', :email => '[email protected]', :password => 'testy', :password_confirmation => 'testy', :admin => true } assert_models_equal [sites(:first)], assigns(:user).sites assert_equal assigns(:user), User.authenticate_for(sites(:first), 'bob', 'testy') assert_redirected_to :action => 'index' assert flash[:notice] end end end def test_should_update_email_and_password login_as :quentin post :update, :id => users(:quentin).id, :user => { :email => '[email protected]', :password => 'testy', :password_confirmation => 'testy' } users(:quentin).reload assert_equal '[email protected]', users(:quentin).email assert_equal users(:quentin), User.authenticate_for(sites(:first), 'quentin', 'testy') assert_response :success end def test_should_update_email_and_password_as_site_member login_as :arthur, :hostess post :update, :id => users(:arthur).id, :user => { :email => '[email protected]', :password => 'testy', :password_confirmation => 'testy' } users(:arthur).reload assert_equal '[email protected]', users(:arthur).email assert_equal users(:arthur), User.authenticate_for(sites(:hostess), 'arthur', 'testy') assert_response :success end def test_should_leave_password_alone login_as :quentin post :update, :id => users(:quentin).id, :user => { :email => '[email protected]', :password => '', :password_confirmation => '' } users(:quentin).reload assert_equal '[email protected]', users(:quentin).email assert_equal users(:quentin), User.authenticate_for(sites(:first), 'quentin', 'test') assert_response :success end def test_should_show_error_while_updating login_as :quentin post :update, :id => users(:quentin).id, :user => { :email => '[email protected]', :password => 'tea', :password_confirmation => '' } users(:quentin).reload assert_equal '[email protected]', users(:quentin).email assert_equal users(:quentin), User.authenticate_for(sites(:first), 'quentin', 'test') assert_response :success end def test_should_show_error_while_creating login_as :quentin post :create, :user => { :email => '[email protected]', :password => 'tea', :password_confirmation => '' } assert_response :success end def test_should_show_correct_form_action login_as :quentin get :show, :id => users(:quentin).id assert_tag :tag => 'form', :attributes => { :action => '/admin/users/update/1' } end def test_should_highlight_correct_filter login_as :quentin get :show, :id => users(:quentin).id assert_tag :tag => 'select', :attributes => { :id => 'user_filter' }, :descendant => { :tag => 'option', :attributes => { :selected => 'selected', :value => 'textile_filter' } } get :show, :id => users(:arthur).id assert_tag :tag => 'select', :attributes => { :id => 'user_filter' }, :descendant => { :tag => 'option', :attributes => { :selected => 'selected', :value => 'markdown_filter' } } end def test_should_save_new_filter login_as :quentin post :update, :id => '1', :user => { :filter => 'markdown_filter' } users(:quentin).reload assert_equal 'markdown_filter', users(:quentin).filter end def test_should_not_permit_promoting_self_to_admin_in_update login_as :arthur, :hostess assert !users(:arthur).admin, "we mean to test with a non-admin user" post :update, :id => users(:arthur).id, :user => { :admin => 'true' } users(:arthur).reload assert !users(:arthur).admin, "user.admin shouldn't change" assert_response :success end def test_should_not_permit_changing_own_created_at_in_update login_as :arthur, :hostess prev_time = users(:arthur).created_at post :update, :id => users(:arthur).id, :user => { :created_at => prev_time - 1.year } users(:arthur).reload assert_equal prev_time, users(:arthur).created_at, "user.created_at shouldn't change" assert_response :success end def test_should_not_permit_changing_owned_articles_in_update login_as :quentin user = users(:quentin) prev_article_ids = user.article_ids assert prev_article_ids.size > 2, "Test needs more than 2 articles. Pick another user?" #but now we're going to try to own only the first 2 of them... post :update, :id => user.id, :user => { :article_ids => prev_article_ids[0..1] } user.reload assert_equal prev_article_ids, user.article_ids, "user.article_ids[] shouldn't change" assert_response :success end def test_should_show_deleted_users login_as :quentin get :index assert_equal 4, assigns(:users).size assert_select "#users li[id='user-1']" do assert_select "[class='clear']" end assert_select "#users li[id='user-2']" do assert_select "[class='clear']" end assert_select "#disabled_users li[id='user-3']" do assert_select "[class='clear deleted']" end end def test_should_not_disable_as_site_member login_as :arthur, :hostess assert_no_difference User, :count do xhr :post, :destroy, :id => users(:arthur).id assert_redirected_to :controller => 'account', :action => 'login' end end def test_should_disable_site_admin login_as :quentin xhr :post, :admin, :id => users(:arthur).id assert_response :success assert !sites(:first).user(users(:arthur).id).site_admin? end def test_should_enable_site_admin sites(:first).user_with_deleted(3).update_attribute :deleted_at, nil login_as :quentin xhr :post, :admin, :id => users(:aaron).id assert_response :success assert sites(:first).user(users(:aaron).id).site_admin? end def test_should_disable_user login_as :quentin assert_no_difference User, :count_with_deleted do assert_difference User, :count, -1 do xhr :post, :destroy, :id => users(:quentin).id assert_response :success end end assert_equal users(:quentin), User.find_with_deleted(users(:quentin).id) end def test_should_enable_user login_as :quentin assert_no_difference User, :count_with_deleted do assert_difference User, :count do xhr :post, :enable, :id => 3 assert_response :success end end end end
{ "content_hash": "a3104fef106dbe7152aec6f6f0acc7f4", "timestamp": "", "source": "github", "line_count": 206, "max_line_length": 152, "avg_line_length": 36.08252427184466, "alnum_prop": 0.6541100497780169, "repo_name": "vaudoc/jk", "id": "2bf0a66f2ed9780568f8cb716b6a1a6100e61c99", "size": "7433", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/functional/admin/users_controller_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "41217" }, { "name": "Ruby", "bytes": "438076" } ], "symlink_target": "" }
package org.oep.ssomgt.action; public class UserSyncKeys { public class SearchAttributes extends BaseUserSyncAttributes { public static final String APPLICATION_ID = "searchApplicationId"; public static final String IS_SYNC = "searchIsSync"; public static final String USER_SEARCH = "userSearch"; } public class AddEditAttributes extends BaseUserSyncAttributes { public static final String SSO_USERNAME = "addEditSSOUserName"; public static final String EMAIL = "addEditEmail"; public static final String APPLICATION_ID = "addEditApplicationId"; public static final String APP_USERNAME = "addEditAppUserName"; public static final String EMPLOYEE_ID = "addEditEmployeeId"; } public class BaseUserSyncAttributes { public static final String DELETE_ID = "deleteAppRoleId"; public static final String EDIT_ID = "editAppRoleId"; } public class ErrorMessageKeys { } public class SuccessMessageKeys { } }
{ "content_hash": "06ac8d7705dff5933fcfe171ff38d65f", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 69, "avg_line_length": 32.3448275862069, "alnum_prop": 0.7750533049040512, "repo_name": "openegovplatform/OEPv2", "id": "474d68e4495a7222829872f19788c1011410df46", "size": "938", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "oep-ssomgt-portlet/docroot/WEB-INF/src/org/oep/ssomgt/action/UserSyncKeys.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5166" }, { "name": "Java", "bytes": "45541534" } ], "symlink_target": "" }
package com.cbh.mongo; import org.springframework.data.mongodb.core.mapping.Document; /** * Created by Tommy on 2017/5/8. */ @Document(collection="lineHospitalMessagesLog") public class LineHospitalMessage extends Message{ private String userLineId; public String getUserLineId() { return userLineId; } public void setUserLineId(String userLineId) { this.userLineId = userLineId; } }
{ "content_hash": "39966c0a1dd302ca5a0974c13ebc37fd", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 62, "avg_line_length": 21.35, "alnum_prop": 0.7166276346604216, "repo_name": "OpenHCOS/HCOS", "id": "855814fe447a2308a74eb53782a3e3d60e8fcfd0", "size": "427", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/ORS/cbh/src/main/java/com/cbh/mongo/LineHospitalMessage.java", "mode": "33188", "license": "mit", "language": [ { "name": "AspectJ", "bytes": "33035" }, { "name": "CSS", "bytes": "9019" }, { "name": "Java", "bytes": "94726" }, { "name": "Jupyter Notebook", "bytes": "256403" }, { "name": "Python", "bytes": "24136" } ], "symlink_target": "" }
package com.azure.resourcemanager.synapse.implementation; import com.azure.core.util.Context; import com.azure.resourcemanager.synapse.fluent.models.WorkloadGroupInner; import com.azure.resourcemanager.synapse.models.WorkloadGroup; public final class WorkloadGroupImpl implements WorkloadGroup, WorkloadGroup.Definition, WorkloadGroup.Update { private WorkloadGroupInner innerObject; private final com.azure.resourcemanager.synapse.SynapseManager serviceManager; public String id() { return this.innerModel().id(); } public String name() { return this.innerModel().name(); } public String type() { return this.innerModel().type(); } public int minResourcePercent() { return this.innerModel().minResourcePercent(); } public int maxResourcePercent() { return this.innerModel().maxResourcePercent(); } public double minResourcePercentPerRequest() { return this.innerModel().minResourcePercentPerRequest(); } public Double maxResourcePercentPerRequest() { return this.innerModel().maxResourcePercentPerRequest(); } public String importance() { return this.innerModel().importance(); } public Integer queryExecutionTimeout() { return this.innerModel().queryExecutionTimeout(); } public WorkloadGroupInner innerModel() { return this.innerObject; } private com.azure.resourcemanager.synapse.SynapseManager manager() { return this.serviceManager; } private String resourceGroupName; private String workspaceName; private String sqlPoolName; private String workloadGroupName; public WorkloadGroupImpl withExistingSqlPool(String resourceGroupName, String workspaceName, String sqlPoolName) { this.resourceGroupName = resourceGroupName; this.workspaceName = workspaceName; this.sqlPoolName = sqlPoolName; return this; } public WorkloadGroup create() { this.innerObject = serviceManager .serviceClient() .getSqlPoolWorkloadGroups() .createOrUpdate( resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, this.innerModel(), Context.NONE); return this; } public WorkloadGroup create(Context context) { this.innerObject = serviceManager .serviceClient() .getSqlPoolWorkloadGroups() .createOrUpdate( resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, this.innerModel(), context); return this; } WorkloadGroupImpl(String name, com.azure.resourcemanager.synapse.SynapseManager serviceManager) { this.innerObject = new WorkloadGroupInner(); this.serviceManager = serviceManager; this.workloadGroupName = name; } public WorkloadGroupImpl update() { return this; } public WorkloadGroup apply() { this.innerObject = serviceManager .serviceClient() .getSqlPoolWorkloadGroups() .createOrUpdate( resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, this.innerModel(), Context.NONE); return this; } public WorkloadGroup apply(Context context) { this.innerObject = serviceManager .serviceClient() .getSqlPoolWorkloadGroups() .createOrUpdate( resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, this.innerModel(), context); return this; } WorkloadGroupImpl(WorkloadGroupInner innerObject, com.azure.resourcemanager.synapse.SynapseManager serviceManager) { this.innerObject = innerObject; this.serviceManager = serviceManager; this.resourceGroupName = Utils.getValueFromIdByName(innerObject.id(), "resourceGroups"); this.workspaceName = Utils.getValueFromIdByName(innerObject.id(), "workspaces"); this.sqlPoolName = Utils.getValueFromIdByName(innerObject.id(), "sqlPools"); this.workloadGroupName = Utils.getValueFromIdByName(innerObject.id(), "workloadGroups"); } public WorkloadGroup refresh() { this.innerObject = serviceManager .serviceClient() .getSqlPoolWorkloadGroups() .getWithResponse(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, Context.NONE) .getValue(); return this; } public WorkloadGroup refresh(Context context) { this.innerObject = serviceManager .serviceClient() .getSqlPoolWorkloadGroups() .getWithResponse(resourceGroupName, workspaceName, sqlPoolName, workloadGroupName, context) .getValue(); return this; } public WorkloadGroupImpl withMinResourcePercent(int minResourcePercent) { this.innerModel().withMinResourcePercent(minResourcePercent); return this; } public WorkloadGroupImpl withMaxResourcePercent(int maxResourcePercent) { this.innerModel().withMaxResourcePercent(maxResourcePercent); return this; } public WorkloadGroupImpl withMinResourcePercentPerRequest(double minResourcePercentPerRequest) { this.innerModel().withMinResourcePercentPerRequest(minResourcePercentPerRequest); return this; } public WorkloadGroupImpl withMaxResourcePercentPerRequest(Double maxResourcePercentPerRequest) { this.innerModel().withMaxResourcePercentPerRequest(maxResourcePercentPerRequest); return this; } public WorkloadGroupImpl withImportance(String importance) { this.innerModel().withImportance(importance); return this; } public WorkloadGroupImpl withQueryExecutionTimeout(Integer queryExecutionTimeout) { this.innerModel().withQueryExecutionTimeout(queryExecutionTimeout); return this; } }
{ "content_hash": "1a23646993b3f85fe73baef3321fbb88", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 120, "avg_line_length": 34.03351955307262, "alnum_prop": 0.6759684832567301, "repo_name": "Azure/azure-sdk-for-java", "id": "99099f1b0766aedb5f04dec53b04257965f04cef", "size": "6249", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/synapse/azure-resourcemanager-synapse/src/main/java/com/azure/resourcemanager/synapse/implementation/WorkloadGroupImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8762" }, { "name": "Bicep", "bytes": "15055" }, { "name": "CSS", "bytes": "7676" }, { "name": "Dockerfile", "bytes": "2028" }, { "name": "Groovy", "bytes": "3237482" }, { "name": "HTML", "bytes": "42090" }, { "name": "Java", "bytes": "432409546" }, { "name": "JavaScript", "bytes": "36557" }, { "name": "Jupyter Notebook", "bytes": "95868" }, { "name": "PowerShell", "bytes": "737517" }, { "name": "Python", "bytes": "240542" }, { "name": "Scala", "bytes": "1143898" }, { "name": "Shell", "bytes": "18488" }, { "name": "XSLT", "bytes": "755" } ], "symlink_target": "" }
import Observable from './helpers/observable'; class HeaderView { constructor({ view, sortAscendingButton, sortDescendingButton, addCityButton }) { this.view = view; this.sortAscendingClicked = new Observable(); this.sortDescendingClicked = new Observable(); this.addCityClicked = new Observable(); sortAscendingButton.addEventListener('click', () => { this.sortAscendingClicked.notify(); }); sortDescendingButton.addEventListener('click', () => { this.sortDescendingClicked.notify(); }); addCityButton.addEventListener('click', () => { this.addCityClicked.notify(); }); } fix() { this.view.firstElementChild.classList.add('stuck'); } unfix() { this.view.firstElementChild.classList.remove('stuck'); } } export default HeaderView;
{ "content_hash": "ab986a40b2905f3745cc1bc97886ae32", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 83, "avg_line_length": 25.5, "alnum_prop": 0.6801470588235294, "repo_name": "jsperts/workshop_unterlagen", "id": "b6bcb149a81110afadda2b1cb203344e2e7b5ff1", "size": "816", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "performance/exercises/solution/src/app/header_view.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "135561" }, { "name": "HTML", "bytes": "263573" }, { "name": "JavaScript", "bytes": "698971" }, { "name": "TypeScript", "bytes": "463740" } ], "symlink_target": "" }
<?php if (!defined('_PS_VERSION_')) exit; class BlockFacebook extends Module { public function __construct() { $this->name = 'blockfacebook'; $this->tab = 'front_office_features'; $this->version = '1.3'; $this->author = 'PrestaShop'; $this->bootstrap = true; parent::__construct(); $this->displayName = $this->l('Facebook block'); $this->description = $this->l('Displays a block for subscribing to your Facebook page.'); $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_); } public function install() { return parent::install() && Configuration::updateValue('blockfacebook_url', 'https://www.facebook.com/prestashop') && $this->registerHook('displayHome') && $this->registerHook('displayHeader'); } public function uninstall() { // Delete configuration return Configuration::deleteByName('blockfacebook_url') && parent::uninstall(); } public function getContent() { $html = ''; // If we try to update the settings if (Tools::isSubmit('submitModule')) { Configuration::updateValue('blockfacebook_url', Tools::getValue('blockfacebook_url')); $html .= $this->displayConfirmation($this->l('Configuration updated')); $this->_clearCache('blockfacebook.tpl'); Tools::redirectAdmin('index.php?tab=AdminModules&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules')); } $html .= $this->renderForm(); $facebookurl = Configuration::get('blockfacebook_url'); if(!strstr($facebookurl, "facebook.com")) $facebookurl="https://www.facebook.com/".$facebookurl; $this->context->smarty->assign('facebookurl', $facebookurl); $this->context->smarty->assign('facebook_js_url', $this->_path.'blockfacebook.js'); $this->context->smarty->assign('facebook_css_url', $this->_path.'css/blockfacebook.css'); $html .= $this->context->smarty->fetch($this->local_path.'views/admin/_configure/preview.tpl'); return $html; } public function hookDisplayHome() { if (!$this->isCached('blockfacebook.tpl', $this->getCacheId())) { $facebookurl = Configuration::get('blockfacebook_url'); if (!strstr($facebookurl, 'facebook.com')) $facebookurl = 'https://www.facebook.com/'.$facebookurl; $this->context->smarty->assign('facebookurl', $facebookurl); } return $this->display(__FILE__, 'blockfacebook.tpl', $this->getCacheId()); } public function hookHeader() { $this->page_name = Dispatcher::getInstance()->getController(); if ($this->page_name == 'index') { $this->context->controller->addCss(($this->_path).'css/blockfacebook.css'); $this->context->controller->addJS(($this->_path).'blockfacebook.js'); } } public function renderForm() { $fields_form = array( 'form' => array( 'legend' => array( 'title' => $this->l('Settings'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'text', 'label' => $this->l('Facebook link (full URL is required)'), 'name' => 'blockfacebook_url', ), ), 'submit' => array( 'title' => $this->l('Save') ) ), ); $helper = new HelperForm(); $helper->show_toolbar = false; $helper->table = $this->table; $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT')); $helper->default_form_language = $lang->id; $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0; $this->fields_form = array(); $helper->identifier = $this->identifier; $helper->submit_action = 'submitModule'; $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->tpl_vars = array( 'fields_value' => $this->getConfigFieldsValues(), 'languages' => $this->context->controller->getLanguages(), 'id_language' => $this->context->language->id ); return $helper->generateForm(array($fields_form)); } public function getConfigFieldsValues() { return array( 'blockfacebook_url' => Tools::getValue('blockfacebook_url', Configuration::get('blockfacebook_url')), ); } }
{ "content_hash": "9ffdbc95d5705fe685bb519e0f18cf71", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 164, "avg_line_length": 32.4, "alnum_prop": 0.6547958214624882, "repo_name": "tuyto/715_ps_temp", "id": "161601cf73aa43a369c16841cf30e4146bb9b54e", "size": "5180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/blockfacebook/blockfacebook.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7372586" }, { "name": "JavaScript", "bytes": "1633339" }, { "name": "PHP", "bytes": "8679861" }, { "name": "Ruby", "bytes": "1150" } ], "symlink_target": "" }
Simple and responsive website for remote work in Japan in Japanese and English. # Install & Run 1. Git clone repo 2. ``` cd docs bundle install bundle exec jekyll serve ``` ## Languages - Japanese - English ## Categories 1. Fully remote jobs: `full_remote` 2. Japanese required remote jobs: `ja_required` ## Contribute to translation Adding missing Japanese translation is much appreciated. - In file `/_data/translations.yml` - Add to the translation key the missing translation in `ja` ## License The theme is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
{ "content_hash": "ccebebf5676ae35efa81082c8fa6e0a0", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 112, "avg_line_length": 20.483870967741936, "alnum_prop": 0.7338582677165354, "repo_name": "uiureo/remote-in-japan", "id": "bbe5ae3147230032c43348480531830b4db38fe9", "size": "652", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/DEVELOPMENT.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.ofbiz.webapp.renderer; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.RandomStringUtils; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.webapp.renderer.RenderTargetExpr.MultiRenderTargetExpr; import org.ofbiz.webapp.renderer.RenderWriter.SwitchRenderWriter; /** * Targeted rendering util. * <p> * FIXME?: The main RenderTargetExpr class is currently under widget package, so we can't * access it from here. */ public abstract class RenderTargetUtil { private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass()); public static final String RENDERTARGETEXPR_REQPARAM = "scpRenderTargetExpr"; public static final String ERRORRENDERTARGETEXPR_REQPARAM = "scpErrorRenderTargetExpr"; public static final String LOGINRENDERTARGETEXPR_REQPARAM = "scpLoginRenderTargetExpr"; public static final Set<String> RENDERTARGET_REQPARAM_ALL = UtilMisc.unmodifiableHashSet(RENDERTARGETEXPR_REQPARAM, ERRORRENDERTARGETEXPR_REQPARAM, LOGINRENDERTARGETEXPR_REQPARAM); public static final String RENDERTARGETSTATE_ATTR = "scpRenderTargetState"; public static final String RENDERTARGETON_ATTR = "scpRenderTargetOn"; public static final boolean DEBUG = false || Debug.verboseOn(); /** * for an expr in the format: * "+multi:somename:$My-Section, */ public static final String RENDERTARGETEXPR_RAW_MULTI_PREFIX = "+multi:"; public static final String RENDERTARGETEXPR_RAW_EMPTY = ""; public static final String RENDERTARGETEXPR_MULTI_DEFAULT = "_default_"; /** * SPECIAL DELIMITER attribute name for non-optimized multi targeting support. * It consists of: * prefix + random chars + name + name-terminator + open-/close-flag * The random chars are to prevent clashes with page content; this could theoretically * still happen but the odds are statistically extremely small. Nevertheless this remains * the most reliable way to extract sections using the current ofbiz code. */ public static final String MULTITARGET_DELIM_PREFIX_ATTR = "scpRenderTargetDelim"; public static final String MULTITARGET_DELIM_PREFIX = "!%#@%#@!@#"; public static final int MULTITARGET_DELIM_RANDOM_SIZE = 8; public static final String MULTITARGET_DELIM_NAMESUFFIX = ";"; public static final char MULTITARGET_DELIM_OPEN_CHAR = '^'; public static final String MULTITARGET_DELIM_OPEN = String.valueOf(MULTITARGET_DELIM_OPEN_CHAR); public static final char MULTITARGET_DELIM_CLOSE_CHAR = '$'; public static final String MULTITARGET_DELIM_CLOSE = String.valueOf(MULTITARGET_DELIM_CLOSE_CHAR); protected RenderTargetUtil() { } public static Object getRawRenderTargetExpr(HttpServletRequest request, String paramName) { Object scpRenderTargetExpr = request.getAttribute(paramName); if (scpRenderTargetExpr != null) return scpRenderTargetExpr; else return request.getParameter(paramName); } // now taken care of in WidgetMultiRenderTargetExpr, so that it's faster and cacheable // public static Map<String, Object> splitMultiExprToMap(String expr) { // Map<String, Object> exprMap = new HashMap<>(); // String[] pairs = StringUtils.split(expr, ","); // for(String pair : pairs) { // String[] parts = StringUtils.split(pair, ":", 2); // if (parts.length != 2) throw new IllegalArgumentException("targeted rendering multi expression is invalid: " + expr); // String name = parts[0].trim(); // String strExpr = parts[1].trim(); // if (name.isEmpty() || strExpr.isEmpty()) throw new IllegalArgumentException("targeted rendering multi expression is invalid: " + expr); // exprMap.put(name, strExpr); // } // return exprMap; // } public static Object getRawRenderTargetExpr(HttpServletRequest request) { return getRawRenderTargetExpr(request, RENDERTARGETEXPR_REQPARAM); } public static void setRawRenderTargetExpr(HttpServletRequest request, String paramName, Object expr) { request.setAttribute(paramName, expr); } public static void setRawRenderTargetExpr(HttpServletRequest request, Object expr) { setRawRenderTargetExpr(request, RENDERTARGETEXPR_REQPARAM, expr); } /** * This caches the result of the first get so next fetch doesn't re-preprocess it. */ public static Object getSetRawRenderTargetExpr(HttpServletRequest request) { Object expr = getRawRenderTargetExpr(request); setRawRenderTargetExpr(request, expr != null ? expr : RENDERTARGETEXPR_RAW_EMPTY); return expr; } /** * FIXME?: this is an approximation because we don't have the state yet from where this is called. */ public static boolean isRenderTargetExprOn(HttpServletRequest request, Object expr) { return (expr != null) && !(expr instanceof String && ((String) expr).isEmpty()); } public static boolean isRenderTargetExprMulti(Object expr) { return (expr instanceof MultiRenderTargetExpr || expr instanceof Map || (expr instanceof String && ((String) expr).startsWith(RENDERTARGETEXPR_RAW_MULTI_PREFIX))); } public static String generateMultiTargetDelimiterPrefix(HttpServletRequest request) { return MULTITARGET_DELIM_PREFIX + RandomStringUtils.randomAlphanumeric(MULTITARGET_DELIM_RANDOM_SIZE); } public static String generateSetMultiTargetDelimiterPrefix(HttpServletRequest request) { String prefix = generateMultiTargetDelimiterPrefix(request); request.setAttribute(MULTITARGET_DELIM_PREFIX_ATTR, prefix); return prefix; } public static String getOrGenerateMultiTargetDelimiterPrefix(HttpServletRequest request) { String prefix = (String) request.getAttribute(MULTITARGET_DELIM_PREFIX_ATTR); if (prefix == null || prefix.isEmpty()) { prefix = generateMultiTargetDelimiterPrefix(request); } return prefix; } public static String getOrGenerateSetMultiTargetDelimiterPrefix(HttpServletRequest request) { String prefix = (String) request.getAttribute(MULTITARGET_DELIM_PREFIX_ATTR); if (prefix == null || prefix.isEmpty()) { prefix = generateSetMultiTargetDelimiterPrefix(request); } return prefix; } public static void makeMultiTargetDelimOpen(Appendable out, String name, String prefix) throws IOException { out.append(prefix); out.append(name); out.append(MULTITARGET_DELIM_NAMESUFFIX); out.append(MULTITARGET_DELIM_OPEN); } public static void makeMultiTargetDelimClose(Appendable out, String name, String prefix) throws IOException { out.append(prefix); out.append(name); out.append(MULTITARGET_DELIM_NAMESUFFIX); out.append(MULTITARGET_DELIM_CLOSE); } public static Map<String, Object> extractMultiTargetOutputs(Appendable out, String prefix) { if (out instanceof SwitchRenderWriter) { // TODO: NOT IMPLEMENTED: fast mode not yet implemented because it is more likely to fail. //Map<String, Object> map = new HashMap<>(); throw new UnsupportedOperationException("SwitchRenderWriter fast extract not yet implemented"); } else if (out instanceof StringWriter) { return extractMultiTargetOutputsTextual(((StringWriter) out).getBuffer(), prefix); } else { throw new UnsupportedOperationException(); } } /** * DIRTY TEXT EXTRACTION - slow and memory hog, but only method guaranteed success */ public static Map<String, Object> extractMultiTargetOutputsTextual(StringBuffer sb, String prefix) { Map<String, Object> map = new HashMap<>(); int prefixLength = prefix.length(); //if (DEBUG) { // Debug.logInfo("FULL OUTPUT: " + sb.toString(), module); //} Set<String> nameStack = new LinkedHashSet<>(); // NOTE: this may have more than one at a time due to nesting int delimIndex; int lastPostDelimIndex = 0; int searchIndex = 0; while(searchIndex < sb.length() && ((delimIndex = sb.indexOf(prefix, searchIndex)) >= 0)) { final int nameIndex = delimIndex + prefixLength; int nameSuffixIndex = sb.indexOf(MULTITARGET_DELIM_NAMESUFFIX, nameIndex); if (nameSuffixIndex < 0) { Debug.logWarning("invalid targeted rendering output: delimiter is missing name (this is probably an error, but not guaranteed)", module); searchIndex = nameIndex; continue; } String name = sb.substring(nameIndex, nameSuffixIndex); if (name.isEmpty()) { Debug.logWarning("invalid targeted rendering output: delimiter name empty (this is probably an error, but not guaranteed)", module); searchIndex = nameIndex; continue; } int lastCharIndex = nameSuffixIndex + MULTITARGET_DELIM_NAMESUFFIX.length(); if (lastCharIndex >= sb.length()) { Debug.logWarning("invalid targeted rendering output: unexpected end of buffer (missing delimiter open/close symbol) (this is probably an error, but not guaranteed)", module); searchIndex = nameSuffixIndex; continue; } char openCloseChar = sb.charAt(lastCharIndex); int postDelimIndex = lastCharIndex + 1; String prevTextPart = sb.substring(lastPostDelimIndex, delimIndex); if (openCloseChar == MULTITARGET_DELIM_OPEN_CHAR) { for(String prevName : nameStack) { ((StringBuilder) map.get(prevName)).append(prevTextPart); } map.put(name, new StringBuilder()); nameStack.add(name); } else if (openCloseChar == MULTITARGET_DELIM_CLOSE_CHAR) { for(String prevName : nameStack) { ((StringBuilder) map.get(prevName)).append(prevTextPart); } nameStack.remove(name); // if (DEBUG) { // Debug.logInfo("TEXT PART: " + prevTextPart, module); // } } else { Debug.logWarning("invalid targeted rendering output: unrecognized open/close symbol (this is probably an error, but not guaranteed)", module); searchIndex = lastCharIndex; continue; } searchIndex = postDelimIndex; lastPostDelimIndex = postDelimIndex; } if (lastPostDelimIndex < sb.length()) { String prevTextPart = sb.substring(lastPostDelimIndex); for(String prevName : nameStack) { ((StringBuilder) map.get(prevName)).append(prevTextPart); } } // TODO: check if this works // for(Map.Entry<String, Object> entry : map.entrySet()) { // entry.setValue(entry.getValue().toString()); // } return map; } }
{ "content_hash": "86b0a26f5a1fa16b9ddb001303c0d519", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 190, "avg_line_length": 46.108870967741936, "alnum_prop": 0.6694359422824662, "repo_name": "ilscipio/scipio-erp", "id": "6daf46fd031fd299a41609c10639beb7ff3209c6", "size": "11435", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "framework/webapp/src/org/ofbiz/webapp/renderer/RenderTargetUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "15540" }, { "name": "CSS", "bytes": "533213" }, { "name": "FreeMarker", "bytes": "6482124" }, { "name": "Groovy", "bytes": "2254105" }, { "name": "HTML", "bytes": "4409922" }, { "name": "Java", "bytes": "23079876" }, { "name": "JavaScript", "bytes": "1106310" }, { "name": "Ruby", "bytes": "2377" }, { "name": "SCSS", "bytes": "514759" }, { "name": "Shell", "bytes": "66335" }, { "name": "XSLT", "bytes": "1712" } ], "symlink_target": "" }
class AddDestroyedAtToAlerts < ActiveRecord::Migration def change add_column :alerts, :destroyed_at, :timestamp, null: true end end
{ "content_hash": "1109f929826af7100069f3b83841ac97", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 61, "avg_line_length": 28, "alnum_prop": 0.7571428571428571, "repo_name": "houston/houston-alerts", "id": "66e0e47a9ca26a3324da0cb868ae0beff86a43a5", "size": "140", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "db/migrate/20140907005810_add_destroyed_at_to_alerts.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6335" }, { "name": "CoffeeScript", "bytes": "2362" }, { "name": "HTML", "bytes": "12247" }, { "name": "JavaScript", "bytes": "1498" }, { "name": "Ruby", "bytes": "37196" } ], "symlink_target": "" }
typedef void (^gouwucheBlock)(NSInteger index);//定义block @interface ClassCustomTableViewCell : UITableViewCell @property(nonatomic,copy)gouwucheBlock gouwucheBlock; @property(nonatomic,strong)NSString *type; -(CGFloat)loadCustomViewWithModel:(ProductModel*)model index:(NSIndexPath*)theIndexPath; -(void)setGouwucheBlock:(gouwucheBlock)gouwucheBlock; @end
{ "content_hash": "c92f2aa22c969e7825c51089acf94ee0", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 88, "avg_line_length": 21.529411764705884, "alnum_prop": 0.8169398907103825, "repo_name": "TeamOfFBAuto/WJXC", "id": "84fff110e2085f01a2c6834e17ead0fc4092e0f4", "size": "588", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "WJXC/WJXC/CommonViews/分类/ClassCustomTableViewCell.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5331" }, { "name": "C++", "bytes": "864" }, { "name": "HTML", "bytes": "9110" }, { "name": "Objective-C", "bytes": "3215562" }, { "name": "Objective-C++", "bytes": "30581" }, { "name": "Ruby", "bytes": "362" }, { "name": "Shell", "bytes": "15327" } ], "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 WpfMovieSystem.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
{ "content_hash": "965ffa9988281ddd60220189ef068c34", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 151, "avg_line_length": 35.63333333333333, "alnum_prop": 0.5827876520112254, "repo_name": "Brevering/Databases_2017_Teamwork", "id": "bb3a6965259d326b6b6f3008b59f5f129a85f030", "size": "1071", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MoviesSystem/WpfMovieSystem/Properties/Settings.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "77937" } ], "symlink_target": "" }
import {docsUrl} from "gen/gocd_version"; import _ from "lodash"; import m from "mithril"; import {TemplateSummary} from "models/admin_templates/templates"; import {PipelineStructure} from "models/internal_pipeline_structure/pipeline_structure"; import {ScrollManager} from "views/components/anchor/anchor"; import {stubAllMethods, TestHelper} from "views/pages/spec/test_helper"; import {AdminTemplatesWidget} from "../admin_templates_widget"; describe('AdminTemplatesSpecs', () => { const helper = new TestHelper(); afterEach((done) => helper.unmount(done)); it('should render info message when no templates are passed', () => { mount([]); const infoMsgElement = helper.byTestId("no-template-present-msg"); expect(infoMsgElement).toBeInDOM(); expect(infoMsgElement.innerText).toBe("Either no templates have been set up or you are not authorized to view the same. Learn More"); expect(helper.q("a", infoMsgElement)).toBeInDOM(); expect(helper.q("a", infoMsgElement).getAttribute("href")).toBe(docsUrl("configuration/pipeline_templates.html")); }); it('should render error msg if the element specified in scroll manager does not exist', () => { let sm: ScrollManager; sm = { hasTarget: jasmine.createSpy().and.callFake(() => true), getTarget: jasmine.createSpy().and.callFake(() => "template1"), shouldScroll: jasmine.createSpy(), setTarget: jasmine.createSpy(), scrollToEl: jasmine.createSpy() }; mount([], sm); const errorMsgElement = helper.byTestId("anchor-template-not-present"); expect(errorMsgElement).toBeInDOM(); expect(errorMsgElement.innerText).toBe("Either 'template1' template has not been set up or you are not authorized to view the same. Learn More"); expect(helper.q("a", errorMsgElement)).toBeInDOM(); expect(helper.q("a", errorMsgElement).getAttribute("href")).toBe(docsUrl("configuration/pipeline_templates.html")); }); function mount(templates: TemplateSummary.TemplateSummaryTemplate[], sm: ScrollManager = stubAllMethods(["hasTarget"])) { const pipelineStructure = new PipelineStructure([], []); const editSpy = jasmine.createSpy("edit_pipeline"); const scrollOpts = { sm, shouldOpenReadOnlyView: false }; helper.mount(() => <AdminTemplatesWidget doEditPipeline={editSpy} doShowTemplate={_.noop} templates={templates} pipelineStructure={pipelineStructure} editPermissions={_.noop} onSuccessfulSave={_.noop} onEdit={_.noop} onDelete={_.noop} onError={_.noop} onCreate={_.noop} scrollOptions={scrollOpts}/>); } });
{ "content_hash": "992c82d603aa7c96a5bd065b24717a02", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 149, "avg_line_length": 45.73134328358209, "alnum_prop": 0.6024804177545692, "repo_name": "marques-work/gocd", "id": "916cef161924cc25a9e3c1ffe8123bbcc92cda92", "size": "3665", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/src/main/webapp/WEB-INF/rails/webpack/views/pages/admin_templates/specs/admin_templates_widget_spec.tsx", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "466" }, { "name": "CSS", "bytes": "807605" }, { "name": "FreeMarker", "bytes": "9759" }, { "name": "Groovy", "bytes": "2317159" }, { "name": "HTML", "bytes": "641338" }, { "name": "Java", "bytes": "21014983" }, { "name": "JavaScript", "bytes": "2539248" }, { "name": "NSIS", "bytes": "23525" }, { "name": "PowerShell", "bytes": "691" }, { "name": "Ruby", "bytes": "1907011" }, { "name": "Shell", "bytes": "169586" }, { "name": "TSQL", "bytes": "200114" }, { "name": "TypeScript", "bytes": "3423163" }, { "name": "XSLT", "bytes": "203240" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Ploeh.Samples.Commerce.Domain; namespace Ploeh.Samples.CommerceService { public interface IContractMapper { MoneyContract Map(Money money); Money Map(MoneyContract moneyContract); ProductContract Map(Product product); IEnumerable<ProductContract> Map(IEnumerable<Product> products); Product Map(ProductContract productContract); } }
{ "content_hash": "4a3b8bcd65f5064531d33641fa3bd786", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 72, "avg_line_length": 23, "alnum_prop": 0.7329192546583851, "repo_name": "owolp/Telerik-Academy", "id": "8b2cded82650d4990665333ec5db4277bda73b3a", "size": "485", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Module-2/Design-Patterns/Materials/DI.NET/ComplexCommerce/CommerceService/IContractMapper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "41735" }, { "name": "Batchfile", "bytes": "260" }, { "name": "C", "bytes": "1487" }, { "name": "C#", "bytes": "4599043" }, { "name": "CSS", "bytes": "160410" }, { "name": "CoffeeScript", "bytes": "3700" }, { "name": "HTML", "bytes": "2086891" }, { "name": "JavaScript", "bytes": "2891383" }, { "name": "PowerShell", "bytes": "287" }, { "name": "XSLT", "bytes": "2499" } ], "symlink_target": "" }
package org.apache.rya.indexing.pcj.storage.accumulo; import static org.junit.Assert.assertEquals; import org.apache.rya.indexing.pcj.storage.accumulo.AccumuloPcjSerializer; import org.apache.rya.indexing.pcj.storage.accumulo.BindingSetConverter; import org.apache.rya.indexing.pcj.storage.accumulo.BindingSetConverter.BindingSetConversionException; import org.apache.rya.indexing.pcj.storage.accumulo.VariableOrder; import org.junit.Test; import org.openrdf.model.impl.LiteralImpl; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.BindingSet; import org.openrdf.query.algebra.evaluation.QueryBindingSet; import org.openrdf.query.impl.MapBindingSet; import mvm.rya.api.resolver.RyaTypeResolverException; /** * Tests the methods of {@link AccumuloPcjSerialzer}. */ public class AccumuloPcjSerialzerTest { /** * The BindingSet has fewer Bindings than there are variables in the variable * order, but they are all in the variable order. This is the case where * the missing bindings were optional. */ @Test public void serialize_bindingsSubsetOfVarOrder() throws BindingSetConversionException { // Setup the Binding Set. final MapBindingSet originalBindingSet = new MapBindingSet(); originalBindingSet.addBinding("x", new URIImpl("http://a")); originalBindingSet.addBinding("y", new URIImpl("http://b")); // Setup the variable order. final VariableOrder varOrder = new VariableOrder("x", "a", "y", "b"); // Create the byte[] representation of the BindingSet. BindingSetConverter<byte[]> converter = new AccumuloPcjSerializer(); byte[] serialized = converter.convert(originalBindingSet, varOrder); // Deserialize the byte[] back into the binding set. BindingSet deserialized = converter.convert(serialized, varOrder); // Ensure the deserialized value matches the original. assertEquals(originalBindingSet, deserialized); } /** * The BindingSet has a Binding whose name is not in the variable order. * This is illegal. */ @Test(expected = IllegalArgumentException.class) public void serialize_bindingNotInVariableOrder() throws RyaTypeResolverException, BindingSetConversionException { // Setup the Binding Set. final MapBindingSet originalBindingSet = new MapBindingSet(); originalBindingSet.addBinding("x", new URIImpl("http://a")); originalBindingSet.addBinding("y", new URIImpl("http://b")); originalBindingSet.addBinding("z", new URIImpl("http://d")); // Setup the variable order. final VariableOrder varOrder = new VariableOrder("x", "y"); // Create the byte[] representation of the BindingSet. This will throw an exception. BindingSetConverter<byte[]> converter = new AccumuloPcjSerializer(); converter.convert(originalBindingSet, varOrder); } @Test public void basicShortUriBsTest() throws BindingSetConversionException { final QueryBindingSet bs = new QueryBindingSet(); bs.addBinding("X",new URIImpl("http://uri1")); bs.addBinding("Y",new URIImpl("http://uri2")); final VariableOrder varOrder = new VariableOrder("X","Y"); BindingSetConverter<byte[]> converter = new AccumuloPcjSerializer(); final byte[] byteVal = converter.convert(bs, varOrder); final BindingSet newBs = converter.convert(byteVal, varOrder); assertEquals(bs, newBs); } @Test public void basicLongUriBsTest() throws BindingSetConversionException { final QueryBindingSet bs = new QueryBindingSet(); bs.addBinding("X",new URIImpl("http://uri1")); bs.addBinding("Y",new URIImpl("http://uri2")); bs.addBinding("Z",new URIImpl("http://uri3")); bs.addBinding("A",new URIImpl("http://uri4")); bs.addBinding("B",new URIImpl("http://uri5")); final VariableOrder varOrder = new VariableOrder("X","Y","Z","A","B"); BindingSetConverter<byte[]> converter = new AccumuloPcjSerializer(); final byte[] byteVal = converter.convert(bs, varOrder); final BindingSet newBs = converter.convert(byteVal, varOrder); assertEquals(bs, newBs); } @Test public void basicShortStringLiteralBsTest() throws BindingSetConversionException { final QueryBindingSet bs = new QueryBindingSet(); bs.addBinding("X",new LiteralImpl("literal1")); bs.addBinding("Y",new LiteralImpl("literal2")); final VariableOrder varOrder = new VariableOrder("X","Y"); BindingSetConverter<byte[]> converter = new AccumuloPcjSerializer(); final byte[] byteVal = converter.convert(bs, varOrder); final BindingSet newBs = converter.convert(byteVal, varOrder); assertEquals(bs, newBs); } @Test public void basicShortMixLiteralBsTest() throws BindingSetConversionException { final QueryBindingSet bs = new QueryBindingSet(); bs.addBinding("X",new LiteralImpl("literal1")); bs.addBinding("Y",new LiteralImpl("5", new URIImpl("http://www.w3.org/2001/XMLSchema#integer"))); final VariableOrder varOrder = new VariableOrder("X","Y"); BindingSetConverter<byte[]> converter = new AccumuloPcjSerializer(); final byte[] byteVal = converter.convert(bs, varOrder); final BindingSet newBs = converter.convert(byteVal, varOrder); assertEquals(bs, newBs); } @Test public void basicLongMixLiteralBsTest() throws BindingSetConversionException { final QueryBindingSet bs = new QueryBindingSet(); bs.addBinding("X",new LiteralImpl("literal1")); bs.addBinding("Y",new LiteralImpl("5", new URIImpl("http://www.w3.org/2001/XMLSchema#integer"))); bs.addBinding("Z",new LiteralImpl("5.0", new URIImpl("http://www.w3.org/2001/XMLSchema#double"))); bs.addBinding("W",new LiteralImpl("1000", new URIImpl("http://www.w3.org/2001/XMLSchema#long"))); final VariableOrder varOrder = new VariableOrder("W","X","Y","Z"); BindingSetConverter<byte[]> converter = new AccumuloPcjSerializer(); final byte[] byteVal = converter.convert(bs, varOrder); final BindingSet newBs = converter.convert(byteVal, varOrder); assertEquals(bs, newBs); } @Test public void basicMixUriLiteralBsTest() throws BindingSetConversionException { final QueryBindingSet bs = new QueryBindingSet(); bs.addBinding("X",new LiteralImpl("literal1")); bs.addBinding("Y",new LiteralImpl("5", new URIImpl("http://www.w3.org/2001/XMLSchema#integer"))); bs.addBinding("Z",new LiteralImpl("5.0", new URIImpl("http://www.w3.org/2001/XMLSchema#double"))); bs.addBinding("W",new LiteralImpl("1000", new URIImpl("http://www.w3.org/2001/XMLSchema#long"))); bs.addBinding("A",new URIImpl("http://uri1")); bs.addBinding("B",new URIImpl("http://uri2")); bs.addBinding("C",new URIImpl("http://uri3")); final VariableOrder varOrder = new VariableOrder("A","W","X","Y","Z","B","C"); BindingSetConverter<byte[]> converter = new AccumuloPcjSerializer(); final byte[] byteVal = converter.convert(bs, varOrder); final BindingSet newBs = converter.convert(byteVal, varOrder); assertEquals(bs, newBs); } }
{ "content_hash": "6c5876f698c4f7418725c60af55b70cf", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 118, "avg_line_length": 44.037974683544306, "alnum_prop": 0.7266455878125898, "repo_name": "isper3at/incubator-rya", "id": "5011adf15eddb742d616d7c096dea111dd96660c", "size": "7765", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "extras/rya.indexing.pcj/src/test/java/org/apache/rya/indexing/pcj/storage/accumulo/AccumuloPcjSerialzerTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5766" }, { "name": "FreeMarker", "bytes": "755" }, { "name": "Groovy", "bytes": "98213" }, { "name": "Java", "bytes": "5364235" }, { "name": "JavaScript", "bytes": "1059" }, { "name": "Ruby", "bytes": "17096" }, { "name": "Shell", "bytes": "4050" }, { "name": "Web Ontology Language", "bytes": "13774" }, { "name": "XSLT", "bytes": "7341" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/texttospeech/v1beta1/cloud_tts.proto package com.google.cloud.texttospeech.v1beta1; public interface AudioConfigOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.texttospeech.v1beta1.AudioConfig) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. The format of the audio byte stream. * </pre> * * <code> * .google.cloud.texttospeech.v1beta1.AudioEncoding audio_encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for audioEncoding. */ int getAudioEncodingValue(); /** * * * <pre> * Required. The format of the audio byte stream. * </pre> * * <code> * .google.cloud.texttospeech.v1beta1.AudioEncoding audio_encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The audioEncoding. */ com.google.cloud.texttospeech.v1beta1.AudioEncoding getAudioEncoding(); /** * * * <pre> * Optional. Input only. Speaking rate/speed, in the range [0.25, 4.0]. 1.0 is * the normal native speed supported by the specific voice. 2.0 is twice as * fast, and 0.5 is half as fast. If unset(0.0), defaults to the native 1.0 * speed. Any other values &lt; 0.25 or &gt; 4.0 will return an error. * </pre> * * <code> * double speaking_rate = 2 [(.google.api.field_behavior) = INPUT_ONLY, (.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The speakingRate. */ double getSpeakingRate(); /** * * * <pre> * Optional. Input only. Speaking pitch, in the range [-20.0, 20.0]. 20 means * increase 20 semitones from the original pitch. -20 means decrease 20 * semitones from the original pitch. * </pre> * * <code> * double pitch = 3 [(.google.api.field_behavior) = INPUT_ONLY, (.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The pitch. */ double getPitch(); /** * * * <pre> * Optional. Input only. Volume gain (in dB) of the normal native volume * supported by the specific voice, in the range [-96.0, 16.0]. If unset, or * set to a value of 0.0 (dB), will play at normal native signal amplitude. A * value of -6.0 (dB) will play at approximately half the amplitude of the * normal native signal amplitude. A value of +6.0 (dB) will play at * approximately twice the amplitude of the normal native signal amplitude. * Strongly recommend not to exceed +10 (dB) as there's usually no effective * increase in loudness for any value greater than that. * </pre> * * <code> * double volume_gain_db = 4 [(.google.api.field_behavior) = INPUT_ONLY, (.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The volumeGainDb. */ double getVolumeGainDb(); /** * * * <pre> * Optional. The synthesis sample rate (in hertz) for this audio. When this is * specified in SynthesizeSpeechRequest, if this is different from the voice's * natural sample rate, then the synthesizer will honor this request by * converting to the desired sample rate (which might result in worse audio * quality), unless the specified sample rate is not supported for the * encoding chosen, in which case it will fail the request and return * [google.rpc.Code.INVALID_ARGUMENT][]. * </pre> * * <code>int32 sample_rate_hertz = 5 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The sampleRateHertz. */ int getSampleRateHertz(); /** * * * <pre> * Optional. Input only. An identifier which selects 'audio effects' profiles * that are applied on (post synthesized) text to speech. Effects are applied * on top of each other in the order they are given. See * [audio * profiles](https://cloud.google.com/text-to-speech/docs/audio-profiles) for * current supported profile ids. * </pre> * * <code> * repeated string effects_profile_id = 6 [(.google.api.field_behavior) = INPUT_ONLY, (.google.api.field_behavior) = OPTIONAL]; * </code> * * @return A list containing the effectsProfileId. */ java.util.List<java.lang.String> getEffectsProfileIdList(); /** * * * <pre> * Optional. Input only. An identifier which selects 'audio effects' profiles * that are applied on (post synthesized) text to speech. Effects are applied * on top of each other in the order they are given. See * [audio * profiles](https://cloud.google.com/text-to-speech/docs/audio-profiles) for * current supported profile ids. * </pre> * * <code> * repeated string effects_profile_id = 6 [(.google.api.field_behavior) = INPUT_ONLY, (.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The count of effectsProfileId. */ int getEffectsProfileIdCount(); /** * * * <pre> * Optional. Input only. An identifier which selects 'audio effects' profiles * that are applied on (post synthesized) text to speech. Effects are applied * on top of each other in the order they are given. See * [audio * profiles](https://cloud.google.com/text-to-speech/docs/audio-profiles) for * current supported profile ids. * </pre> * * <code> * repeated string effects_profile_id = 6 [(.google.api.field_behavior) = INPUT_ONLY, (.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index of the element to return. * @return The effectsProfileId at the given index. */ java.lang.String getEffectsProfileId(int index); /** * * * <pre> * Optional. Input only. An identifier which selects 'audio effects' profiles * that are applied on (post synthesized) text to speech. Effects are applied * on top of each other in the order they are given. See * [audio * profiles](https://cloud.google.com/text-to-speech/docs/audio-profiles) for * current supported profile ids. * </pre> * * <code> * repeated string effects_profile_id = 6 [(.google.api.field_behavior) = INPUT_ONLY, (.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index of the value to return. * @return The bytes of the effectsProfileId at the given index. */ com.google.protobuf.ByteString getEffectsProfileIdBytes(int index); }
{ "content_hash": "a4c81a01e6a5b4cd744e5d378ad7a6bd", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 129, "avg_line_length": 32.77948717948718, "alnum_prop": 0.659261576971214, "repo_name": "googleapis/java-texttospeech", "id": "3825c9ff6646a5713a57c8c8b87e57c4f7f56cae", "size": "6986", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "proto-google-cloud-texttospeech-v1beta1/src/main/java/com/google/cloud/texttospeech/v1beta1/AudioConfigOrBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "801" }, { "name": "Java", "bytes": "1032682" }, { "name": "Python", "bytes": "788" }, { "name": "Shell", "bytes": "22872" } ], "symlink_target": "" }
BASE_DIR=`dirname $0` echo "" echo "Starting Karma Server (http://karma-runner.github.io)" echo "-------------------------------------------------------------------" karma start $BASE_DIR/../config/karma.conf.js $* echo "" echo "Running jasmine-node (https://github.com/mhevery/jasmine-node)" echo "-------------------------------------------------------------------" jasmine-node $BASE_DIR/.. --matchall --verbose $* echo "" echo "Running JSHint (http://www.jshint.com/)" echo "-------------------------------------------------------------------" jshint $BASE_DIR/../*.js $*
{ "content_hash": "839c3289d802eab06d6a534aa97f1597", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 74, "avg_line_length": 30.57894736842105, "alnum_prop": 0.43717728055077454, "repo_name": "simoneb/ja.di", "id": "431aeb0d896d6954744f3b9ce02e64301efc69b8", "size": "594", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/humans-run-this.sh", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "18271" }, { "name": "Shell", "bytes": "670" } ], "symlink_target": "" }
/* Without this pragma, gcc 4.7.0 20111124 mistakenly suggests that the proper_name function might be candidate for attribute 'const' */ #if (__GNUC__ == 4 && 6 <= __GNUC_MINOR__) || 4 < __GNUC__ # pragma GCC diagnostic ignored "-Wsuggest-attribute=const" #endif #include <config.h> /* Specification. */ #include "propername.h" #include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if HAVE_ICONV # include <iconv.h> #endif #include "trim.h" #include "mbchar.h" #include "mbuiter.h" #include "localcharset.h" #include "c-strcase.h" #include "xstriconv.h" #include "xalloc.h" #include "gettext.h" /* Tests whether STRING contains trim (SUB), starting and ending at word boundaries. Here, instead of implementing Unicode Standard Annex #29 for determining word boundaries, we assume that trim (SUB) starts and ends with words and only test whether the part before it ends with a non-word and the part after it starts with a non-word. */ static bool mbsstr_trimmed_wordbounded (const char *string, const char *sub) { char *tsub = trim (sub); bool found = false; for (; *string != '\0';) { const char *tsub_in_string = mbsstr (string, tsub); if (tsub_in_string == NULL) break; else { if (MB_CUR_MAX > 1) { mbui_iterator_t string_iter; bool word_boundary_before; bool word_boundary_after; mbui_init (string_iter, string); word_boundary_before = true; if (mbui_cur_ptr (string_iter) < tsub_in_string) { mbchar_t last_char_before_tsub; do { if (!mbui_avail (string_iter)) abort (); last_char_before_tsub = mbui_cur (string_iter); mbui_advance (string_iter); } while (mbui_cur_ptr (string_iter) < tsub_in_string); if (mb_isalnum (last_char_before_tsub)) word_boundary_before = false; } mbui_init (string_iter, tsub_in_string); { mbui_iterator_t tsub_iter; for (mbui_init (tsub_iter, tsub); mbui_avail (tsub_iter); mbui_advance (tsub_iter)) { if (!mbui_avail (string_iter)) abort (); mbui_advance (string_iter); } } word_boundary_after = true; if (mbui_avail (string_iter)) { mbchar_t first_char_after_tsub = mbui_cur (string_iter); if (mb_isalnum (first_char_after_tsub)) word_boundary_after = false; } if (word_boundary_before && word_boundary_after) { found = true; break; } mbui_init (string_iter, tsub_in_string); if (!mbui_avail (string_iter)) break; string = tsub_in_string + mb_len (mbui_cur (string_iter)); } else { bool word_boundary_before; const char *p; bool word_boundary_after; word_boundary_before = true; if (string < tsub_in_string) if (isalnum ((unsigned char) tsub_in_string[-1])) word_boundary_before = false; p = tsub_in_string + strlen (tsub); word_boundary_after = true; if (*p != '\0') if (isalnum ((unsigned char) *p)) word_boundary_after = false; if (word_boundary_before && word_boundary_after) { found = true; break; } if (*tsub_in_string == '\0') break; string = tsub_in_string + 1; } } } free (tsub); return found; } /* Return the localization of NAME. NAME is written in ASCII. */ const char * proper_name (const char *name) { /* See whether there is a translation. */ const char *translation = gettext (name); if (translation != name) { /* See whether the translation contains the original name. */ if (mbsstr_trimmed_wordbounded (translation, name)) return translation; else { /* Return "TRANSLATION (NAME)". */ char *result = XNMALLOC (strlen (translation) + 2 + strlen (name) + 1 + 1, char); sprintf (result, "%s (%s)", translation, name); return result; } } else return name; } /* Return the localization of a name whose original writing is not ASCII. NAME_UTF8 is the real name, written in UTF-8 with octal or hexadecimal escape sequences. NAME_ASCII is a fallback written only with ASCII characters. */ const char * proper_name_utf8 (const char *name_ascii, const char *name_utf8) { /* See whether there is a translation. */ const char *translation = gettext (name_ascii); /* Try to convert NAME_UTF8 to the locale encoding. */ const char *locale_code = locale_charset (); char *alloc_name_converted = NULL; char *alloc_name_converted_translit = NULL; const char *name_converted = NULL; const char *name_converted_translit = NULL; const char *name; if (c_strcasecmp (locale_code, "UTF-8") != 0) { #if HAVE_ICONV name_converted = alloc_name_converted = xstr_iconv (name_utf8, "UTF-8", locale_code); # if (((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2) || __GLIBC__ > 2) \ && !defined __UCLIBC__) \ || _LIBICONV_VERSION >= 0x0105 { char *converted_translit; size_t len = strlen (locale_code); char *locale_code_translit = XNMALLOC (len + 10 + 1, char); memcpy (locale_code_translit, locale_code, len); memcpy (locale_code_translit + len, "//TRANSLIT", 10 + 1); converted_translit = xstr_iconv (name_utf8, "UTF-8", locale_code_translit); free (locale_code_translit); if (converted_translit != NULL) { # if !_LIBICONV_VERSION /* Don't use the transliteration if it added question marks. glibc's transliteration falls back to question marks; libiconv's transliteration does not. mbschr is equivalent to strchr in this case. */ if (strchr (converted_translit, '?') != NULL) free (converted_translit); else # endif name_converted_translit = alloc_name_converted_translit = converted_translit; } } # endif #endif } else { name_converted = name_utf8; name_converted_translit = name_utf8; } /* The name in locale encoding. */ name = (name_converted != NULL ? name_converted : name_converted_translit != NULL ? name_converted_translit : name_ascii); /* See whether we have a translation. Some translators have not understood that they should use the UTF-8 form of the name, if possible. So if the translator provided a no-op translation, we ignore it. */ if (strcmp (translation, name_ascii) != 0) { /* See whether the translation contains the original name. */ if (mbsstr_trimmed_wordbounded (translation, name_ascii) || (name_converted != NULL && mbsstr_trimmed_wordbounded (translation, name_converted)) || (name_converted_translit != NULL && mbsstr_trimmed_wordbounded (translation, name_converted_translit))) { if (alloc_name_converted != NULL) free (alloc_name_converted); if (alloc_name_converted_translit != NULL) free (alloc_name_converted_translit); return translation; } else { /* Return "TRANSLATION (NAME)". */ char *result = XNMALLOC (strlen (translation) + 2 + strlen (name) + 1 + 1, char); sprintf (result, "%s (%s)", translation, name); if (alloc_name_converted != NULL) free (alloc_name_converted); if (alloc_name_converted_translit != NULL) free (alloc_name_converted_translit); return result; } } else { if (alloc_name_converted != NULL && alloc_name_converted != name) free (alloc_name_converted); if (alloc_name_converted_translit != NULL && alloc_name_converted_translit != name) free (alloc_name_converted_translit); return name; } } #ifdef TEST1 # include <locale.h> int main (int argc, char *argv[]) { setlocale (LC_ALL, ""); if (mbsstr_trimmed_wordbounded (argv[1], argv[2])) printf("found\n"); return 0; } #endif #ifdef TEST2 # include <locale.h> # include <stdio.h> int main (int argc, char *argv[]) { setlocale (LC_ALL, ""); printf ("%s\n", proper_name_utf8 ("Franc,ois Pinard", "Fran\303\247ois Pinard")); return 0; } #endif
{ "content_hash": "8eb808094861f1a44b8bb0a608194b4f", "timestamp": "", "source": "github", "line_count": 303, "max_line_length": 84, "avg_line_length": 30.455445544554454, "alnum_prop": 0.5458387516254877, "repo_name": "google/qpp", "id": "79c6b08e45ea135bd96369f74ee624781dae963e", "size": "10017", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "http/node_modules/jsDAV/node_modules/gnu-tools/grep-src/lib/propername.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "123044" }, { "name": "JavaScript", "bytes": "4477456" }, { "name": "LiveScript", "bytes": "6103" } ], "symlink_target": "" }
<?php /** * Class Admin_model */ class Admin_model extends MY_Model { /** * add 添加管理员 * * @param array $admin_info 管理员信息 * @return mixed */ public function add($admin_info) { if(empty($admin_info['login_name']) || empty($admin_info['password'])) { return false; } $this->load->helper(['tools', 'security']); $this->_insertData['login_name'] = $admin_info['login_name']; $this->_insertData['salt'] = random_characters(); $this->_insertData['password'] = generate_admin_password($admin_info['password'], $this->_insertData['salt']); $this->_insertData['status'] = 0; // 状态[0:正常,1:禁止] return $this->create(); } /** * edit 根据ID修改管理员信息 * * @param int $id 主键ID * @return int 影响的行数 */ public function edit($id) { if(0 >= $id ) { return false; } $this->load->helper(['tools', 'security']); $this->_updateData['status'] = $this->_updateData['lock']; // 状态[0:正常,1:禁止] unset($this->_updateData['lock']); if(! empty($this->_updateData['password'])) { $this->_updateData['salt'] = random_characters(); $this->_updateData['password'] = generate_admin_password($this->_updateData['password'], $this->_updateData['salt']); } $this->_conditions['AND']['id ='] = $id; return $this->update(); } }
{ "content_hash": "1934af68ec2c7307b1d4c0189990ea66", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 129, "avg_line_length": 29.79591836734694, "alnum_prop": 0.5184931506849315, "repo_name": "jadesouth/xy001", "id": "640f0f7b2443f1bbc9dc7a9fc39712ef65c814ea", "size": "1536", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/models/Admin_model.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "97996" }, { "name": "HTML", "bytes": "5747" }, { "name": "JavaScript", "bytes": "15289" }, { "name": "PHP", "bytes": "3822665" } ], "symlink_target": "" }
/** * This class is generated by jOOQ */ package edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.records; import edu.kit.ipd.crowdcontrol.objectservice.database.model.enums.ExperimentsPlatformModeMode; import edu.kit.ipd.crowdcontrol.objectservice.database.model.tables.ExperimentsPlatformMode; import java.sql.Timestamp; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record4; import org.jooq.Row4; import org.jooq.impl.UpdatableRecordImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.7.3" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class ExperimentsPlatformModeRecord extends UpdatableRecordImpl<ExperimentsPlatformModeRecord> implements Record4<Integer, Integer, ExperimentsPlatformModeMode, Timestamp> { private static final long serialVersionUID = 118115201; /** * Setter for <code>crowdcontrol.Experiments_Platform_Mode.id_Experiments_Platform_Mode</code>. */ public void setIdExperimentsPlatformMode(Integer value) { setValue(0, value); } /** * Getter for <code>crowdcontrol.Experiments_Platform_Mode.id_Experiments_Platform_Mode</code>. */ public Integer getIdExperimentsPlatformMode() { return (Integer) getValue(0); } /** * Setter for <code>crowdcontrol.Experiments_Platform_Mode.experiments_platform</code>. */ public void setExperimentsPlatform(Integer value) { setValue(1, value); } /** * Getter for <code>crowdcontrol.Experiments_Platform_Mode.experiments_platform</code>. */ public Integer getExperimentsPlatform() { return (Integer) getValue(1); } /** * Setter for <code>crowdcontrol.Experiments_Platform_Mode.mode</code>. */ public void setMode(ExperimentsPlatformModeMode value) { setValue(2, value); } /** * Getter for <code>crowdcontrol.Experiments_Platform_Mode.mode</code>. */ public ExperimentsPlatformModeMode getMode() { return (ExperimentsPlatformModeMode) getValue(2); } /** * Setter for <code>crowdcontrol.Experiments_Platform_Mode.timestamp</code>. */ public void setTimestamp(Timestamp value) { setValue(3, value); } /** * Getter for <code>crowdcontrol.Experiments_Platform_Mode.timestamp</code>. */ public Timestamp getTimestamp() { return (Timestamp) getValue(3); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record4 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row4<Integer, Integer, ExperimentsPlatformModeMode, Timestamp> fieldsRow() { return (Row4) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row4<Integer, Integer, ExperimentsPlatformModeMode, Timestamp> valuesRow() { return (Row4) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Integer> field1() { return ExperimentsPlatformMode.EXPERIMENTS_PLATFORM_MODE.ID_EXPERIMENTS_PLATFORM_MODE; } /** * {@inheritDoc} */ @Override public Field<Integer> field2() { return ExperimentsPlatformMode.EXPERIMENTS_PLATFORM_MODE.EXPERIMENTS_PLATFORM; } /** * {@inheritDoc} */ @Override public Field<ExperimentsPlatformModeMode> field3() { return ExperimentsPlatformMode.EXPERIMENTS_PLATFORM_MODE.MODE; } /** * {@inheritDoc} */ @Override public Field<Timestamp> field4() { return ExperimentsPlatformMode.EXPERIMENTS_PLATFORM_MODE.TIMESTAMP; } /** * {@inheritDoc} */ @Override public Integer value1() { return getIdExperimentsPlatformMode(); } /** * {@inheritDoc} */ @Override public Integer value2() { return getExperimentsPlatform(); } /** * {@inheritDoc} */ @Override public ExperimentsPlatformModeMode value3() { return getMode(); } /** * {@inheritDoc} */ @Override public Timestamp value4() { return getTimestamp(); } /** * {@inheritDoc} */ @Override public ExperimentsPlatformModeRecord value1(Integer value) { setIdExperimentsPlatformMode(value); return this; } /** * {@inheritDoc} */ @Override public ExperimentsPlatformModeRecord value2(Integer value) { setExperimentsPlatform(value); return this; } /** * {@inheritDoc} */ @Override public ExperimentsPlatformModeRecord value3(ExperimentsPlatformModeMode value) { setMode(value); return this; } /** * {@inheritDoc} */ @Override public ExperimentsPlatformModeRecord value4(Timestamp value) { setTimestamp(value); return this; } /** * {@inheritDoc} */ @Override public ExperimentsPlatformModeRecord values(Integer value1, Integer value2, ExperimentsPlatformModeMode value3, Timestamp value4) { value1(value1); value2(value2); value3(value3); value4(value4); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached ExperimentsPlatformModeRecord */ public ExperimentsPlatformModeRecord() { super(ExperimentsPlatformMode.EXPERIMENTS_PLATFORM_MODE); } /** * Create a detached, initialised ExperimentsPlatformModeRecord */ public ExperimentsPlatformModeRecord(Integer idExperimentsPlatformMode, Integer experimentsPlatform, ExperimentsPlatformModeMode mode, Timestamp timestamp) { super(ExperimentsPlatformMode.EXPERIMENTS_PLATFORM_MODE); setValue(0, idExperimentsPlatformMode); setValue(1, experimentsPlatform); setValue(2, mode); setValue(3, timestamp); } }
{ "content_hash": "316d3a4f283fb51cfe6176ca28f8a57b", "timestamp": "", "source": "github", "line_count": 258, "max_line_length": 180, "avg_line_length": 22.875968992248062, "alnum_prop": 0.6684174855981023, "repo_name": "coolcrowd/object-service", "id": "08ab70517fa82ab2a8c2909992bbbbf986d80782", "size": "5902", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/edu/kit/ipd/crowdcontrol/objectservice/database/model/tables/records/ExperimentsPlatformModeRecord.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "598" }, { "name": "Java", "bytes": "1213277" }, { "name": "JavaScript", "bytes": "2342" }, { "name": "SQLPL", "bytes": "33476" }, { "name": "Shell", "bytes": "551" } ], "symlink_target": "" }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValueAudit" table="trackedentitydatavalueaudit"> <id name="id" column="trackedentitydatavalueauditid"> <generator class="native" /> </id> <many-to-one name="programStageInstance" class="org.hisp.dhis.program.ProgramStageInstance" column="programstageinstanceid" foreign-key="fk_entityinstancedatavalueaudit_programstageinstanceid" /> <many-to-one name="dataElement" class="org.hisp.dhis.dataelement.DataElement" column="dataelementid" foreign-key="fk_entityinstancedatavalueaudit_dataelementid" /> <property name="value" length="50000" /> <property name="created" type="timestamp" /> <property name="providedElsewhere" /> <property name="modifiedBy" /> <property name="auditType" column="audittype" length="100" not-null="true"> <type name="org.hibernate.type.EnumType"> <param name="enumClass">org.hisp.dhis.common.AuditType</param> <param name="type">12</param> </type> </property> </class> </hibernate-mapping>
{ "content_hash": "5fe0d40ac1157c394b9cdcfaeee0ca46", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 117, "avg_line_length": 37.48571428571429, "alnum_prop": 0.6852134146341463, "repo_name": "minagri-rwanda/DHIS2-Agriculture", "id": "3df2d8aa883b247a5d40913e580ad483f90cd6d9", "size": "1312", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dhis-services/dhis-service-core/src/main/resources/org/hisp/dhis/trackedentitydatavalue/hibernate/TrackedEntityDataValueAudit.hbm.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "384517" }, { "name": "Game Maker Language", "bytes": "20893" }, { "name": "HTML", "bytes": "637522" }, { "name": "Java", "bytes": "16273326" }, { "name": "JavaScript", "bytes": "5566092" }, { "name": "Ruby", "bytes": "1011" }, { "name": "Shell", "bytes": "388" }, { "name": "XSLT", "bytes": "8281" } ], "symlink_target": "" }
package edu.sampleu.admin; import org.junit.Test; import org.kuali.rice.testtools.selenium.AutomatedFunctionalTestUtils; import org.kuali.rice.testtools.selenium.WebDriverLegacyITBase; import org.kuali.rice.testtools.selenium.WebDriverUtils; /** * Tests the Component section in Rice. * * @author Kuali Rice Team ([email protected]) */ public class ComponentAft extends ConfigComponentAftBase { String docId; /** * ITUtil.PORTAL + "?channelTitle=Component&channelUrl=" + WebDriverUtils.getBaseUrlString() + "/kr/lookup.do?methodToCall=start&businessObjectClassName=org.kuali.rice.coreservice.impl.component.ComponentBo&docFormKey=88888888&returnLocation=" + ITUtil.PORTAL_URL + "&hideReturnLink=true"; */ public static final String BOOKMARK_URL = AutomatedFunctionalTestUtils.PORTAL + "?channelTitle=Component&channelUrl=" + WebDriverUtils .getBaseUrlString() +"/kr/lookup.do?methodToCall=start&businessObjectClassName=org.kuali.rice.coreservice.impl.component.ComponentBo&docFormKey=88888888&returnLocation=" + AutomatedFunctionalTestUtils.PORTAL_URL + "&hideReturnLink=true"; @Override protected String getBookmarkUrl() { return BOOKMARK_URL; } protected void testComponentParameter() throws Exception { //Create New namespaceCode = "KR-IDM"; uniqueString = AutomatedFunctionalTestUtils.createUniqueDtsPlusTwoRandomCharsNot9Digits(); String componentName = "name" + uniqueString; // same pattern as used in testCreateNewEnterDetails String componentCode = "code" + uniqueString; // same pattern as used in testCreateNewEnterDetails docId = testCreateNew(); submitAndClose(); //Lookup navigate(); testLookUpComponent(docId, componentName, componentCode); //edit testEditComponent(docId, componentName, componentCode); //Verify if its edited navigate(); testVerifyEditedComponent(docId, componentName, componentCode); //copy testCopyComponent(docId, componentName + "copy", componentCode + "copy"); //Verify if its copied navigate(); testVerifyCopyComponent(docId, componentName + "copy", componentCode + "copy"); passed(); } @Test public void testCreateNewCancelComponentBookmark() throws Exception { testCreateNewCancel(); passed(); } @Test public void testComponentCreateNewCancelComponentNav() throws Exception { testCreateNewCancel(); passed(); } @Test public void testComponentParameterBookmark() throws Exception { testComponentParameter(); passed(); } @Test public void testComponentParameterNav() throws Exception { testComponentParameter(); passed(); } }
{ "content_hash": "8515705781dd5aa97017a5722263e554", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 183, "avg_line_length": 33.964285714285715, "alnum_prop": 0.6985629162285314, "repo_name": "ewestfal/rice-svn2git-test", "id": "66e71be2d68ba4f9e7627703c8560fccc32b267b", "size": "3474", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "rice-middleware/sampleapp/src/it/java/edu/sampleu/admin/ComponentAft.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "793243" }, { "name": "Groovy", "bytes": "2170621" }, { "name": "Java", "bytes": "34445604" }, { "name": "JavaScript", "bytes": "2635300" }, { "name": "PHP", "bytes": "15766" }, { "name": "Shell", "bytes": "10444" }, { "name": "XSLT", "bytes": "107686" } ], "symlink_target": "" }
<!-- ~ Copyright (C) 2017 The Android Open Source Project ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="androidx.work.impl.background.firebase"> <application> <service android:exported="false" android:name=".FirebaseJobService"> <intent-filter> <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/> </intent-filter> </service> <receiver android:name=".FirebaseDelayedJobAlarmReceiver" android:exported="true"/> </application> </manifest>
{ "content_hash": "bb004a5fcaf02d7c40073aa96ed6917e", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 82, "avg_line_length": 37.3125, "alnum_prop": 0.6633165829145728, "repo_name": "aosp-mirror/platform_frameworks_support", "id": "0cc38cb2da0037222c20fd9755a62b279b33580f", "size": "1194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "work/workmanager-firebase/src/main/AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "20090" }, { "name": "HTML", "bytes": "514" }, { "name": "IDL", "bytes": "308" }, { "name": "Java", "bytes": "30647232" }, { "name": "Kotlin", "bytes": "2665731" }, { "name": "Python", "bytes": "43821" }, { "name": "Shell", "bytes": "18933" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Propel\Generator\Behavior\Archivable\Component\ActiveRecordTrait; use Propel\Generator\Behavior\Archivable\ArchivableBehavior; use Propel\Generator\Builder\Om\Component\BuildComponent; /** * * @author Marc J. Schmidt <[email protected]> */ class DeleteWithoutArchiveMethod extends BuildComponent { public function process() { /** @var ArchivableBehavior $behavior */ $behavior = $this->getBehavior(); $body = " \$this->getRepository()->deleteWithoutArchive(\$this); \$this->getPropelConfiguration()->getSession()->commit(); "; $this->addMethod('deleteWithoutArchive') ->setDescription('[Archivable] Deletes without creating an archive for it.') ->setBody($body); } }
{ "content_hash": "2d8b3f49babbb1384cb518ee065ef8a1", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 88, "avg_line_length": 27.17241379310345, "alnum_prop": 0.6928934010152284, "repo_name": "propelorm/Propel3", "id": "4cc1357790a304a129dfd6d03ffd18b70c1d2e15", "size": "996", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Generator/Behavior/Archivable/Component/ActiveRecordTrait/DeleteWithoutArchiveMethod.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2909" }, { "name": "Gherkin", "bytes": "6832" }, { "name": "HTML", "bytes": "20281" }, { "name": "Makefile", "bytes": "146" }, { "name": "PHP", "bytes": "4434090" }, { "name": "Shell", "bytes": "3993" }, { "name": "XSLT", "bytes": "74121" } ], "symlink_target": "" }
//// [server.ts] export var a = 10; //// [client.ts] export import defaultBinding, * as nameSpaceBinding from "./server"; export var x: number = nameSpaceBinding.a; //// [server.js] "use strict"; exports.__esModule = true; exports.a = void 0; exports.a = 10; //// [client.js] "use strict"; exports.__esModule = true; exports.x = void 0; var nameSpaceBinding = require("./server"); exports.x = nameSpaceBinding.a; //// [server.d.ts] export declare var a: number; //// [client.d.ts] export declare var x: number;
{ "content_hash": "98e5e2609aed96bb917ab409b1cb955b", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 69, "avg_line_length": 21.6, "alnum_prop": 0.6370370370370371, "repo_name": "weswigham/TypeScript", "id": "4b8c46e904156f07a652d487bd8f7ccb1440ebfd", "size": "639", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingWithExport.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "6259" }, { "name": "JavaScript", "bytes": "1152" }, { "name": "PowerShell", "bytes": "2855" }, { "name": "Shell", "bytes": "47" }, { "name": "TypeScript", "bytes": "121823671" } ], "symlink_target": "" }
package org.apache.lucene.index; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.TestUtil; import org.apache.lucene.util.TestUtil; import org.apache.lucene.store.BufferedIndexInput; import org.apache.lucene.store.ByteArrayDataInput; import org.apache.lucene.store.ByteArrayDataOutput; import org.apache.lucene.store.DataInput; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.RAMDirectory; import org.junit.AfterClass; import org.junit.BeforeClass; import java.io.IOException; import java.util.Random; public class TestIndexInput extends LuceneTestCase { static final byte[] READ_TEST_BYTES = new byte[] { (byte) 0x80, 0x01, (byte) 0xFF, 0x7F, (byte) 0x80, (byte) 0x80, 0x01, (byte) 0x81, (byte) 0x80, 0x01, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x07, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x0F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x07, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x7F, 0x06, 'L', 'u', 'c', 'e', 'n', 'e', // 2-byte UTF-8 (U+00BF "INVERTED QUESTION MARK") 0x02, (byte) 0xC2, (byte) 0xBF, 0x0A, 'L', 'u', (byte) 0xC2, (byte) 0xBF, 'c', 'e', (byte) 0xC2, (byte) 0xBF, 'n', 'e', // 3-byte UTF-8 (U+2620 "SKULL AND CROSSBONES") 0x03, (byte) 0xE2, (byte) 0x98, (byte) 0xA0, 0x0C, 'L', 'u', (byte) 0xE2, (byte) 0x98, (byte) 0xA0, 'c', 'e', (byte) 0xE2, (byte) 0x98, (byte) 0xA0, 'n', 'e', // surrogate pairs // (U+1D11E "MUSICAL SYMBOL G CLEF") // (U+1D160 "MUSICAL SYMBOL EIGHTH NOTE") 0x04, (byte) 0xF0, (byte) 0x9D, (byte) 0x84, (byte) 0x9E, 0x08, (byte) 0xF0, (byte) 0x9D, (byte) 0x84, (byte) 0x9E, (byte) 0xF0, (byte) 0x9D, (byte) 0x85, (byte) 0xA0, 0x0E, 'L', 'u', (byte) 0xF0, (byte) 0x9D, (byte) 0x84, (byte) 0x9E, 'c', 'e', (byte) 0xF0, (byte) 0x9D, (byte) 0x85, (byte) 0xA0, 'n', 'e', // null bytes 0x01, 0x00, 0x08, 'L', 'u', 0x00, 'c', 'e', 0x00, 'n', 'e', // tests for Exceptions on invalid values (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x17, (byte) 0x01, // guard value (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x01, // guard value }; static final int COUNT = RANDOM_MULTIPLIER * 65536; static int[] INTS; static long[] LONGS; static byte[] RANDOM_TEST_BYTES; @BeforeClass public static void beforeClass() throws IOException { Random random = random(); INTS = new int[COUNT]; LONGS = new long[COUNT]; RANDOM_TEST_BYTES = new byte[COUNT * (5 + 4 + 9 + 8)]; final ByteArrayDataOutput bdo = new ByteArrayDataOutput(RANDOM_TEST_BYTES); for (int i = 0; i < COUNT; i++) { final int i1 = INTS[i] = random.nextInt(); bdo.writeVInt(i1); bdo.writeInt(i1); final long l1; if (rarely()) { // a long with lots of zeroes at the end l1 = LONGS[i] = TestUtil.nextLong(random, 0, Integer.MAX_VALUE) << 32; } else { l1 = LONGS[i] = TestUtil.nextLong(random, 0, Long.MAX_VALUE); } bdo.writeVLong(l1); bdo.writeLong(l1); } } @AfterClass public static void afterClass() { INTS = null; LONGS = null; RANDOM_TEST_BYTES = null; } private void checkReads(DataInput is, Class<? extends Exception> expectedEx) throws IOException { assertEquals(128,is.readVInt()); assertEquals(16383,is.readVInt()); assertEquals(16384,is.readVInt()); assertEquals(16385,is.readVInt()); assertEquals(Integer.MAX_VALUE, is.readVInt()); assertEquals(-1, is.readVInt()); assertEquals((long) Integer.MAX_VALUE, is.readVLong()); assertEquals(Long.MAX_VALUE, is.readVLong()); assertEquals("Lucene",is.readString()); assertEquals("\u00BF",is.readString()); assertEquals("Lu\u00BFce\u00BFne",is.readString()); assertEquals("\u2620",is.readString()); assertEquals("Lu\u2620ce\u2620ne",is.readString()); assertEquals("\uD834\uDD1E",is.readString()); assertEquals("\uD834\uDD1E\uD834\uDD60",is.readString()); assertEquals("Lu\uD834\uDD1Ece\uD834\uDD60ne",is.readString()); assertEquals("\u0000",is.readString()); assertEquals("Lu\u0000ce\u0000ne",is.readString()); try { is.readVInt(); fail("Should throw " + expectedEx.getName()); } catch (Exception e) { assertTrue(e.getMessage().startsWith("Invalid vInt")); assertTrue(expectedEx.isInstance(e)); } assertEquals(1, is.readVInt()); // guard value try { is.readVLong(); fail("Should throw " + expectedEx.getName()); } catch (Exception e) { assertTrue(e.getMessage().startsWith("Invalid vLong")); assertTrue(expectedEx.isInstance(e)); } assertEquals(1L, is.readVLong()); // guard value } private void checkRandomReads(DataInput is) throws IOException { for (int i = 0; i < COUNT; i++) { assertEquals(INTS[i], is.readVInt()); assertEquals(INTS[i], is.readInt()); assertEquals(LONGS[i], is.readVLong()); assertEquals(LONGS[i], is.readLong()); } } // this test checks the IndexInput methods of any impl public void testRawIndexInputRead() throws IOException { for (int i = 0; i < 10; i++) { Random random = random(); final Directory dir = newDirectory(); IndexOutput os = dir.createOutput("foo", newIOContext(random)); os.writeBytes(READ_TEST_BYTES, READ_TEST_BYTES.length); os.close(); IndexInput is = dir.openInput("foo", newIOContext(random)); checkReads(is, IOException.class); is.close(); os = dir.createOutput("bar", newIOContext(random)); os.writeBytes(RANDOM_TEST_BYTES, RANDOM_TEST_BYTES.length); os.close(); is = dir.openInput("bar", newIOContext(random)); checkRandomReads(is); is.close(); dir.close(); } } public void testByteArrayDataInput() throws IOException { ByteArrayDataInput is = new ByteArrayDataInput(READ_TEST_BYTES); checkReads(is, RuntimeException.class); is = new ByteArrayDataInput(RANDOM_TEST_BYTES); checkRandomReads(is); } }
{ "content_hash": "9b84cc18ab1ed502a20548d5d354dbe4", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 120, "avg_line_length": 34.43617021276596, "alnum_prop": 0.6261970960766141, "repo_name": "markjin1990/solr", "id": "4acc566b69d0d54ccb78b6d28f34923f4ed8d70e", "size": "7275", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "lucene/core/src/test/org/apache/lucene/index/TestIndexInput.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "26531" }, { "name": "C++", "bytes": "13377" }, { "name": "CSS", "bytes": "118634" }, { "name": "GAP", "bytes": "11057" }, { "name": "Gnuplot", "bytes": "2444" }, { "name": "HTML", "bytes": "1914418" }, { "name": "Java", "bytes": "42750795" }, { "name": "JavaScript", "bytes": "969675" }, { "name": "Perl", "bytes": "85788" }, { "name": "Python", "bytes": "217877" }, { "name": "Shell", "bytes": "219038" }, { "name": "XSLT", "bytes": "160405" } ], "symlink_target": "" }
package slib.platform.android.ui.helper; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebView; import slib.platform.android.Logger; public class WebViewFileChooser implements FileChooserListener { private WebView webView; private int requestCode; private FileChooser fileChooser; private ValueCallback<Uri[]> callback; private ValueCallback<Uri> callbackOld; private boolean flagUseDefaultFileChooserParams; public WebViewFileChooser(WebView webView, int requestCode) { this.webView = webView; this.requestCode = requestCode; this.fileChooser = new FileChooser((Activity)(webView.getContext()), requestCode, this); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public void chooseFile(ValueCallback<Uri[]> callback, WebChromeClient.FileChooserParams fileChooserParams) { if (flagUseDefaultFileChooserParams) { this.callback = callback; this.callbackOld = null; ((Activity)(webView.getContext())).startActivityForResult(fileChooserParams.createIntent(), requestCode); } else { String[] acceptTypes = fileChooserParams.getAcceptTypes(); String acceptTypeTotal = ""; for (int i = 0; i < acceptTypes.length; i++) { String acceptType = acceptTypes[i]; if (acceptType != null && acceptType.length() > 0) { if (acceptTypeTotal.length() > 0) { acceptTypeTotal += ";"; } acceptTypeTotal += acceptType; } } if (acceptTypeTotal.length() == 0) { acceptTypeTotal = "*"; } chooseFile(acceptTypeTotal, fileChooserParams.isCaptureEnabled() ? "capture" : "filesystem", null, callback); } } public void chooseFile(ValueCallback<Uri> callback) { chooseFile(callback, ""); } public void chooseFile(ValueCallback<Uri> callback, String acceptType) { chooseFile(callback, acceptType, "filesystem"); } public void chooseFile(ValueCallback<Uri> callback, String acceptType, String mediaSource) { chooseFile(acceptType, mediaSource, callback, null); } public void chooseFile(String acceptType, String mediaSource, ValueCallback<Uri> callbackOld, ValueCallback<Uri[]> callback) { this.callbackOld = callbackOld; this.callback = callback; try { boolean flagFileSystem = false; if (mediaSource == null || mediaSource.length() == 0) { flagFileSystem = true; mediaSource = "filesystem"; } else if (mediaSource.equals("filesystem")) { flagFileSystem = true; } if (flagFileSystem) { int indexCapture = acceptType.indexOf("capture="); if (indexCapture >= 0) { indexCapture += 8; int lastCapture = acceptType.indexOf(';', indexCapture); if (lastCapture < 0) { mediaSource = acceptType.substring(indexCapture); } else { mediaSource = acceptType.substring(indexCapture, lastCapture); } if (!(mediaSource.equals("filesystem"))) { flagFileSystem = false; } } } if (acceptType.startsWith("image/")) { if (!flagFileSystem && (mediaSource.equals("camera") || mediaSource.equals("capture"))) { fileChooser.captureImage(); } else { fileChooser.chooseImage(); } } else if (acceptType.startsWith("video/")) { if (!flagFileSystem && (mediaSource.equals("camcorder") || mediaSource.equals("capture"))) { fileChooser.captureVideo(); } else { fileChooser.chooseVideo(); } } else if (acceptType.startsWith("audio/")) { if (!flagFileSystem && (mediaSource.equals("microphone") || mediaSource.equals("capture"))) { fileChooser.captureAudio(); } else { fileChooser.chooseAudio(); } } else { fileChooser.chooseFile(); } } catch (Exception e) { Logger.exception(e); if (callback != null) { callback.onReceiveValue(null); } if (callbackOld != null) { callbackOld.onReceiveValue(null); } } } @Override public void onChooseFile(Uri uri, Object content) { if (callback != null) { if (uri != null) { callback.onReceiveValue(new Uri[]{uri}); } else { callback.onReceiveValue(null); } } if (callbackOld != null) { callbackOld.onReceiveValue(uri); } } public void processActivityResult(int resultCode, Intent intent) { if (flagUseDefaultFileChooserParams && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (callback != null) { callback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent)); } } else { fileChooser.processActivityResult(resultCode, intent); } } }
{ "content_hash": "2d148f4b1048f152853642dc5e83ff75", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 127, "avg_line_length": 30.202614379084967, "alnum_prop": 0.6970352737502705, "repo_name": "SLIBIO/SLib", "id": "30ecdf77835a9b5c53680d756786a159663cd96b", "size": "5796", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/android/slib/platform/android/ui/helper/WebViewFileChooser.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "12324" }, { "name": "C", "bytes": "172728" }, { "name": "C++", "bytes": "8974152" }, { "name": "CMake", "bytes": "25579" }, { "name": "Java", "bytes": "412451" }, { "name": "Objective-C", "bytes": "13961" }, { "name": "Objective-C++", "bytes": "641784" }, { "name": "PHP", "bytes": "306070" }, { "name": "Shell", "bytes": "4835" }, { "name": "SourcePawn", "bytes": "19475" } ], "symlink_target": "" }
<?php namespace Magento\Framework\Search\Request\Config; class FileResolverStub implements \Magento\Framework\Config\FileResolverInterface { /** * {@inheritdoc} */ public function get($filename, $scope) { $path = realpath(__DIR__ . '/../../_files/etc'); $paths = [$path . '/search_request_1.xml', $path . '/search_request_2.xml']; return new \Magento\Framework\Config\FileIterator( new \Magento\Framework\Filesystem\File\ReadFactory(new \Magento\Framework\Filesystem\DriverPool), $paths ); } }
{ "content_hash": "008db1b018bc5f89e2462f6a7112aee1", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 109, "avg_line_length": 30.42105263157895, "alnum_prop": 0.6262975778546713, "repo_name": "tarikgwa/test", "id": "7af408c73d09562f26e65f72949c9b995f9342bf", "size": "715", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "html/dev/tests/integration/testsuite/Magento/Framework/Search/Request/Config/FileResolverStub.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "26588" }, { "name": "CSS", "bytes": "4874492" }, { "name": "HTML", "bytes": "8635167" }, { "name": "JavaScript", "bytes": "6810903" }, { "name": "PHP", "bytes": "55645559" }, { "name": "Perl", "bytes": "7938" }, { "name": "Shell", "bytes": "4505" }, { "name": "XSLT", "bytes": "19889" } ], "symlink_target": "" }
#error This file is now obsolete. Instead include stlsoft/collections/util/collections.hpp /* Compatibility [<[STLSOFT-AUTO:NO-DOCFILELABEL]>] [<[STLSOFT-AUTO:NO-UNITTEST]>] */ /* ///////////////////////////// end of file //////////////////////////// */
{ "content_hash": "3f2bf488ff5c36b0fdc8e9e5d8dc26a2", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 90, "avg_line_length": 28.444444444444443, "alnum_prop": 0.5625, "repo_name": "RichieSams/thehalflingproject", "id": "66c34ed9aea0d62c252eea7da9cabeab99f57883", "size": "256", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "libs/stlsoft/include/stlsoft/collections/collections.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "63" }, { "name": "C", "bytes": "535455" }, { "name": "C#", "bytes": "8542" }, { "name": "C++", "bytes": "11857718" }, { "name": "HLSL", "bytes": "112050" }, { "name": "Rich Text Format", "bytes": "46532" } ], "symlink_target": "" }
package org.lambda3.indra; public class AnalyzedTranslatedPair extends AnalyzedPair { public AnalyzedTranslatedPair(TextPair pair) { super(pair); } public void setTranslatedTerm1(MutableTranslatedTerm t1) { this.t1 = t1; } public void setTranslatedTerm2(MutableTranslatedTerm t2) { this.t2 = t2; } public TextPair getTextPair() { return this.pair; } public MutableTranslatedTerm getTranslatedT1() { return (MutableTranslatedTerm) t1; } public MutableTranslatedTerm getTranslatedT2() { return (MutableTranslatedTerm) t2; } }
{ "content_hash": "22c12018d07c095a62d877b100453358", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 62, "avg_line_length": 21.655172413793103, "alnum_prop": 0.6719745222929936, "repo_name": "julsal/indra", "id": "0490c4867e0727c62bfa78942128aedf47077a23", "size": "2056", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "indra-essentials/src/main/java/org/lambda3/indra/AnalyzedTranslatedPair.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "515482" }, { "name": "Python", "bytes": "810" }, { "name": "Shell", "bytes": "418" } ], "symlink_target": "" }
<?php namespace qtil\Tests { use qtil\Identifier; /** * Base qtil test case class * Class qtilTestCase * @package qtil */ abstract class qtilTestCase extends \PHPUnit_Framework_TestCase { /** * Perform setUp tasks */ protected function setUp() { } /** * Perform clean up / tear down tasks */ protected function tearDown() { Identifier::clearSchemes(); } } }
{ "content_hash": "cb5fd19348be0f1dbcbe1c7e7be55e43", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 69, "avg_line_length": 20, "alnum_prop": 0.512, "repo_name": "jgswift/qtil", "id": "c86fe536f9f327739c2d1d63d1e47180b0b4efc5", "size": "500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/qtilTestCase.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "102198" } ], "symlink_target": "" }
srt2vtt ======= Refer: https://github.com/aki159/srt2vtt. I want to make simple interface to be easy to use
{ "content_hash": "3e34bf1a4c423fa05addcaa09b797e21", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 91, "avg_line_length": 27.25, "alnum_prop": 0.7155963302752294, "repo_name": "anbinhtrong/srt2vtt", "id": "5d73364993976c4acadf312c86cf5bb352de6fd9", "size": "109", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1675" } ], "symlink_target": "" }