text
stringlengths
2
1.04M
meta
dict
This package enables metrics from Azure SDK Java libraries through [OpenTelemetry][OpenTelemetry]. OpenTelemetry is an open source, vendor-agnostic, single distribution of libraries to provide metrics collection and distributed tracing for services. [Source code][source_code] | [API reference documentation][api_documentation] | [Product documentation][OpenTelemetry] | [Samples][samples] ## Getting started ### Prerequisites - A [Java Development Kit (JDK)][jdk_link], version 8 or later. ### Include the package [//]: # ({x-version-update-start;com.azure:azure-core-metrics-opentelemetry;current}) ```xml <dependency> <groupId>com.azure</groupId> <artifactId>azure-core-metrics-opentelemetry</artifactId> <version>1.0.0-beta.3</version> </dependency> ``` [//]: # ({x-version-update-end}) ## Key concepts Check out [Metrics in OpenTelemetry](https://opentelemetry.io/docs/concepts/signals/metrics/) for all the details on metrics. ## Examples The following sections provide several code snippets covering some of the most common client configuration scenarios. - [Default configuration: agent](#default-configuration-agent) - [Default configuration: Opentelemtery SDK](#default-configuration-agent) - [Custom configuration](#custom-configuration) You can find more samples [here](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-metrics-opentelemetry/src/samples/). ### Default configuration: agent If you use OpenTelemetry Java agent or Application Insights Java agent version 3.3.0-BETA or higher, no additional Azure SDK configuration is needed. ### Default configuration: OpenTelemetry SDK Azure SDK uses global OpenTelemetry instance by default. You can use [OpenTelemetry SDK Autoconfigure](https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk-extensions/autoconfigure/README.md) package to configure OpenTelemetry using environment variables (or system properties). ```xml <dependency> <groupId>io.opentelemetry</groupId> <artifactId>opentelemetry-sdk-extension-autoconfigure</artifactId> </dependency> ``` ```java readme-sample-defaultConfiguration // configure OpenTelemetry SDK using io.opentelemetry:opentelemetry-sdk-extension-autoconfigure // AutoConfiguredOpenTelemetrySdk.initialize(); // configure Azure Client, no metric configuration needed // client will use global OTel configured by OpenTelemetry autoconfigure package. AzureClient sampleClient = new AzureClientBuilder() .endpoint("https://my-client.azure.com") .build(); // use client as usual, if it emits metric, they will be exported sampleClient.methodCall("get items"); ``` ### Custom configuration If you want to pass `MeterProvider` explicitly, you can do it using `MetricsOptions` and passing them to Azure Clients. `MetricsOptions` can also be used to disable metrics from specific client. ```java readme-sample-customConfiguration // configure OpenTelemetry SDK explicitly per https://opentelemetry.io/docs/instrumentation/java/manual/ SdkMeterProvider meterProvider = SdkMeterProvider.builder() .registerMetricReader(PeriodicMetricReader.builder(OtlpGrpcMetricExporter.builder().build()).build()) .build(); // Pass OTel meterProvider to MetricsOptions. MetricsOptions customMetricsOptions = new OpenTelemetryMetricsOptions() .setProvider(meterProvider); // configure Azure Client to use customMetricsOptions - it will use meterProvider // to create meters and instruments AzureClient sampleClient = new AzureClientBuilder() .endpoint("https://my-client.azure.com") .clientOptions(new ClientOptions().setMetricsOptions(customMetricsOptions)) .build(); // use client as usual, if it emits metric, they will be exported sampleClient.methodCall("get items"); ``` ## Troubleshooting ### General For more information on OpenTelemetry, see [OpenTelemetry documentation](https://opentelemetry.io/docs/instrumentation/java/getting-started/) and [OpenTelemetry Java](https://github.com/open-telemetry/opentelemetry-java). ### Enabling Logging Azure SDKs for Java offer a consistent logging story to help aid in troubleshooting application errors and expedite their resolution. The logs produced will capture the flow of an application before reaching the terminal state to help locate the root issue. View the [logging][logging] wiki for guidance about enabling logging. ## Next steps Get started with Azure libraries that are [built using Azure Core](https://azure.github.io/azure-sdk/releases/latest/#java). ## Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [cla](https://cla.microsoft.com). When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments. <!-- Links --> [api_documentation]: https://aka.ms/java-docs [context]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core/src/main/java/com/azure/core/util/Context.java [jdk_link]: https://docs.microsoft.com/java/azure/jdk/?view=azure-java-stable [logging]: https://github.com/Azure/azure-sdk-for-java/wiki/Logging-with-Azure-SDK [source_code]: https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/core/azure-core-metrics-opentelemetry/src/ ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fcore%2Fazure-core-metrics-opentelemetry%2FREADME.png)
{ "content_hash": "0ae7e1bbd8e9f57ef9714f11f8a56edd", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 287, "avg_line_length": 46.31782945736434, "alnum_prop": 0.7856066945606694, "repo_name": "Azure/azure-sdk-for-java", "id": "75a0646d78db25332db00c6145c049382ed83eee", "size": "6030", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/core/azure-core-metrics-opentelemetry/README.md", "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": "" }
// // AKABinding+IBPropertySupport.h // AKABeacon // // Created by Michael Utech on 24.11.15. // Copyright © 2015 Michael Utech & AKA Sarl. All rights reserved. // #import "AKABinding.h" @interface AKABinding (IBPropertySupport) /** * Gets the binding expression text associated with the specified property selector * of the specified view. * * @param selector the selector of a binding properties getter. The selector name will be used for KVC access to the property value. * @param view the view providing the binding property. * * @return the text of the binding expression or nil if the binding property is undefined. */ + (opt_NSString) bindingExpressionTextForSelector:(req_SEL)selector inView:(req_id)view; /** * Associates the binding expression specified by the expression text with the specified * property select of the specified view. If the binding expression text is nil, the * binding property will be cleared. * * @warn Please note that an exception is thrown if the binding expression is invalid. * * @param bindingExpressionText A valid binding expression or nil. * @param selector the selector of a binding properties getter. The selector name will be used for KVC access to the property value. * @param view the view providing the binding property. */ + (void) setBindingExpressionText:(opt_NSString)bindingExpressionText forSelector:(req_SEL)selector inView:(req_id)view; @end
{ "content_hash": "6f15fe3d794e8818a2732a70c550fdeb", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 132, "avg_line_length": 40.375, "alnum_prop": 0.6736842105263158, "repo_name": "mutech/aka-ios-beacon", "id": "a2b67309ebaae830dd85197358533001847c54e1", "size": "1616", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AKABeacon/AKABeacon/Classes/AKABinding+IBPropertySupport.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "9143" }, { "name": "Objective-C", "bytes": "2238261" }, { "name": "Ruby", "bytes": "1257" }, { "name": "Shell", "bytes": "842" }, { "name": "Swift", "bytes": "42293" } ], "symlink_target": "" }
export { default as ElementCard } from './card' export { default as ElementCardTitle } from './card--title'
{ "content_hash": "ced17c370317214ead50d6186e1b36fc", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 59, "avg_line_length": 54, "alnum_prop": 0.7222222222222222, "repo_name": "vuikit/vuikit", "id": "801a1cca99f43c515522bd1d9361181c5d7fbe21", "size": "108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/vuikit/src/library/card/elements/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "17261" }, { "name": "JavaScript", "bytes": "363451" }, { "name": "Vue", "bytes": "133194" } ], "symlink_target": "" }
void engineLayoutViewGearInit(struct engineLayoutView *this){ engineLayoutViewGearFamilyInit((struct engineLayoutView*)this); engineLayoutViewGearPositionInit((struct engineLayoutView*)this); engineLayoutViewGearGraphicObjectInit((struct engineLayoutView*)this); this->color.r = 1.0; this->color.g = 1.0; this->color.b = 1.0; this->color.a = 1.0; } // 表示要素構造体 ユーティリティの破棄 void engineLayoutViewGearDispose(struct engineLayoutView *this){ engineLayoutViewGearGraphicObjectDispose((struct engineLayoutView*)this); engineLayoutViewGearPositionDispose((struct engineLayoutView*)this); engineLayoutViewGearFamilyDispose((struct engineLayoutView*)this); } // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ---------------------------------------------------------------- // 表示要素構造体 デフォルト関数 bool engineLayoutViewDefaultTouch(struct engineLayoutView *this, int touchIndex, double x, double y, bool dn, bool mv, bool isCancel){ bool isActive = false; bool isActiveChild = engineLayoutViewGearChildrenTouch((struct engineLayoutView*)this, touchIndex, x, y, dn, mv, isCancel || isActive); isActive = isActiveChild || isActive; bool isActiveLocal = engineLayoutViewGearInteractTouch((struct engineLayoutView*)this, touchIndex, x, y, dn, mv, isCancel || isActive); isActive = isActiveLocal || isActive; return isActive; } // 表示要素構造体 デフォルト関数 void engineLayoutViewDefaultCalc(struct engineLayoutView *this, bool isCancel){ // 子要素計算 engineLayoutViewGearChildrenCalc((struct engineLayoutView*)this, isCancel); } // 表示要素構造体 デフォルト関数 void engineLayoutViewDefaultDraw(struct engineLayoutView *this, struct engineMathMatrix44 *mat, struct engineMathVector4 *color){ // 子要素描画 engineLayoutViewGearChildrenDraw((struct engineLayoutView*)this, mat, color); } // 表示要素構造体 デフォルト関数 void engineLayoutViewDefaultPause(struct engineLayoutView *this){ // 子要素一時停止 engineLayoutViewGearChildrenPause((struct engineLayoutView*)this); } // 表示要素構造体 デフォルト関数 void engineLayoutViewDefaultDispose(struct engineLayoutView *this){ // 子要素破棄 engineLayoutViewGearChildrenDispose((struct engineLayoutView*)this); // 自要素破棄 engineLayoutViewGearDispose((struct engineLayoutView*)this); engineUtilMemoryFree(this); } // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ---------------------------------------------------------------- // 初期化 static void init(struct engineLayoutView *this){ engineLayoutViewGearInit((struct engineLayoutView*)this); } // ---------------------------------------------------------------- // 表示要素構造体 作成 struct engineLayoutView *engineLayoutViewCreate(void){ struct engineLayoutView *this = (struct engineLayoutView*)engineUtilMemoryCalloc(1, sizeof(struct engineLayoutView)); init(this); struct engineLayoutView *view = (struct engineLayoutView*)this; view->touch = engineLayoutViewDefaultTouch; view->calc = engineLayoutViewDefaultCalc; view->draw = engineLayoutViewDefaultDraw; view->pause = engineLayoutViewDefaultPause; view->dispose = engineLayoutViewDefaultDispose; view->graphicObject.shouldBufferCreate = engineLayoutViewGearGraphicObjectDefaultShouldBufferCreate; view->graphicObject.bufferCreate = engineLayoutViewGearGraphicObjectDefaultBufferCreate; return (struct engineLayoutView*)this; } // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ----------------------------------------------------------------
{ "content_hash": "c3691701fb985d8b3c2147b03f3498ca", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 174, "avg_line_length": 41, "alnum_prop": 0.6590909090909091, "repo_name": "totetero/fuhaha_engine", "id": "be5fd8f001e10786dc37d7219a553756539ce368", "size": "4151", "binary": false, "copies": "1", "ref": "refs/heads/engine", "path": "src_client/fuhahaEngine/core/engine/engineLayout/engineLayoutView.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "564776" }, { "name": "C++", "bytes": "7115" }, { "name": "HTML", "bytes": "3260" }, { "name": "Java", "bytes": "41266" }, { "name": "JavaScript", "bytes": "66754" }, { "name": "Makefile", "bytes": "3855" }, { "name": "Objective-C", "bytes": "9219" }, { "name": "Shell", "bytes": "12077" }, { "name": "Swift", "bytes": "34280" } ], "symlink_target": "" }
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>RESTEASY-1103</display-name> <!--context-param> <param-name>resteasy.document.secure.processing.feature</param-name> <param-value></param-value> </context-param--> <!--context-param> <param-name>resteasy.document.secure.disableDTDs</param-name> <param-value></param-value> </context-param--> <context-param> <param-name>resteasy.document.expand.entity.references</param-name> <param-value>true</param-value> </context-param> <servlet> <servlet-name>Resteasy</servlet-name> <servlet-class> org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher </servlet-class> <init-param> <param-name>javax.ws.rs.Application</param-name> <param-value>org.jboss.resteasy.utils.TestApplication</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Resteasy</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
{ "content_hash": "39b07fed2fa618ac301f4ed51421ad15", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 113, "avg_line_length": 34.75675675675676, "alnum_prop": 0.6368584758942457, "repo_name": "awhitford/Resteasy", "id": "df2324652b29d4b76a649229c0277f5612e89cf1", "size": "1286", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "testsuite/integration-tests/src/test/resources/org/jboss/resteasy/test/xxe/SecureProcessing_web_default_default_true.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "226" }, { "name": "Java", "bytes": "8760338" }, { "name": "JavaScript", "bytes": "17786" }, { "name": "Python", "bytes": "4868" }, { "name": "Shell", "bytes": "1606" } ], "symlink_target": "" }
<?php // classpath namespace Mimoto\Core\entities; // Mimoto classes use Mimoto\Core\Validation; use Mimoto\Mimoto; use Mimoto\Core\CoreConfig; use Mimoto\Core\CoreFormUtils; use Mimoto\EntityConfig\MimotoEntityPropertyValueTypes; /** * Component * * @author Sebastian Kersten (@supertaboo) */ class ComponentTemplate { public static function getStructure() { return (object) array( 'id' => CoreConfig::MIMOTO_COMPONENT_TEMPLATE, // --- 'name' => CoreConfig::MIMOTO_COMPONENT_TEMPLATE, 'extends' => null, 'forms' => [CoreConfig::MIMOTO_COMPONENT_TEMPLATE], 'properties' => [ (object) array( 'id' => CoreConfig::MIMOTO_COMPONENT_TEMPLATE.'--file', // --- 'name' => 'file', 'type' => CoreConfig::PROPERTY_TYPE_VALUE, 'settings' => [ 'type' => (object) array( 'key' => 'type', 'type' => MimotoEntityPropertyValueTypes::VALUETYPE_TEXT, 'value' => CoreConfig::DATA_VALUE_TEXTLINE ) ] ), (object) array( 'id' => CoreConfig::MIMOTO_COMPONENT_TEMPLATE.'--conditionals', // --- 'name' => 'conditionals', 'type' => CoreConfig::PROPERTY_TYPE_COLLECTION, 'settings' => [ 'allowedEntityTypes' => (object) array( 'key' => 'allowedEntityTypes', 'type' => MimotoEntityPropertyValueTypes::VALUETYPE_ARRAY, 'value' => [CoreConfig::MIMOTO_COMPONENT_CONDITIONAL] ), 'allowDuplicates' => (object) array( 'key' => 'allowDuplicates', 'type' => MimotoEntityPropertyValueTypes::VALUETYPE_BOOLEAN, 'value' => CoreConfig::DATA_VALUE_FALSE ) ] ) ] ); } public static function getData() { } // ---------------------------------------------------------------------------- // --- Form ------------------------------------------------------------------- // ---------------------------------------------------------------------------- /** * Get form structure */ public static function getFormStructure() { return (object) array( 'id' => CoreConfig::MIMOTO_COMPONENT_TEMPLATE, 'name' => CoreConfig::MIMOTO_COMPONENT_TEMPLATE, 'class' => get_class(), 'inputFieldIds' => [ CoreFormUtils::composeFieldName(CoreConfig::MIMOTO_COMPONENT_TEMPLATE, 'file'), CoreFormUtils::composeFieldName(CoreConfig::MIMOTO_COMPONENT_TEMPLATE, 'conditionals') ] ); } /** * Get form */ public static function getForm() { // init $form = CoreFormUtils::initForm(CoreConfig::MIMOTO_COMPONENT_TEMPLATE, true); // setup CoreFormUtils::addField_title($form, 'Component', '', "The key element in presenting data is the 'component'. These are twig files that use the Aimless protocol to read and render the data, with the support of realtime updates to any client."); CoreFormUtils::addField_groupStart($form); $field = CoreFormUtils::addField_textline ( $form, 'file', CoreConfig::MIMOTO_COMPONENT_TEMPLATE.'--file', 'Twig file', 'your_template_file.twig', '', Mimoto::service('config')->get('folders.components') ); self::setFileValidation($field); CoreFormUtils::addField_groupEnd($form); // send return $form; } // ---------------------------------------------------------------------------- // --- private methods--------------------------------------------------------- // ---------------------------------------------------------------------------- /** * Set file validation */ private static function setFileValidation($field) { // validation rule #1 $validationRule = Mimoto::service('data')->create(CoreConfig::MIMOTO_FORM_FIELD_VALIDATION); $validationRule->setId(CoreConfig::MIMOTO_COMPONENT_TEMPLATE.'--file_value_validation1'); $validationRule->setValue('type', 'minchars'); $validationRule->setValue('value', 1); $validationRule->setValue('errorMessage', "Value can't be empty"); $field->addValue('validation', $validationRule); // send return $field; } }
{ "content_hash": "b250b5283168df786e53bea17baca061", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 252, "avg_line_length": 33.10204081632653, "alnum_prop": 0.4712289354706124, "repo_name": "SebastianKersten/Mimoto.Aimless", "id": "956c3d8f7f2573f1d5501c4fa9b12247a8c6a63c", "size": "4866", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/domains/Core/entities/ComponentTemplate.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "447" }, { "name": "CSS", "bytes": "196135" }, { "name": "HTML", "bytes": "333667" }, { "name": "JavaScript", "bytes": "716341" }, { "name": "PHP", "bytes": "793753" } ], "symlink_target": "" }
'use strict'; const fs = require('fs'); const path = require('path'); function loadPlugins(callback) { const dir = path.join(__dirname, 'browser-sync/plugins'); fs.readdir(dir, (err, files) => { if (err) { return callback(err); } let readPlugins = 0; let scriptContents = ''; files.map((file) => { fs.readFile(path.join(dir, file), 'utf-8', (err, data) => { if (err) { return callback(err); } scriptContents += data; if (++readPlugins === files.length) { callback(null, scriptContents); } }); }); }); } function loadHandlers(callback) { fs.readdir(path.join(__dirname, 'browser-sync/handlers'), (err, files) => { if (err) { return callback(err); } let otherFiles = ['build/public/**/*.{html,css,js}']; const watchedFiles = []; files.map((file) => { const handler = require(path.join(__dirname, 'browser-sync/handlers', file)); watchedFiles.push(handler); // Add the specially handled files to an ignored list. otherFiles = otherFiles.concat(handler.match.map((s) => { return `!${s}`; })); }); // Return list of files with special handlers at top of list to ensure custom handlers are // run. All other files are included afterwards. callback(null, watchedFiles.concat(otherFiles)); }); } module.exports = (server) => { if (server.get('env') === 'production') { return; } const browserSync = require('browser-sync'); const bs = browserSync.create('Server'); loadPlugins((err, scriptContents) => { if (err) { console.log(err); return; } // TODO: Load this from a JSON file. // Scroll elements to be synced across apps. const scrollElements = [ '#mainContainer' ]; bs.use({ plugin: function () { return true; }, hooks: { 'client:events': function () { // TODO: Load this from plugins. const events = ['custom-component-css']; scrollElements.map(function (element) { events.push(`${element}:scroll`); }); return events; }, 'client:js': scriptContents } }); loadHandlers((err, files) => { if (err) { console.log(err); return; } // Defer initialisation until next tick to ensure express server is running. process.nextTick(() => { const port = process.env.PORT_BROWSER_SYNC || 3000; const proxy = `localhost:${parseInt(server.get('port'))}`; bs.init({ files: files, logPrefix: 'BrowserSync', minify: true, open: false, reloadOnRestart: true, reloadDebound: 2000, server: false, port: port, proxy: proxy }); }); }); }); };
{ "content_hash": "3540c93ad4495b2244ba65fb24951dbe", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 92, "avg_line_length": 21.096774193548388, "alnum_prop": 0.6032110091743119, "repo_name": "KK578/generator-kk578", "id": "d1b45b6368c0df346de205a6db41c0a010b13a49", "size": "2616", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "generators/node-server/templates/server/configs/browser-sync.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "15904" }, { "name": "HTML", "bytes": "5809" }, { "name": "JavaScript", "bytes": "72081" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace EZOper.TechTester.EZWebCoreTemplate { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "Help", template: "Help/{controller}/{action}/{id?}", defaults: new { area = "Help", controller = "Home", action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { area = "Home", controller = "Home", action = "Index" }); }); } } }
{ "content_hash": "8b7a1eab48c12e6cdf0e7075ddb8ef33", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 109, "avg_line_length": 34.72727272727273, "alnum_prop": 0.5815881326352531, "repo_name": "erikzhouxin/CSharpSolution", "id": "b75ee3eaba864c249a4946f8a84fc12e36db3077", "size": "2294", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EZWebCoreTemplate/Startup.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "153832" }, { "name": "Batchfile", "bytes": "104" }, { "name": "C#", "bytes": "16507100" }, { "name": "CSS", "bytes": "1339701" }, { "name": "HTML", "bytes": "25059213" }, { "name": "Java", "bytes": "10698" }, { "name": "JavaScript", "bytes": "53532704" }, { "name": "PHP", "bytes": "48348" }, { "name": "PLSQL", "bytes": "8976" }, { "name": "PowerShell", "bytes": "471" }, { "name": "Ruby", "bytes": "1030" } ], "symlink_target": "" }
package com.sinotrans.transport.controller; import com.sinotrans.transport.common.ErrorCode; import com.sinotrans.transport.common.cache.SingletonCache; import com.sinotrans.transport.common.enums.CompanyType; import com.sinotrans.transport.common.exception.CommonException; import com.sinotrans.transport.common.exception.RestException; import com.sinotrans.transport.dto.OnPassageOrderSearchRequest; import com.sinotrans.transport.dto.OnPassageOrderSearchResponse; import com.sinotrans.transport.dto.QueryBill3Response; import com.sinotrans.transport.dto.common.RestResponse; import com.sinotrans.transport.dto.out.*; import com.sinotrans.transport.dto.vo.CompanySimpleVo; import com.sinotrans.transport.service.BaseService; import com.sinotrans.transport.service.CompanyAddressService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by emi on 2016/5/20. */ @Controller @RequestMapping(value = "/api") public class BaseController { Logger logger = Logger.getLogger(BaseController.class); @Autowired private BaseService baseService; @Autowired private CompanyAddressService companyAddressService; // 客户基础信息,货主,用户注册绑定的公司 @RequestMapping(value = "queryCrmTypeIdIsCU", method = RequestMethod.GET) @ResponseBody public QueryCrmResponse queryUser(HttpServletRequest request, String codeOrName) { int customerType = (Integer)request.getAttribute("customerType"); return baseService.queryCustomer(customerType, codeOrName); } @RequestMapping(value = "queryCrmTypeIdIsCW", method = RequestMethod.GET) @ResponseBody public QueryCrmResponse queryContainerOwner(HttpServletRequest request, String codeOrName) { int customerType = (Integer)request.getAttribute("customerType"); return baseService.queryContainerOwner(customerType, codeOrName); } @RequestMapping(value = "queryContainerType", method = RequestMethod.GET) @ResponseBody public QueryTypeCodeResponse queryContainerType(HttpServletRequest request) { int customerType = (Integer)request.getAttribute("customerType"); return baseService.queryTypeCode(customerType, "queryContainerType"); } @RequestMapping(value = "queryContainerSize", method = RequestMethod.GET) @ResponseBody public QueryTypeCodeResponse queryContainerSize(HttpServletRequest request) { int customerType = (Integer)request.getAttribute("customerType"); return baseService.queryTypeCode(customerType, "queryContainerSize"); } /** * 获取船名信息 */ @RequestMapping(value = "queryVessel", method = RequestMethod.GET) @ResponseBody public QueryVesselResponse queryVessel(HttpServletRequest request, String codeOrEnname) { int customerType = (Integer)request.getAttribute("customerType"); return baseService.queryVessel(customerType, codeOrEnname); } /** * 获取航次信息 */ @RequestMapping(value = "queryVesselEtd", method = RequestMethod.GET) @ResponseBody public QueryVesselEtdResponse queryVesselEtd(HttpServletRequest request, String vesselCode, String voyage) { int customerType = (Integer)request.getAttribute("customerType"); return baseService.queryVesselEtd(customerType, vesselCode, voyage); } /** * 获取港口信息 */ @RequestMapping(value = "queryPortCode", method = RequestMethod.GET) @ResponseBody public QueryPortCodeResponse queryPortCode(HttpServletRequest request, String codeOrEnname) { int customerType = (Integer)request.getAttribute("customerType"); return baseService.queryPortCode(customerType, codeOrEnname); } /** * 获取提箱点 返箱点信息 */ @RequestMapping(value = "queryDepot", method = RequestMethod.GET) @ResponseBody public QueryDepotResponse queryDepot(HttpServletRequest request, String codeOrName) { int customerType = (Integer)request.getAttribute("customerType"); return baseService.queryDepot(customerType, codeOrName); } // @RequestMapping(value = "/queryBillList", method = RequestMethod.GET) // @ResponseBody // public QueryBillResponse queryBillList(HttpServletRequest request, QueryBillRequest billRequest) { // int customerType = (Integer)request.getAttribute("customerType"); // return baseService.queryBillList(customerType, billRequest); // } // @RequestMapping(value = "/queryBillList2", method = RequestMethod.GET) // @ResponseBody // public QueryBill2Response queryBillList2(HttpServletRequest request, QueryBillRequest billRequest) { // int customerType = (Integer)request.getAttribute("customerType"); // return baseService.queryBillList2(customerType, billRequest); // } @RequestMapping(value = "/queryBillList3", method = RequestMethod.GET) @ResponseBody public QueryBill3Response queryBillList3(QueryBillRequest billRequest, HttpServletRequest request) { int customerType = (Integer)request.getAttribute("customerType"); return baseService.queryBillList3(customerType, billRequest); } @RequestMapping(value = "/excel/bill",method = RequestMethod.GET) @ResponseBody public RestResponse exportBill(QueryBillRequest billRequest, String customerType, HttpServletResponse response) { // int customerType = (Integer)request.getAttribute("customerType"); if (StringUtils.isEmpty(customerType)) { throw new CommonException(ErrorCode.COMMON_ERROR, "用户类型不能为空", "用户类型[" + customerType + "]错误", logger); } int custType = ("1".equals(customerType) || CompanyType.YuXiong.getCode().equals(customerType) || CompanyType.AdminAll.getCode().equals(customerType)) ? 1 : ("2".equals(customerType) || CompanyType.YuGuo.getCode().equals(customerType))? 2 : 0; if (0 == custType) { throw new CommonException(ErrorCode.COMMON_ERROR, "用户类型错误", "用户类型[" + customerType + "]错误", logger); } try { String fileName = "report_bill_" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".xls"; ServletOutputStream outputStream; response.reset(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); try { response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1")); outputStream = response.getOutputStream(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new CommonException(ErrorCode.COMMON_ERROR, "http下载异常", null, null); } catch (IOException e) { e.printStackTrace(); throw new CommonException(ErrorCode.COMMON_ERROR, "http下载获取流异常异常", null, null); } outputStream = baseService.exportBillExcel(custType, billRequest, outputStream); if (null == outputStream) { throw new CommonException(ErrorCode.COMMON_ERROR, "查询结果为空,无需导出", null, null); } baseService.exportDownload(outputStream); } catch (RestException e) { throw e; }catch (Exception e) { e.printStackTrace(); throw new CommonException(ErrorCode.COMMON_ERROR, "导出xml失败", null, logger); } return new RestResponse(); } /** * 在途订单跟踪 * @param request * @param search * @return */ @RequestMapping(value = "/onPassage",method = RequestMethod.GET) @ResponseBody public OnPassageOrderSearchResponse searchOnPassage(HttpServletRequest request,OnPassageOrderSearchRequest search){ CompanySimpleVo vo = SingletonCache.getCompanySimpleInfo(request); search.setCompanyCode(vo.getCompanyCode()); return companyAddressService.searchOnPassage(search); } }
{ "content_hash": "fef50a83a86d5715c26f0324825c9759", "timestamp": "", "source": "github", "line_count": 189, "max_line_length": 162, "avg_line_length": 44.64021164021164, "alnum_prop": 0.7219390778712813, "repo_name": "okmnhyxx/car-free-transport", "id": "042ff79e5b668be955f6fde2af30e0ab4dab492c", "size": "8649", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/sinotrans/transport/controller/BaseController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "83328" }, { "name": "HTML", "bytes": "809251" }, { "name": "Java", "bytes": "1301223" }, { "name": "JavaScript", "bytes": "1281417" } ], "symlink_target": "" }
package robot import ( "context" "github.com/goharbor/harbor/src/lib/q" "github.com/goharbor/harbor/src/pkg/robot/dao" "github.com/goharbor/harbor/src/pkg/robot/model" ) var ( // Mgr is a global variable for the default robot account manager implementation Mgr = NewManager() ) // Manager ... type Manager interface { // Get ... Get(ctx context.Context, id int64) (*model.Robot, error) // Count returns the total count of robots according to the query Count(ctx context.Context, query *q.Query) (total int64, err error) // Create ... Create(ctx context.Context, m *model.Robot) (int64, error) // Delete ... Delete(ctx context.Context, id int64) error // DeleteByProjectID ... DeleteByProjectID(ctx context.Context, projectID int64) error // Update ... Update(ctx context.Context, m *model.Robot, props ...string) error // List ... List(ctx context.Context, query *q.Query) ([]*model.Robot, error) } var _ Manager = &manager{} type manager struct { dao dao.DAO } // NewManager return a new instance of defaultRobotManager func NewManager() Manager { return &manager{ dao: dao.New(), } } // Get ... func (m *manager) Get(ctx context.Context, id int64) (*model.Robot, error) { return m.dao.Get(ctx, id) } // Count ... func (m *manager) Count(ctx context.Context, query *q.Query) (total int64, err error) { return m.dao.Count(ctx, query) } // Create ... func (m *manager) Create(ctx context.Context, r *model.Robot) (int64, error) { return m.dao.Create(ctx, r) } // Delete ... func (m *manager) Delete(ctx context.Context, id int64) error { return m.dao.Delete(ctx, id) } // DeleteByProjectID ... func (m *manager) DeleteByProjectID(ctx context.Context, projectID int64) error { return m.dao.DeleteByProjectID(ctx, projectID) } // Update ... func (m *manager) Update(ctx context.Context, r *model.Robot, props ...string) error { return m.dao.Update(ctx, r, props...) } // List ... func (m *manager) List(ctx context.Context, query *q.Query) ([]*model.Robot, error) { return m.dao.List(ctx, query) }
{ "content_hash": "8305c5f04b8d731a0c9f4aa98c7e77ee", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 87, "avg_line_length": 23.802325581395348, "alnum_prop": 0.6897899364924279, "repo_name": "wy65701436/harbor", "id": "63526038577bce3d7bf88a675addc6915ae83606", "size": "2047", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/pkg/robot/manager.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2122" }, { "name": "Dockerfile", "bytes": "17013" }, { "name": "Go", "bytes": "5543957" }, { "name": "HTML", "bytes": "857388" }, { "name": "JavaScript", "bytes": "8987" }, { "name": "Jinja", "bytes": "199133" }, { "name": "Makefile", "bytes": "41515" }, { "name": "PLpgSQL", "bytes": "11799" }, { "name": "Python", "bytes": "532665" }, { "name": "RobotFramework", "bytes": "482646" }, { "name": "SCSS", "bytes": "113564" }, { "name": "Shell", "bytes": "81765" }, { "name": "Smarty", "bytes": "1931" }, { "name": "TypeScript", "bytes": "2048995" } ], "symlink_target": "" }
<?php namespace Proxies\__CG__\furies\orbitBundle\Entity; /** * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR */ class Radgroupcheck extends \furies\orbitBundle\Entity\Radgroupcheck implements \Doctrine\ORM\Proxy\Proxy { /** * @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with * three parameters, being respectively the proxy object to be initialized, the method that triggered the * initialization process and an array of ordered parameters that were passed to that method. * * @see \Doctrine\Common\Persistence\Proxy::__setInitializer */ public $__initializer__; /** * @var \Closure the callback responsible of loading properties that need to be copied in the cloned object * * @see \Doctrine\Common\Persistence\Proxy::__setCloner */ public $__cloner__; /** * @var boolean flag indicating if this object was already initialized * * @see \Doctrine\Common\Persistence\Proxy::__isInitialized */ public $__isInitialized__ = false; /** * @var array properties to be lazy loaded, with keys being the property * names and values being their default values * * @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties */ public static $lazyPropertiesDefaults = array(); /** * @param \Closure $initializer * @param \Closure $cloner */ public function __construct($initializer = null, $cloner = null) { $this->__initializer__ = $initializer; $this->__cloner__ = $cloner; } /** * * @return array */ public function __sleep() { if ($this->__isInitialized__) { return array('__isInitialized__', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'groupname', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'attribute', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'op', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'value', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'companyid', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'id'); } return array('__isInitialized__', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'groupname', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'attribute', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'op', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'value', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'companyid', '' . "\0" . 'furies\\orbitBundle\\Entity\\Radgroupcheck' . "\0" . 'id'); } /** * */ public function __wakeup() { if ( ! $this->__isInitialized__) { $this->__initializer__ = function (Radgroupcheck $proxy) { $proxy->__setInitializer(null); $proxy->__setCloner(null); $existingProperties = get_object_vars($proxy); foreach ($proxy->__getLazyProperties() as $property => $defaultValue) { if ( ! array_key_exists($property, $existingProperties)) { $proxy->$property = $defaultValue; } } }; } } /** * */ public function __clone() { $this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', array()); } /** * Forces initialization of the proxy */ public function __load() { $this->__initializer__ && $this->__initializer__->__invoke($this, '__load', array()); } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __isInitialized() { return $this->__isInitialized__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitialized($initialized) { $this->__isInitialized__ = $initialized; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitializer(\Closure $initializer = null) { $this->__initializer__ = $initializer; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __getInitializer() { return $this->__initializer__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setCloner(\Closure $cloner = null) { $this->__cloner__ = $cloner; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific cloning logic */ public function __getCloner() { return $this->__cloner__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic * @static */ public function __getLazyProperties() { return self::$lazyPropertiesDefaults; } /** * {@inheritDoc} */ public function setGroupname($groupname) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setGroupname', array($groupname)); return parent::setGroupname($groupname); } /** * {@inheritDoc} */ public function getGroupname() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getGroupname', array()); return parent::getGroupname(); } /** * {@inheritDoc} */ public function setAttribute($attribute) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setAttribute', array($attribute)); return parent::setAttribute($attribute); } /** * {@inheritDoc} */ public function getAttribute() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getAttribute', array()); return parent::getAttribute(); } /** * {@inheritDoc} */ public function setOp($op) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setOp', array($op)); return parent::setOp($op); } /** * {@inheritDoc} */ public function getOp() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getOp', array()); return parent::getOp(); } /** * {@inheritDoc} */ public function setValue($value) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setValue', array($value)); return parent::setValue($value); } /** * {@inheritDoc} */ public function getValue() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getValue', array()); return parent::getValue(); } /** * {@inheritDoc} */ public function setCompanyid($companyid) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setCompanyid', array($companyid)); return parent::setCompanyid($companyid); } /** * {@inheritDoc} */ public function getCompanyid() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getCompanyid', array()); return parent::getCompanyid(); } /** * {@inheritDoc} */ public function getId() { if ($this->__isInitialized__ === false) { return (int) parent::getId(); } $this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', array()); return parent::getId(); } }
{ "content_hash": "53bdffb1ef7f27caa08f4a52b02d6e2d", "timestamp": "", "source": "github", "line_count": 301, "max_line_length": 502, "avg_line_length": 26.87043189368771, "alnum_prop": 0.5569980217606331, "repo_name": "furies/orbit", "id": "10e02c263cca67ba2f0bc04b4e858f7e42c4c6dd", "size": "8088", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/cache/prod/doctrine/orm/Proxies/__CG__furiesorbitBundleEntityRadgroupcheck.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "412754" }, { "name": "JavaScript", "bytes": "1347858" }, { "name": "PHP", "bytes": "145793" } ], "symlink_target": "" }
/** * Показывает предупреждение о несовместимом браузере * * @module BrowserCompatibility * * Created by Evgeniy Malyarov on 07.09.2017. */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import Paper from '@material-ui/core/Paper'; import Typography from '@material-ui/core/Typography'; import withStyles from '../styles/paper600'; // Совместимость браузера проверяем по наличию конструкторов Promise, Proxy и Symbol export function browser_compatible(ie11) { // navigator.userAgent.match(/(Chrome|Opera|YaBrowser)/) && !navigator.userAgent.match(/Edge/); return (typeof Promise == 'function' && typeof Proxy == 'function' && typeof Symbol == 'function') || (ie11 && navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/11.0/)) || navigator.userAgent.match(/Google|Yandex|Slurp|ia_archiver/i); } function BrowserCompatibility({classes}) { return <Paper className={classes.root} elevation={4}> <Typography variant="h4">Неподдерживаемый браузер</Typography> <Typography>Для запуска приложений metadata.js, требуется браузер с движком V8 или SpiderMonkey:</Typography> <ul> <li>Chrome</li> <li>Opera</li> <li>Yandex</li> <li>Firefox</li> </ul> <p>&nbsp;</p> </Paper>; } export default withStyles(BrowserCompatibility);
{ "content_hash": "ff321786325a67f14522ea75670b9752", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 113, "avg_line_length": 31.162790697674417, "alnum_prop": 0.7067164179104478, "repo_name": "oknosoft/metadata.js", "id": "271ad4fe2d8640fba7b967162d700d8bd570cd66", "size": "1509", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/metadata-react/src/App/BrowserCompatibility.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "936" }, { "name": "CSS", "bytes": "561997" }, { "name": "HTML", "bytes": "20310" }, { "name": "JavaScript", "bytes": "5313002" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Adenosacme mindanaensis Elmer ### Remarks null
{ "content_hash": "019b5195300410844e7aef785beb95d0", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 12.23076923076923, "alnum_prop": 0.7295597484276729, "repo_name": "mdoering/backbone", "id": "e0186f7ca7ecf1782eb2936818c94626f61b3870", "size": "220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Mycetia/Mycetia mindanaensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
name = "Andre Christoga" age = 11 height = 151 hobby = "#coding" print "My name is " + name print "My age is " + age print "I am" + height print "My height is " + hobby
{ "content_hash": "2328827be78d53f7a817da3c4e8479b1", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 29, "avg_line_length": 19, "alnum_prop": 0.6374269005847953, "repo_name": "christoga/learn-python", "id": "73ed125046960df756bbca4aa847c1e0b0cba023", "size": "171", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "profile.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "964" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>stdpp: 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.15.1 / stdpp - 1.2.1</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> stdpp <small> 1.2.1 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-11 09:27:55 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-11 09:27:55 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.15.1 Formal proof management system dune 3.4.1 Fast, portable, and opinionated build system ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler ocamlfind 1.9.1 A library manager for OCaml ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; name: &quot;coq-stdpp&quot; maintainer: &quot;Ralf Jung &lt;jung@mpi-sws.org&gt;&quot; homepage: &quot;https://gitlab.mpi-sws.org/iris/stdpp&quot; authors: &quot;Robbert Krebbers, Jacques-Henri Jourdan, Ralf Jung&quot; bug-reports: &quot;https://gitlab.mpi-sws.org/iris/stdpp/issues&quot; license: &quot;BSD&quot; dev-repo: &quot;git+https://gitlab.mpi-sws.org/iris/stdpp.git&quot; tags: [ &quot;date:2019-08-29&quot; ] synopsis: &quot;std++ is an extended \&quot;Standard Library\&quot; for Coq&quot; description: &quot;&quot;&quot; The key features of this library are as follows: - It provides a great number of definitions and lemmas for common data structures such as lists, finite maps, finite sets, and finite multisets. - It uses type classes for common notations (like `∅`, `∪`, and Haskell-style monad notations) so that these can be overloaded for different data structures. - It uses type classes to keep track of common properties of types, like it having decidable equality or being countable or finite. - Most data structures are represented in canonical ways so that Leibniz equality can be used as much as possible (for example, for maps we have `m1 = m2` iff `∀ i, m1 !! i = m2 !! i`). On top of that, the library provides setoid instances for most types and operations. - It provides various tactics for common tasks, like an ssreflect inspired `done` tactic for finishing trivial goals, a simple breadth-first solver `naive_solver`, an equality simplifier `simplify_eq`, a solver `solve_proper` for proving compatibility of functions with respect to relations, and a solver `set_solver` for goals involving set operations. - It is entirely dependency- and axiom-free.&quot;&quot;&quot; depends: [ &quot;coq&quot; {(&gt;= &quot;8.7.2&quot; &amp; &lt; &quot;8.11~&quot;) | (= &quot;dev&quot;)} ] build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] url { src: &quot;https://gitlab.mpi-sws.org/iris/stdpp/-/archive/coq-stdpp-1.2.1.tar.gz&quot; checksum: &quot;sha512=8eb04e9a70a9be0b7a9565516d03952ec9c54cb7abe20ddea4d27ceb3c18022fdf2f1409df6988092741a0e5e9086f852dc2eb3e7bdc4f4eff91b2baa72c16af&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-stdpp.1.2.1 coq.8.15.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.15.1). The following dependencies couldn&#39;t be met: - coq-stdpp -&gt; coq (&lt; 8.11~ &amp; = dev) -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-stdpp.1.2.1</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "756fa5582c25fb4423114e78fb1b507e", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 159, "avg_line_length": 44.950819672131146, "alnum_prop": 0.5697787503039144, "repo_name": "coq-bench/coq-bench.github.io", "id": "321450a8337119264cb907aa4739cde928e94c36", "size": "8257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.15.1/stdpp/1.2.1.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/* $OpenBSD: vmparam.h,v 1.3 2001/09/22 18:00:09 miod Exp $ */ /* $NetBSD: vmparam.h,v 1.1 1996/09/30 16:34:38 ws Exp $ */ /*- * Copyright (C) 1995, 1996 Wolfgang Solfrank. * Copyright (C) 1995, 1996 TooLs GmbH. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by TooLs GmbH. * 4. The name of TooLs GmbH may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MACHINE_VMPARAM_H #define MACHINE_VMPARAM_H #define USRTEXT PAGE_SIZE #define USRSTACK VM_MAXUSER_ADDRESS #ifndef MAXTSIZ #define MAXTSIZ (16*1024*1024) /* max text size */ #endif #ifndef DFLDSIZ #define DFLDSIZ (32*1024*1024) /* default data size */ #endif #ifndef MAXDSIZ #define MAXDSIZ (512*1024*1024) /* max data size */ #endif #ifndef DFLSSIZ #define DFLSSIZ (1*1024*1024) /* default stack size */ #endif #ifndef MAXSSIZ #define MAXSSIZ (32*1024*1024) /* max stack size */ #endif /* * Size of shared memory map */ #ifndef SHMMAXPGS #define SHMMAXPGS 1024 #endif /* * Size of User Raw I/O map */ #define USRIOSIZE 1024 /* * The time for a process to be blocked before being very swappable. * This is a number of seconds which the system takes as being a non-trivial * amount of real time. You probably shouldn't change this; * it is used in subtle ways (fractions and multiples of it are, that is, like * half of a ``long time'', almost a long time, etc.) * It is related to human patience and other factors which don't really * change over time. */ #define MAXSLP 20 /* * Would like to have MAX addresses = 0, but this doesn't (currently) work */ #define VM_MIN_ADDRESS ((vm_offset_t)0) #define VM_MAXUSER_ADDRESS ((vm_offset_t)0xfffff000) #define VM_MAX_ADDRESS VM_MAXUSER_ADDRESS #define VM_MIN_KERNEL_ADDRESS ((vm_offset_t)(KERNEL_SR << ADDR_SR_SHFT)) /* ppc_kvm_size is so that vm space can be stolen before vm is fully * initialized. */ #define VM_KERN_ADDR_SIZE_DEF SEGMENT_LENGTH extern vm_offset_t ppc_kvm_size; #define VM_KERN_ADDRESS_SIZE (ppc_kvm_size) #define VM_MAX_KERNEL_ADDRESS ((vm_offset_t)((KERNEL_SR << ADDR_SR_SHFT) \ + SEGMENT_LENGTH)) #define VM_KMEM_SIZE (NKMEMCLUSTERS * PAGE_SIZE) #define VM_MBUF_SIZE (NMBCLUSTERS * PAGE_SIZE) #define VM_PHYS_SIZE (USRIOSIZE * PAGE_SIZE) struct pmap_physseg { struct pv_entry *pvent; char *attrs; /* NULL ??? */ }; #define VM_PHYSSEG_MAX 32 /* actually we could have this many segments */ #define VM_PHYSSEG_STRAT VM_PSTRAT_BSEARCH #define VM_PHYSSEG_NOADD /* can't add RAM after vm_mem_init */ #define VM_NFREELIST 1 #define VM_FREELIST_DEFAULT 0 #endif
{ "content_hash": "b26b927413e52c8a2526fffd6cacefe3", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 79, "avg_line_length": 34.09322033898305, "alnum_prop": 0.7293064876957495, "repo_name": "MarginC/kame", "id": "e402f26b52c84bc4d5d785b98e684ba116aad9ed", "size": "4023", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "openbsd/sys/arch/macppc/include/vmparam.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Arc", "bytes": "7491" }, { "name": "Assembly", "bytes": "14375563" }, { "name": "Awk", "bytes": "313712" }, { "name": "Batchfile", "bytes": "6819" }, { "name": "C", "bytes": "356715789" }, { "name": "C++", "bytes": "4231647" }, { "name": "DIGITAL Command Language", "bytes": "11155" }, { "name": "Emacs Lisp", "bytes": "790" }, { "name": "Forth", "bytes": "253695" }, { "name": "GAP", "bytes": "9964" }, { "name": "Groff", "bytes": "2220485" }, { "name": "Lex", "bytes": "168376" }, { "name": "Logos", "bytes": "570213" }, { "name": "Makefile", "bytes": "1778847" }, { "name": "Mathematica", "bytes": "16549" }, { "name": "Objective-C", "bytes": "529629" }, { "name": "PHP", "bytes": "11283" }, { "name": "Perl", "bytes": "151251" }, { "name": "Perl6", "bytes": "2572" }, { "name": "Ruby", "bytes": "7283" }, { "name": "Scheme", "bytes": "76872" }, { "name": "Shell", "bytes": "583253" }, { "name": "Stata", "bytes": "408" }, { "name": "Yacc", "bytes": "606054" } ], "symlink_target": "" }
package com.intellij.openapi.vcs.history; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.vcs.AbstractVcs; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.impl.VcsBackgroundableActions; import com.intellij.util.Alarm; import com.intellij.util.concurrency.SequentialTaskExecutor; import com.intellij.vcs.history.VcsHistoryProviderEx; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; /** * Refreshes file history. * * @author irengrig * @author Kirill Likhodedov */ public class FileHistoryRefresher implements FileHistoryRefresherI { @NotNull private static final ExecutorService ourExecutor = SequentialTaskExecutor.createSequentialApplicationPoolExecutor("File History Refresh"); @NotNull private final FileHistorySessionPartner mySessionPartner; @NotNull private final VcsHistoryProvider myVcsHistoryProvider; @NotNull private final FilePath myPath; @NotNull private final AbstractVcs myVcs; @Nullable private final VcsRevisionNumber myStartingRevisionNumber; private boolean myFirstTime = true; public FileHistoryRefresher(@NotNull VcsHistoryProvider vcsHistoryProvider, @NotNull FilePath path, @NotNull AbstractVcs vcs) { this(vcsHistoryProvider, path, null, vcs); } public FileHistoryRefresher(@NotNull VcsHistoryProviderEx vcsHistoryProvider, @NotNull FilePath path, @Nullable VcsRevisionNumber startingRevisionNumber, @NotNull AbstractVcs vcs) { this((VcsHistoryProvider)vcsHistoryProvider, path, startingRevisionNumber, vcs); } private FileHistoryRefresher(@NotNull VcsHistoryProvider vcsHistoryProvider, @NotNull FilePath path, @Nullable VcsRevisionNumber startingRevisionNumber, @NotNull AbstractVcs vcs) { myVcsHistoryProvider = vcsHistoryProvider; myPath = path; myVcs = vcs; myStartingRevisionNumber = startingRevisionNumber; mySessionPartner = new FileHistorySessionPartner(vcsHistoryProvider, path, startingRevisionNumber, vcs, this); RefreshRequest request = new RefreshRequest(20_000, mySessionPartner); request.schedule(); } @NotNull public static FileHistoryRefresherI findOrCreate(@NotNull VcsHistoryProvider vcsHistoryProvider, @NotNull FilePath path, @NotNull AbstractVcs vcs) { FileHistoryRefresherI refresher = FileHistorySessionPartner.findExistingHistoryRefresher(vcs.getProject(), path, null); return refresher == null ? new FileHistoryRefresher(vcsHistoryProvider, path, vcs) : refresher; } @NotNull public static FileHistoryRefresherI findOrCreate(@NotNull VcsHistoryProviderEx vcsHistoryProvider, @NotNull FilePath path, @NotNull AbstractVcs vcs, @Nullable VcsRevisionNumber startingRevisionNumber) { FileHistoryRefresherI refresher = FileHistorySessionPartner.findExistingHistoryRefresher(vcs.getProject(), path, startingRevisionNumber); return refresher == null ? new FileHistoryRefresher(vcsHistoryProvider, path, startingRevisionNumber, vcs) : refresher; } @Override public void selectContent() { mySessionPartner.createOrSelectContent(); } @Override public boolean isInRefresh() { return VcsCachingHistory.getHistoryLock(myVcs, VcsBackgroundableActions.CREATE_HISTORY_SESSION, myPath, myStartingRevisionNumber) .isLocked(); } /** * @param canUseCache */ @Override public void refresh(boolean canUseCache) { mySessionPartner.beforeRefresh(); if (myVcsHistoryProvider instanceof VcsHistoryProviderEx && myStartingRevisionNumber != null) { VcsCachingHistory.collectInBackground(myVcs, myPath, myStartingRevisionNumber, mySessionPartner); } else { boolean collectedFromCache = false; if (myFirstTime) { collectedFromCache = VcsCachingHistory.collectFromCache(myVcs, myPath, mySessionPartner); } if (!collectedFromCache) { VcsCachingHistory.collectInBackground(myVcs, myPath, mySessionPartner, canUseCache); } } myFirstTime = false; } private class RefreshRequest implements Runnable { @NotNull private final Alarm myUpdateAlarm; private final int myDelayMillis; @Nullable Future<?> myLastTask; public RefreshRequest(int delayMillis, @NotNull Disposable parent) { myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, parent); myDelayMillis = delayMillis; } public void run() { if (myLastTask != null) { myLastTask.cancel(false); } if (myVcs.getProject().isDisposed()) { return; } myUpdateAlarm.cancelAllRequests(); if (myUpdateAlarm.isDisposed()) return; schedule(); if (!ApplicationManager.getApplication().isActive()) return; myLastTask = ourExecutor.submit(() -> { if (!myUpdateAlarm.isDisposed() && mySessionPartner.shouldBeRefreshed()) { ApplicationManager.getApplication().invokeLater(() -> refresh(true)); } }); } public void schedule() { myUpdateAlarm.addRequest(this, myDelayMillis); } } }
{ "content_hash": "beed89b9be2bc25403b02e1658f47a73", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 133, "avg_line_length": 38.12751677852349, "alnum_prop": 0.6930117936982926, "repo_name": "sabi0/intellij-community", "id": "cd4c7f35c512fff8c50db15421d88374042574a4", "size": "6281", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryRefresher.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.esri.geoevent.solutions.processor.rangefan; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.esri.ges.core.component.ComponentException; import com.esri.ges.core.property.PropertyException; import com.esri.ges.manager.geoeventdefinition.GeoEventDefinitionManager; import com.esri.ges.processor.GeoEventProcessor; import com.esri.ges.processor.GeoEventProcessorServiceBase; public class RangeFanProcessorService extends GeoEventProcessorServiceBase { public GeoEventDefinitionManager manager; private static final Log LOG = LogFactory .getLog(RangeFanProcessorService.class); public RangeFanProcessorService() throws PropertyException { definition = new RangeFanProcessorDefinition(); } @Override public GeoEventProcessor create() { try { return new RangeFanProcessor(definition); } catch (ComponentException e) { LOG.error("Rangefan processor"); LOG.error(e.getMessage()); LOG.error(e.getStackTrace()); return null; } catch (Exception e) { LOG.error("Rangefan processor"); LOG.error(e.getMessage()); LOG.error(e.getStackTrace()); return null; } } }
{ "content_hash": "09393102bcc2bb005988caf124d069a3", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 76, "avg_line_length": 29.075, "alnum_prop": 0.7815993121238177, "repo_name": "Esri/solutions-geoevent-java", "id": "14185ec4a42e1ab1982bac031b766b59a75af95b", "size": "1864", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "solutions-geoevent/processors/rangefan-processor/src/main/java/com/esri/geoevent/solutions/processor/rangefan/RangeFanProcessorService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "138" }, { "name": "FreeMarker", "bytes": "4208" }, { "name": "HTML", "bytes": "534" }, { "name": "Java", "bytes": "1605316" }, { "name": "Python", "bytes": "110579" } ], "symlink_target": "" }
using System.Windows; using Microsoft.Win32; namespace HtmlDownloader { class DefaultDialogService : IDialogService { public string FilePath { get; set; } public bool OpenFileDialog() { OpenFileDialog openFileDialog = new OpenFileDialog() { InitialDirectory = @"d:\", Filter = "HTML (*.html)|*.html|Все файлы (*.*)|*.*", Multiselect = false, ValidateNames = true, }; if (openFileDialog.ShowDialog() == true) { FilePath = openFileDialog.FileName; return true; } // if return false; } // OpenFileDialog public bool SaveFileDialog() { SaveFileDialog saveFileDialog = new SaveFileDialog() { InitialDirectory = @"d:\", Filter = "HTML (*.html)|*.html|Все файлы (*.*)|*.*", ValidateNames = true }; if (saveFileDialog.ShowDialog() == true) { FilePath = saveFileDialog.FileName; return true; } // if return false; } // SaveFileDialog public void ShowError(string message) { MessageBox.Show(message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } // ShowError } // class DefaultDialogService } // HtmlDownloader
{ "content_hash": "95acb6793486a7281c9a01155125d638", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 91, "avg_line_length": 32.18181818181818, "alnum_prop": 0.5211864406779662, "repo_name": "AlexeyBuryanov/EducationalProjects", "id": "28b12fb8bd6e7855c564544f3c90bc3f2e5f9e59", "size": "1440", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WPF/HtmlDownloader/HtmlDownloader/Service/DefaultDialogService.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "29755" }, { "name": "C#", "bytes": "296301" }, { "name": "C++", "bytes": "230213" }, { "name": "CSS", "bytes": "10011" }, { "name": "HTML", "bytes": "679" }, { "name": "Hack", "bytes": "22936" }, { "name": "Java", "bytes": "142884" }, { "name": "PHP", "bytes": "64708" }, { "name": "PLSQL", "bytes": "3406" }, { "name": "SQLPL", "bytes": "11249" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2011 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. --> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:state_window_focused="false" android:state_enabled="true" android:drawable="@drawable/btn_radio_on_holo_dark_green" /> <item android:state_checked="false" android:state_window_focused="false" android:state_enabled="true" android:drawable="@drawable/btn_radio_off_holo_dark_green" /> <item android:state_checked="true" android:state_pressed="true" android:state_enabled="true" android:drawable="@drawable/btn_radio_on_pressed_holo_dark_green" /> <item android:state_checked="false" android:state_pressed="true" android:state_enabled="true" android:drawable="@drawable/btn_radio_off_pressed_holo_dark_green" /> <item android:state_checked="true" android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/btn_radio_on_focused_holo_dark_green" /> <item android:state_checked="false" android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/btn_radio_off_focused_holo_dark_green" /> <item android:state_checked="false" android:state_enabled="true" android:drawable="@drawable/btn_radio_off_holo_dark_green" /> <item android:state_checked="true" android:state_enabled="true" android:drawable="@drawable/btn_radio_on_holo_dark" /> <!-- Disabled states --> <item android:state_checked="true" android:state_window_focused="false" android:drawable="@drawable/btn_radio_on_disabled_holo_dark_green" /> <item android:state_checked="false" android:state_window_focused="false" android:drawable="@drawable/btn_radio_off_disabled_holo_dark_green" /> <item android:state_checked="true" android:state_focused="true" android:drawable="@drawable/btn_radio_on_disabled_focused_holo_dark_green" /> <item android:state_checked="false" android:state_focused="true" android:drawable="@drawable/btn_radio_off_disabled_focused_holo_dark_green" /> <item android:state_checked="false" android:drawable="@drawable/btn_radio_off_disabled_holo_dark_green" /> <item android:state_checked="true" android:drawable="@drawable/btn_radio_on_disabled_holo_dark_green" /> </selector>
{ "content_hash": "cb8ed91529d6f1b566038963f61a1e2e", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 110, "avg_line_length": 51.59322033898305, "alnum_prop": 0.6964520367936925, "repo_name": "jonathangerbaud/Klyph", "id": "b53db7d1175f43b3a8defe76337ceade75a4b2b1", "size": "3044", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Klyph/res/drawable/btn_radio_holo_dark_green.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "3871051" } ], "symlink_target": "" }
<div id="__id__" class="__class__"> <a class="bx-def-valign-center" href="__href__"<bx_if:show_onclick> onclick="__onclick__"</bx_if:show_onclick>> <bx_repeat:profiles>__icon__</bx_repeat:profiles> <bx_if:show_icon> <div class="sys-action-counter-icon __style_prefix__-counter-icon bx-def-icon-size bx-def-align-center"><i class="__style_prefix__-counter-icon sys-icon comment"></i></div> </bx_if:show_icon> <div class="bx-def-margin-sec-left-auto">__content__</div> </a> </div>
{ "content_hash": "61a84700c11c48c6f321f1487825ef11", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 184, "avg_line_length": 59.77777777777778, "alnum_prop": 0.5966542750929368, "repo_name": "unaio/una", "id": "4c16e40f7c08cf09cd43d6dc1d5bf824d5295f03", "size": "538", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "upgrade/files/13.0.0.A2-13.0.0.A3/files/template/comment_counter.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9522763" }, { "name": "Dockerfile", "bytes": "2367" }, { "name": "HTML", "bytes": "6194660" }, { "name": "JavaScript", "bytes": "24733694" }, { "name": "Less", "bytes": "3020615" }, { "name": "Makefile", "bytes": "1196" }, { "name": "PHP", "bytes": "158741504" }, { "name": "Ruby", "bytes": "210" }, { "name": "Shell", "bytes": "3327" }, { "name": "Smarty", "bytes": "3461" } ], "symlink_target": "" }
import check from '../core/check'; import gulp from 'gulp'; import buildRunner from '../execution/buildRunner'; function generatePhaseTasks({ projects, lifecycle, watchEnabled }) { check.nonEmptyArray('projects', projects); check.definedObject('lifecycle', lifecycle); check.definedBoolean('enableWatch', watchEnabled); lifecycle.phases.forEach((targetPhase) => { createGulpTask(projects, lifecycle, targetPhase.id, watchEnabled); }); } function createGulpTask(projects, lifecycle, targetPhaseId, watchEnabled) { gulp.task(targetPhaseId, () => { const phaseIds = lifecycle.getPhasePath(targetPhaseId); const runner = buildRunner.create(watchEnabled); return runner.run(projects, lifecycle, phaseIds); }) } export default { generate: generatePhaseTasks }
{ "content_hash": "6714764522b7c6139f0388b7b8a3f2de", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 75, "avg_line_length": 28.74074074074074, "alnum_prop": 0.7603092783505154, "repo_name": "xipcode/xipcode", "id": "1bda29564103c9b0b4e3150d04cd488ccf08763b", "size": "776", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xipcode/src/gulp/phaseTasksGenerator.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "936" }, { "name": "JavaScript", "bytes": "880984" }, { "name": "Shell", "bytes": "480" } ], "symlink_target": "" }
package org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals; import javax.annotation.Nonnull; import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringContent; import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiElementImpl; import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil; import com.intellij.lang.ASTNode; import com.intellij.psi.LiteralTextEscaper; import com.intellij.psi.PsiLanguageInjectionHost; /** * @author Max Medvedev */ public class GrStringContentImpl extends GroovyPsiElementImpl implements GrStringContent, PsiLanguageInjectionHost { public GrStringContentImpl(@Nonnull ASTNode node) { super(node); } @Override public String getValue() { final String text = getText(); StringBuilder chars = new StringBuilder(text.length()); boolean result = GrStringUtil.parseStringCharacters(text, chars, null); return result ? chars.toString() : null; } @Override public boolean isValidHost() { return getValue() != null; } @Override public GrStringContentImpl updateText(@Nonnull String text) { if (getFirstChild() != null) { getFirstChild().delete(); } getNode().addLeaf(GroovyTokenTypes.mGSTRING_CONTENT, text, null); return this; } @Nonnull @Override public LiteralTextEscaper<? extends PsiLanguageInjectionHost> createLiteralTextEscaper() { return new GrLiteralEscaper(this); } }
{ "content_hash": "55347fe2f980a448a30e4a4b422f28bd", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 116, "avg_line_length": 30.979591836734695, "alnum_prop": 0.7628458498023716, "repo_name": "consulo/consulo-groovy", "id": "16d176178f2b99193a504c30befc6dba431b8517", "size": "2118", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "groovy-psi/src/main/java/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/literals/GrStringContentImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "902456" }, { "name": "HTML", "bytes": "67017" }, { "name": "Java", "bytes": "7813970" }, { "name": "Lex", "bytes": "61130" } ], "symlink_target": "" }
<?php require_once __DIR__ . '/../vendor/autoload.php'; // Autoload files using Composer autoload use HelloWorld\SayHello; echo SayHello::world(); Go to the terminal (or create a PHP web server inside "tests" dir) and type: php tests/test.php
{ "content_hash": "7fa15d82da78c30572012ddba3701bed", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 91, "avg_line_length": 25, "alnum_prop": 0.712, "repo_name": "kbaylan/test", "id": "1e4797bb5fd31a45460987e0ebd27462c82bb7fb", "size": "250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "523" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Modelo; import Visao.TelaInicial; import javax.swing.JFrame; /** * * @author Pessoal */ public class Principal { public static void main(String[] args) { Visao.TelaInicial tl = new TelaInicial(); tl.setVisible(true); tl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
{ "content_hash": "dac4417a6ff61abc9ce697f4dcf97e9c", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 79, "avg_line_length": 24, "alnum_prop": 0.6590909090909091, "repo_name": "lidiaa/spaspace", "id": "8e175b98681aa135f0e3c89c751f9e3f990c1d64", "size": "528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Modelo/Principal.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "428232" } ], "symlink_target": "" }
#include <stdio.h> #include <string.h> #include <array> #include <vector> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <functional> #include <string> #include <SDL.h> #include "imgui/imgui.h" #include "gpuvis_macros.h" #include "stlini.h" #include "trace-cmd/trace-read.h" #include "gpuvis_utils.h" #include "gpuvis.h" static const struct { const char *leftstr; const char *rightstr; } s_pairs[] = { { "[Compositor Client] Submit Left", "[Compositor Client] Submit End" }, { "[Compositor Client] Submit Right", "[Compositor Client] Submit End" }, { "[Compositor Client] PostPresentHandoff Begin", "[Compositor Client] PostPresentHandoff End" }, { "[Compositor] Before wait query", "[Compositor] After wait query" }, { "[Compositor] Begin Present(wait)", "[Compositor] End Present" }, { "[Compositor] Begin Present(nowait)", "[Compositor] End Present" }, { "[Compositor] Before flush", "[Compositor] After flush" }, { "[Compositor] Sleep - begin: 0", "[Compositor] Sleep - end" }, { "[Compositor] Sleep - begin: 6", "[Compositor] Sleep - end" }, { "[Compositor] Begin Running Start", "[Compositor] End Running Start" }, { "[Compositor] Mirror Begin Present", "[Compositor] Mirror End Present" }, { "[Compositor] Before flush: Graphics", "[Compositor] After flush: Graphics" }, { "[Compositor] Before flush: Compute", "[Compositor] After flush: Compute" }, { "[Compositor Client] Flush (D3D11) - Begin", "[Compositor Client] Flush (D3D11) - End" }, { "[Compositor Client] PostPresentHandoff begin", "[Compositor Client] PostPresentHandoff end" }, { "[Compositor Client] Begin AcquireSync", "[Compositor Client] End AcquireSync" }, { "[Compositor Client] Begin ReleaseSync", "[Compositor Client] End ReleaseSync" }, { "[NvEnc]CalculateMotion run(begin)", "[NvEnc]CalculateMotion run(end)" }, { "[NvEnc]MapResource(begin)", "[NvEnc]MapResource(end)" }, { "[NvEnc]Lock output(begin)", "[NvEnc]Lock output(end)" }, { "[NewFrameHandler] Begin AcquireSync", "[NewFrameHandler] End AcquireSync" }, { "[NewFrameHandler] Begin ReleaseSync", "[NewFrameHandler] End ReleaseSync" }, }; static void init_ftrace_pairs( std::vector< TraceEvents::ftrace_pair_t > &ftrace_pairs ) { for ( size_t i = 0; i < ARRAY_SIZE( s_pairs ); i++ ) { TraceEvents::ftrace_pair_t pair; pair.leftstr = s_pairs[ i ].leftstr; pair.rightstr = s_pairs[ i ].rightstr; pair.lefthashval = hashstr32( pair.leftstr ); pair.righthashval = hashstr32( pair.rightstr ); ftrace_pairs.push_back( pair ); } // Sort ftrace print event IDs based on ts start locations auto cmp = [&]( const TraceEvents::ftrace_pair_t &lx, const TraceEvents::ftrace_pair_t &rx ) { return ( lx.lefthashval < rx.lefthashval ); }; std::sort( ftrace_pairs.begin(), ftrace_pairs.end(), cmp ); } /* [Compositor Client] Received Idx ### [Compositor Client] WaitGetPoses Begin ThreadId=#### [Compositor Client] WaitGetPoses End ThreadId=#### [Compositor] Detected dropped frames: ### [Compositor] frameTimeout( ### ms ) [Compositor] NewFrame idx=#### [Compositor] Predicting( ##.###### ms ) [Compositor] Re-predicting( ##.###### ms ) [Compositor] TimeSinceLastVSync: #.######(#####) */ static const char *s_buf_prefixes[] = { "[Compositor Client] Received Idx ", "[Compositor Client] WaitGetPoses ", "[Compositor] frameTimeout( ", "[Compositor] Predicting( ", "[Compositor] Re-predicting( ", "[Compositor Client] PostPresentHandoff ", "[Compositor] Present() ", }; // ftrace print event information enum bufvar_t { bufvar_ltime, bufvar_dtime, bufvar_lduration, bufvar_duration, bufvar_begin_ctx, bufvar_end_ctx, bufvar_begin_gctx, bufvar_end_gctx, bufvar_equal, bufvar_prefix, bufvar_Max }; static struct { const char *var; size_t len; } s_buf_vars[] = { { "ltime=", 6 }, { "dtime=", 6 }, { "lduration=", 10 }, { "duration=", 9 }, { "begin_ctx=", 10 }, { "end_ctx=", 8 }, { "begin_gctx=", 11 }, { "end_gctx=", 9 }, }; static const char *find_buf_var( const char *buf, bufvar_t *bufvar ) { const char *var; // If we find any of our print variables, use that as buf end for ( size_t i = 0; i <= bufvar_end_ctx; i++ ) { var = strncasestr( buf, s_buf_vars[ i ].var, s_buf_vars[ i ].len ); if ( var ) { *bufvar = ( bufvar_t )i; return var + s_buf_vars[ i ].len; } } // Search for : or = var = strpbrk( buf, ":=" ); if ( var ) { *bufvar = bufvar_equal; return var + 1; } // No colon - try to find one of our buf prefixes for ( size_t i = 0; i < ARRAY_SIZE( s_buf_prefixes ); i++ ) { size_t prefixlen = strlen( s_buf_prefixes[ i ] ); if ( !strncasecmp( buf, s_buf_prefixes[ i ], prefixlen ) ) { *bufvar = bufvar_prefix; return buf + prefixlen; } } *bufvar = bufvar_Max; return NULL; } static const char *trim_ftrace_print_buf( char ( &newbuf )[ TRACE_BUF_SIZE ], const char *buf, const char *buf_end, size_t len ) { const char *tok1 = buf_end; const char *tok0 = buf_end - len; // Read to end of token value. // duration=-1234.5 ms if ( *tok1 == '-' ) tok1++; while ( isdigit( *tok1 ) ) tok1++; if ( *tok1 == '.' ) { tok1++; while ( isdigit( *tok1 ) ) tok1++; } if ( tok1[ 0 ] == 'm' && tok1[ 1 ] == 's' ) tok1 += 2; else if ( tok1[ 0 ] == ' ' && tok1[ 1 ] == 'm' && tok1[ 2 ] == 's' ) tok1 += 3; if ( ( tok0 > buf ) && ( tok0[ -1 ] == '(' ) && ( *tok1 == ')' ) ) { tok0--; tok1++; } if ( ( tok0 > buf ) && isspace( tok0[ -1 ] ) ) tok0--; memmove( newbuf, buf, tok0 - buf ); memmove( newbuf + ( tok0 - buf ), tok1, strlen( tok1 ) + 1 ); return newbuf; } ftrace_row_info_t *TraceEvents::get_ftrace_row_info_pid( int pid, bool add ) { ftrace_row_info_t *row_info = m_ftrace.row_info.get_val( pid ); if ( !row_info && add ) { row_info = m_ftrace.row_info.get_val_create( pid ); if ( pid & 0xffff ) row_info->pid = pid; else row_info->tgid = pid >> 16; } return row_info; } ftrace_row_info_t *TraceEvents::get_ftrace_row_info_tgid( int tgid, bool add ) { return get_ftrace_row_info_pid( tgid << 16, add ); } ftrace_row_info_t *TraceEvents::get_ftrace_row_info( const char *row_name ) { ftrace_row_info_t *ftrace_row_info = NULL; if ( !strcmp( row_name, "print" ) ) ftrace_row_info = get_ftrace_row_info_pid( -1 ); else if ( !strncmp( row_name, "print pid:", 10 ) ) ftrace_row_info = get_ftrace_row_info_pid( atoi( row_name + 10 ) ); else if ( !strncmp( row_name, "print tgid:", 11 ) ) ftrace_row_info = get_ftrace_row_info_tgid( atoi( row_name + 11 ) ); return ftrace_row_info; } // Called by TraceEvents::new_event_cb() when adding new events to m_events array void TraceEvents::new_event_ftrace_print( trace_event_t &event ) { int pid = event.pid; int64_t ts_offset = 0; bool do_find_buf_var = true; bufvar_t bufvar = bufvar_Max; char newbuf[ TRACE_BUF_SIZE ]; trace_event_t *add_event = &event; const char *orig_buf = get_event_field_val( event, "buf" ); const char *buf = orig_buf; bool has_print_ltime = false; bool has_print_dtime = false; if ( m_ftrace.ftrace_pairs.empty() ) init_ftrace_pairs( m_ftrace.ftrace_pairs ); // Default color for ctx events without sibling event.color = 0xffff00ff; event.color_index = 0; event.seqno = UINT32_MAX; // bufvar_ltime is first in enumeration, so if ltime= is present, // it should be the first bufvar returned STATIC_ASSERT( bufvar_ltime == 0 ); const char *var_ltime = NULL; var_ltime = find_buf_var( buf, &bufvar ); if ( bufvar == bufvar_ltime ) { event.ts = atoll( var_ltime ); // Remove "ltime=XXX", etc from buf buf = trim_ftrace_print_buf( newbuf, buf, var_ltime, s_buf_vars[ bufvar ].len ); has_print_ltime = true; } // bufvar_dtime is second in enumeration, so if dtime= is present, // it should be the second bufvar returned. It basically mimics // the behavior of ltime. ltime and dtime are mututally exclusive. STATIC_ASSERT( bufvar_dtime == 1 ); const char *var_dtime = NULL; var_dtime = find_buf_var( buf, &bufvar ); if ( bufvar == bufvar_dtime ) { event.ts += atoll( var_dtime ); // Remove "dtime=XXX", etc from buf buf = trim_ftrace_print_buf( newbuf, buf, var_dtime, s_buf_vars[ bufvar ].len ); has_print_dtime = true; } bufvar = bufvar_Max; const char *tid_offset_str = strncasestr( buf, "tid=", 4 ); if ( tid_offset_str ) { tid_offset_str += 4; event.pid = atoi( tid_offset_str ); buf = trim_ftrace_print_buf( newbuf, buf, tid_offset_str, 4 ); } const char *ts_offset_str = strncasestr( buf, "offset=", 7 ); if ( ts_offset_str ) { ts_offset_str += 7; ts_offset = atoll( ts_offset_str ); buf = trim_ftrace_print_buf( newbuf, buf, ts_offset_str, 7 ); } if ( !tid_offset_str && !ts_offset_str ) { // Hash the buf string uint32_t hashval = hashstr32( buf ); uint64_t key = ( ( uint64_t )event.pid << 32 ); // Try to find this hash+pid in the pairs_ctx map uint32_t *event0id = m_ftrace.pairs_ctx.get_val( key | hashval ); if ( event0id ) { // Found hash+pid in duration map. Value is start event id. trace_event_t &event0 = m_events[ *event0id ]; event0.id_start = event.id; event0.duration = event.ts - event0.ts; event0.color_index = hashval; event.color_index = hashval; m_ftrace.pairs_ctx.erase_key( key | hashval ); m_ftrace.print_ts_max = std::max< int64_t >( m_ftrace.print_ts_max, event0.duration ); // Don't add event (we added event0 already) add_event = NULL; do_find_buf_var = false; } else { ftrace_pair_t x = { hashval }; auto cmp = [&]( const ftrace_pair_t &lx, const ftrace_pair_t &rx ) { return ( lx.lefthashval < rx.lefthashval ); }; auto it = std::lower_bound( m_ftrace.ftrace_pairs.begin(), m_ftrace.ftrace_pairs.end(), x, cmp ); // Try to find this starting hashval in our ftrace_pairs array if ( ( it != m_ftrace.ftrace_pairs.end() ) && ( it->lefthashval == hashval ) ) { // Found - add right hashval or'd with pid pointing to this event id m_ftrace.pairs_ctx.m_map[ key | it->righthashval ] = event.id; do_find_buf_var = false; } } } const char *var = do_find_buf_var ? find_buf_var( buf, &bufvar ) : NULL; if ( bufvar >= bufvar_lduration && bufvar <= bufvar_end_gctx ) { // This is a duration or ctx print event... if ( bufvar == bufvar_lduration ) event.duration = atoll( var ); else if ( bufvar == bufvar_duration ) event.duration = ( int64_t )( atof( var ) * NSECS_PER_MSEC ); else event.seqno = strtoul( var, 0, 10 ); // Remove "duration=XXX", etc from buf buf = trim_ftrace_print_buf( newbuf, buf, var, s_buf_vars[ bufvar ].len ); // Set color index to hash of new string // If the string is something like "sort_name_components: 17343", then only // use the "set_name_components: " portion for the hash so they all get // the same color. const char *colon = strchr( buf, ':' ); size_t len = colon ? ( colon - buf ) : strlen( buf ); event.color_index = hashstr32( buf, len ); if ( bufvar == bufvar_lduration || bufvar == bufvar_duration ) { if ( event.duration < 0 ) { ts_offset += event.duration; event.duration = -event.duration; } } else { uint64_t key = 0; if ( ( bufvar == bufvar_begin_ctx ) || ( bufvar == bufvar_end_ctx ) ) key = ( uint64_t )pid << 32; key |= event.seqno; if ( ( bufvar == bufvar_begin_ctx ) || ( bufvar == bufvar_begin_gctx ) ) m_ftrace.begin_ctx.get_val( key, event.id ); else m_ftrace.end_ctx.get_val( key, event.id ); // We're only going to add a single event for the begin/end ctx pairs add_event = NULL; uint32_t *begin_eventid = m_ftrace.begin_ctx.get_val( key ); uint32_t *end_eventid = m_ftrace.end_ctx.get_val( key ); if ( begin_eventid && end_eventid ) { // We have a begin/end pair for this ctx trace_event_t &event0 = m_events[ *begin_eventid ]; const trace_event_t &event1 = m_events[ *end_eventid ]; event0.id_start = event1.id; event0.duration = event1.ts - event0.ts; // Handle the case where a begin_ctx has no text, or vice versa if ( buf[ 0 ] ) event0.color_index = event.color_index; else if ( event.id == *begin_eventid ) event0.color_index = event1.color_index; else event0.color_index = event0.color_index; // Erase all knowledge of this ctx so it can be reused m_ftrace.begin_ctx.erase_key( event.seqno ); m_ftrace.end_ctx.erase_key( event.seqno ); add_event = &event0; } } } else if ( bufvar < bufvar_Max ) { event.color_index = hashstr32( buf ); } // If this event's timestamp has been injected or modified by // the print buf, add an asterisk to it's text if ( has_print_ltime || has_print_dtime ) { assert( buf == newbuf ); size_t len = strlen( newbuf ); const size_t size = sizeof( newbuf ); if ( len < size - 2 ) { newbuf[ len ] = '*'; newbuf[ len + 1 ] = 0; } } if ( buf == newbuf ) { event_field_t *field = get_event_field( event, "buf" ); if ( add_event && add_event->has_duration() && ( add_event->duration >= 1 * NSECS_PER_MSEC ) ) { size_t len = strlen( newbuf ); double val = add_event->duration * ( 1.0 / NSECS_PER_MSEC ); snprintf( newbuf + len, sizeof( newbuf ) - len, " [%.*lf ms]", 2, val ); newbuf[ sizeof( newbuf ) - 1 ] = 0; } buf = m_strpool.getstr( newbuf ); field->value = buf; #if 0 // Add orig_buf which points to original buf data event_field_t *fields = new event_field_t[ event.numfields + 1 ]; memcpy( fields, event.fields, event.numfields * sizeof( fields[ 0 ] ) ); fields[ event.numfields ].key = m_strpool.getstr( "orig_buf" ); fields[ event.numfields ].value = orig_buf; delete [] event.fields; event.fields = fields; event.numfields++; #endif } if ( add_event ) { print_info_t print_info; const tgid_info_t *tgid_info = tgid_from_pid( pid ); print_info.ts = add_event->ts + ts_offset; print_info.tgid = tgid_info ? tgid_info->tgid : 0; print_info.graph_row_id_pid = 0; print_info.graph_row_id_tgid = 0; print_info.buf = buf; print_info.size = ImVec2( 0, 0 ); // If we have no text, try using the connected event's text if ( !buf[ 0 ] && is_valid_id( add_event->id_start ) ) print_info.buf = get_event_field_val( m_events[ add_event->id ], "buf" ); // Add cached print info for this event m_ftrace.print_info.get_val( add_event->id, print_info ); m_ftrace.print_locs.push_back( add_event->id ); if ( add_event->has_duration() ) m_ftrace.print_ts_max = std::max< int64_t >( m_ftrace.print_ts_max, add_event->duration ); } } // Called by TraceEvents::init() after m_events is filled for second initialization pass. void TraceEvents::calculate_event_print_info() { if ( m_ftrace.print_locs.empty() ) return; // Sort ftrace print event IDs based on ts start locations auto cmp_ts = [&]( const uint32_t lx, const uint32_t rx ) { const print_info_t *lval = m_ftrace.print_info.get_val( lx ); const print_info_t *rval = m_ftrace.print_info.get_val( rx ); return ( lval->ts < rval->ts ); }; std::sort( m_ftrace.print_locs.begin(), m_ftrace.print_locs.end(), cmp_ts ); // Sort ftrace print event IDs based on duration auto cmp_dur = [&]( const uint32_t lx, const uint32_t rx ) { const trace_event_t &lval = m_events[ lx ]; const trace_event_t &rval = m_events[ rx ]; int64_t ldur = lval.has_duration() ? lval.duration : 0; int64_t rdur = rval.has_duration() ? rval.duration : 0; return ( ldur > rdur ); }; std::vector< uint32_t > locs_duration = m_ftrace.print_locs; std::sort( locs_duration.begin(), locs_duration.end(), cmp_dur ); row_pos_t row_pos; ftrace_row_info_t *row_info; util_umap< int, row_pos_t > row_pos_pid; util_umap< int, row_pos_t > row_pos_tgid; // Go through all the ftrace print events with largest durations first for ( uint32_t idx : locs_duration ) { row_pos_t *prow_pos; trace_event_t &event = m_events[ idx ]; print_info_t *print_info = m_ftrace.print_info.get_val( event.id ); int64_t min_ts = print_info->ts; int64_t duration = event.has_duration() ? event.duration : ( 1 * NSECS_PER_MSEC ); int64_t max_ts = min_ts + duration; // Global print row id event.graph_row_id = row_pos.get_row( min_ts, max_ts ); // Pid print row id prow_pos = row_pos_pid.get_val_create( event.pid ); print_info->graph_row_id_pid = prow_pos->get_row( min_ts, max_ts ); row_info = get_ftrace_row_info_pid( event.pid, true ); row_info->rows = std::max< uint32_t >( row_info->rows, prow_pos->m_rows ); row_info->count++; if ( print_info->tgid ) { // Tgid print row id prow_pos = row_pos_tgid.get_val_create( print_info->tgid ); print_info->graph_row_id_tgid = prow_pos->get_row( min_ts, max_ts ); row_info = get_ftrace_row_info_tgid( print_info->tgid, true ); row_info->rows = std::max< uint32_t >( row_info->rows, prow_pos->m_rows ); row_info->count++; } } // Add info for special pid=-1 (all ftrace print events) row_info = get_ftrace_row_info_pid( -1, true ); row_info->rows = row_pos.m_rows; row_info->count = m_ftrace.print_locs.size(); } void TraceEvents::invalidate_ftraceprint_colors() { m_ftrace.text_size_max = -1.0f; } // Called by TraceWin::graph_render_print_timeline() to recalculate text sizes and colors void TraceEvents::update_ftraceprint_colors() { float label_sat = s_clrs().getalpha( col_Graph_PrintLabelSat ); float label_alpha = s_clrs().getalpha( col_Graph_PrintLabelAlpha ); ImU32 color = s_clrs().get( col_FtracePrintText, label_alpha * 255 ); m_ftrace.text_size_max = 0.0f; for ( auto &entry : m_ftrace.print_info.m_map ) { trace_event_t &event = m_events[ entry.first ]; print_info_t &print_info = entry.second; print_info.size = ImGui::CalcTextSize( print_info.buf ); m_ftrace.text_size_max = std::max< float >( print_info.size.x, m_ftrace.text_size_max ); // Mark this event as autogen'd color so it doesn't get overwritten event.flags |= TRACE_FLAG_AUTOGEN_COLOR; if ( event.color_index ) { // If we have a graph row id, use the hashval stored in color_index event.color = imgui_col_from_hashval( event.color_index, label_sat, label_alpha ); if ( is_valid_id( event.id_start ) ) { m_events[ event.id_start ].color = event.color; m_events[ event.id_start ].flags |= TRACE_FLAG_AUTOGEN_COLOR; } } else { event.color = color; } } }
{ "content_hash": "e29ab1d3698ec49cefec4d6a2088ac55", "timestamp": "", "source": "github", "line_count": 635, "max_line_length": 109, "avg_line_length": 32.86771653543307, "alnum_prop": 0.5617363806238321, "repo_name": "mikesart/gpuvis", "id": "5ac499365fb2c2777fcb6cf6c30c2adfbf25d3e2", "size": "22012", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/gpuvis_ftrace_print.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1458327" }, { "name": "C++", "bytes": "2991652" }, { "name": "CMake", "bytes": "34400" }, { "name": "Makefile", "bytes": "8191" }, { "name": "Meson", "bytes": "2408" }, { "name": "Objective-C++", "bytes": "2409" }, { "name": "Shell", "bytes": "996" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; namespace Anarian.Interfaces { public interface IMoveable { // Generic Movements void Move(GameTime gameTime, Vector3 movement); void MoveVertical(GameTime gameTime, float amount); void MoveHorizontal(GameTime gameTime, float amount); void MoveForward(GameTime gameTime, float amount); // Specific Movements void MoveToPosition(GameTime gameTime, Vector3 point); } }
{ "content_hash": "0d417cd9373a8c4ffb1e060240e55800", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 62, "avg_line_length": 23.47826086956522, "alnum_prop": 0.7018518518518518, "repo_name": "KillerrinStudios/Anarian-Game-Engine-MonoGame", "id": "ded95dbb7d39943523ba2b245014da13eed6adf8", "size": "542", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Anarian Game Engine.Shared/Interfaces/IMoveable.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "448862" } ], "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 (version 1.7.0_65) on Wed Sep 03 20:00:50 PDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>AdminProtos.AdminService.BlockingInterface (HBase 0.98.6-hadoop2 API)</title> <meta name="date" content="2014-09-03"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="AdminProtos.AdminService.BlockingInterface (HBase 0.98.6-hadoop2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AdminProtos.AdminService.BlockingInterface.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.Interface.html" title="interface in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html" target="_top">Frames</a></li> <li><a href="AdminProtos.AdminService.BlockingInterface.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.hadoop.hbase.protobuf.generated</div> <h2 title="Interface AdminProtos.AdminService.BlockingInterface" class="title">Interface AdminProtos.AdminService.BlockingInterface</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../../../org/apache/hadoop/hbase/regionserver/HRegionServer.html" title="class in org.apache.hadoop.hbase.regionserver">HRegionServer</a></dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.AdminService</a></dd> </dl> <hr> <br> <pre>public static interface <span class="strong">AdminProtos.AdminService.BlockingInterface</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</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> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.CloseRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.CloseRegionResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#closeRegion(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest)">closeRegion</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.CloseRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.CloseRegionRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.CompactRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.CompactRegionResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#compactRegion(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CompactRegionRequest)">compactRegion</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.CompactRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.CompactRegionRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.FlushRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.FlushRegionResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#flushRegion(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.FlushRegionRequest)">flushRegion</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.FlushRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.FlushRegionRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetOnlineRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetOnlineRegionResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#getOnlineRegion(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetOnlineRegionRequest)">getOnlineRegion</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetOnlineRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetOnlineRegionRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetRegionInfoResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetRegionInfoResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#getRegionInfo(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest)">getRegionInfo</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetRegionInfoRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetRegionInfoRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetServerInfoResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetServerInfoResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#getServerInfo(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetServerInfoRequest)">getServerInfo</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetServerInfoRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetServerInfoRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetStoreFileResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetStoreFileResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#getStoreFile(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileRequest)">getStoreFile</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetStoreFileRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetStoreFileRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.MergeRegionsResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.MergeRegionsResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#mergeRegions(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.MergeRegionsRequest)">mergeRegions</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.MergeRegionsRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.MergeRegionsRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.OpenRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.OpenRegionResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#openRegion(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.OpenRegionRequest)">openRegion</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.OpenRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.OpenRegionRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.ReplicateWALEntryResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.ReplicateWALEntryResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#replay(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.ReplicateWALEntryRequest)">replay</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.ReplicateWALEntryRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.ReplicateWALEntryRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.ReplicateWALEntryResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.ReplicateWALEntryResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#replicateWALEntry(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.ReplicateWALEntryRequest)">replicateWALEntry</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.ReplicateWALEntryRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.ReplicateWALEntryRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.RollWALWriterResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.RollWALWriterResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#rollWALWriter(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.RollWALWriterRequest)">rollWALWriter</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.RollWALWriterRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.RollWALWriterRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.SplitRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.SplitRegionResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#splitRegion(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.SplitRegionRequest)">splitRegion</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.SplitRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.SplitRegionRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.StopServerResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.StopServerResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#stopServer(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.StopServerRequest)">stopServer</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.StopServerRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.StopServerRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.UpdateFavoredNodesResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.UpdateFavoredNodesResponse</a></code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html#updateFavoredNodes(com.google.protobuf.RpcController,%20org.apache.hadoop.hbase.protobuf.generated.AdminProtos.UpdateFavoredNodesRequest)">updateFavoredNodes</a></strong>(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.UpdateFavoredNodesRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.UpdateFavoredNodesRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getRegionInfo(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getRegionInfo</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetRegionInfoResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetRegionInfoResponse</a>&nbsp;getRegionInfo(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetRegionInfoRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetRegionInfoRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="getStoreFile(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getStoreFile</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetStoreFileResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetStoreFileResponse</a>&nbsp;getStoreFile(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetStoreFileRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetStoreFileRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="getOnlineRegion(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetOnlineRegionRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getOnlineRegion</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetOnlineRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetOnlineRegionResponse</a>&nbsp;getOnlineRegion(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetOnlineRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetOnlineRegionRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="openRegion(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.OpenRegionRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>openRegion</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.OpenRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.OpenRegionResponse</a>&nbsp;openRegion(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.OpenRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.OpenRegionRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="closeRegion(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>closeRegion</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.CloseRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.CloseRegionResponse</a>&nbsp;closeRegion(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.CloseRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.CloseRegionRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="flushRegion(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.FlushRegionRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>flushRegion</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.FlushRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.FlushRegionResponse</a>&nbsp;flushRegion(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.FlushRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.FlushRegionRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="splitRegion(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.SplitRegionRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>splitRegion</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.SplitRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.SplitRegionResponse</a>&nbsp;splitRegion(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.SplitRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.SplitRegionRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="compactRegion(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CompactRegionRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>compactRegion</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.CompactRegionResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.CompactRegionResponse</a>&nbsp;compactRegion(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.CompactRegionRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.CompactRegionRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="mergeRegions(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.MergeRegionsRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>mergeRegions</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.MergeRegionsResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.MergeRegionsResponse</a>&nbsp;mergeRegions(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.MergeRegionsRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.MergeRegionsRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="replicateWALEntry(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.ReplicateWALEntryRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>replicateWALEntry</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.ReplicateWALEntryResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.ReplicateWALEntryResponse</a>&nbsp;replicateWALEntry(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.ReplicateWALEntryRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.ReplicateWALEntryRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="replay(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.ReplicateWALEntryRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>replay</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.ReplicateWALEntryResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.ReplicateWALEntryResponse</a>&nbsp;replay(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.ReplicateWALEntryRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.ReplicateWALEntryRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="rollWALWriter(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.RollWALWriterRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>rollWALWriter</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.RollWALWriterResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.RollWALWriterResponse</a>&nbsp;rollWALWriter(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.RollWALWriterRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.RollWALWriterRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="getServerInfo(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetServerInfoRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getServerInfo</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetServerInfoResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetServerInfoResponse</a>&nbsp;getServerInfo(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.GetServerInfoRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.GetServerInfoRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="stopServer(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.StopServerRequest)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>stopServer</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.StopServerResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.StopServerResponse</a>&nbsp;stopServer(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.StopServerRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.StopServerRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> <a name="updateFavoredNodes(com.google.protobuf.RpcController, org.apache.hadoop.hbase.protobuf.generated.AdminProtos.UpdateFavoredNodesRequest)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>updateFavoredNodes</h4> <pre><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.UpdateFavoredNodesResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.UpdateFavoredNodesResponse</a>&nbsp;updateFavoredNodes(com.google.protobuf.RpcController&nbsp;controller, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.UpdateFavoredNodesRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AdminProtos.UpdateFavoredNodesRequest</a>&nbsp;request) throws com.google.protobuf.ServiceException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>com.google.protobuf.ServiceException</code></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AdminProtos.AdminService.BlockingInterface.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.Interface.html" title="interface in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html" target="_top">Frames</a></li> <li><a href="AdminProtos.AdminService.BlockingInterface.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "62a6d7198c213f67552e21da7516d279", "timestamp": "", "source": "github", "line_count": 473, "max_line_length": 373, "avg_line_length": 75.6046511627907, "alnum_prop": 0.702441206901373, "repo_name": "lshain/hbase-0.98.6-hadoop2", "id": "2488dd50b2f217796c33f5b3ec362eadffd2e03b", "size": "35761", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/devapidocs/org/apache/hadoop/hbase/protobuf/generated/AdminProtos.AdminService.BlockingInterface.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "39965" }, { "name": "JavaScript", "bytes": "1347" }, { "name": "Ruby", "bytes": "260273" }, { "name": "Shell", "bytes": "97997" } ], "symlink_target": "" }
Seven (More) Languages in Seven Weeks Solutions
{ "content_hash": "e3bc9bb7be2554eee75fe2c6de09d609", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 47, "avg_line_length": 48, "alnum_prop": 0.8125, "repo_name": "hemslo/seven-in-seven", "id": "2bb807cca3f8d3db445270aa077d2677bf97f8fc", "size": "65", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1025" }, { "name": "CMake", "bytes": "165" }, { "name": "Clojure", "bytes": "11644" }, { "name": "Elixir", "bytes": "22817" }, { "name": "Elm", "bytes": "9107" }, { "name": "Erlang", "bytes": "3299" }, { "name": "Factor", "bytes": "6087" }, { "name": "Haskell", "bytes": "5908" }, { "name": "Idris", "bytes": "2037" }, { "name": "Io", "bytes": "4680" }, { "name": "Julia", "bytes": "2114" }, { "name": "Lua", "bytes": "9463" }, { "name": "Perl", "bytes": "591" }, { "name": "Prolog", "bytes": "2259" }, { "name": "Ruby", "bytes": "4085" }, { "name": "Scala", "bytes": "5053" } ], "symlink_target": "" }
package com.ntut.killboss.object; import java.util.List; import com.ntut.killboss.Constant; import com.ntut.killboss.FunctionUtilities; import com.ntut.killboss.core.GameView; import com.ntut.killboss.sprite.AnimationReduceHP; import com.ntut.killboss.sprite.Sprite; import android.content.Context; public class ObjectSkill2 extends ObjectSkill { private ObjectSkillShortExist temp; public ObjectSkill2(Context context, List<ObjectSkill> objectSkills) { super(context, objectSkills, Constant.skillDrawbleResourceIDs[1], FunctionUtilities.getRandom(GameView._screenSize.x), 0, true); temp = new ObjectSkillShortExist(_context, GameView._objectSkillsBoss, _x, _y); } @Override protected void update() { if (checkYOutOfBound()) { _objectSkills.remove(this); temp.playAnimation(_x, _y); } else { _y += _speed; } } @Override public void hitSprite(Sprite sprite, GameView gameView) { if (isCollsionWithRect2(_x, _y, bmp.getWidth(), bmp.getHeight(), sprite.get_x(), sprite.get_y(), sprite.get_width(), sprite.get_height())) { sprite.reduceHP(_damage); GameView._animationReduceHP.add(new AnimationReduceHP(gameView, sprite.get_x() + (sprite.get_width() / 2), sprite.get_y() + (sprite.get_height() / 3), -_damage)); _objectSkills.remove(this); } } }
{ "content_hash": "5cadca6a6d5cf827dad20446462c389f", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 72, "avg_line_length": 27.979591836734695, "alnum_prop": 0.6929248723559446, "repo_name": "RammusXu/KillBoss", "id": "91b7bfa9e3ada45313b7104cdb3e1b31a99e9687", "size": "1371", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "KillBoss/src/com/ntut/killboss/object/ObjectSkill2.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "82667" } ], "symlink_target": "" }
package main import ( "encoding/json" "errors" "fmt" "io/ioutil" "net" "os" "runtime" "strconv" "strings" "time" "golang.org/x/net/context" google_protobuf "google/protobuf" "github.com/howeyc/gopass" "github.com/op/go-logging" "github.com/spf13/cobra" "github.com/spf13/viper" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/grpclog" "github.com/openblockchain/obc-peer/events/producer" "github.com/openblockchain/obc-peer/openchain" "github.com/openblockchain/obc-peer/openchain/chaincode" "github.com/openblockchain/obc-peer/openchain/consensus/helper" "github.com/openblockchain/obc-peer/openchain/crypto" "github.com/openblockchain/obc-peer/openchain/ledger/genesis" "github.com/openblockchain/obc-peer/openchain/peer" "github.com/openblockchain/obc-peer/openchain/rest" pb "github.com/openblockchain/obc-peer/protos" ) var logger = logging.MustGetLogger("main") // Constants go here. const chainFuncName = "chaincode" const cmdRoot = "openchain" const undefinedParamValue = "" // The main command describes the service and // defaults to printing the help message. var mainCmd = &cobra.Command{ Use: "obc-peer", } var peerCmd = &cobra.Command{ Use: "peer", Short: "Run openchain peer.", Long: `Runs the openchain peer that interacts with the openchain network.`, PersistentPreRun: func(cmd *cobra.Command, args []string) { openchain.LoggingInit("peer") }, RunE: func(cmd *cobra.Command, args []string) error { return serve(args) }, } var statusCmd = &cobra.Command{ Use: "status", Short: "Status of the openchain peer.", Long: `Outputs the status of the currently running openchain peer.`, PersistentPreRun: func(cmd *cobra.Command, args []string) { openchain.LoggingInit("status") }, RunE: func(cmd *cobra.Command, args []string) error { return status() }, } var stopCmd = &cobra.Command{ Use: "stop", Short: "Stop openchain peer.", Long: `Stops the currently running openchain Peer, disconnecting from the openchain network.`, PersistentPreRun: func(cmd *cobra.Command, args []string) { openchain.LoggingInit("stop") }, Run: func(cmd *cobra.Command, args []string) { stop() }, } var loginCmd = &cobra.Command{ Use: "login", Short: "Login user on CLI.", Long: `Login the local user on CLI. Must supply username parameter.`, PersistentPreRun: func(cmd *cobra.Command, args []string) { openchain.LoggingInit("login") }, RunE: func(cmd *cobra.Command, args []string) error { return login(args) }, } var vmCmd = &cobra.Command{ Use: "vm", Short: "VM functionality of openchain.", Long: `Interact with the VM functionality of openchain.`, PersistentPreRun: func(cmd *cobra.Command, args []string) { openchain.LoggingInit("vm") }, } var vmPrimeCmd = &cobra.Command{ Use: "prime", Short: "Prime the VM functionality of openchain.", Long: `Primes the VM functionality of openchain by preparing the necessary VM construction artifacts.`, RunE: func(cmd *cobra.Command, args []string) error { return stop() }, } // Chaincode-related variables. var ( chaincodeLang string chaincodeCtorJSON string chaincodePath string chaincodeName string chaincodeDevMode bool chaincodeUsr string chaincodeQueryRaw bool chaincodeQueryHex bool ) var chaincodeCmd = &cobra.Command{ Use: chainFuncName, Short: fmt.Sprintf("%s specific commands.", chainFuncName), Long: fmt.Sprintf("%s specific commands.", chainFuncName), PersistentPreRun: func(cmd *cobra.Command, args []string) { openchain.LoggingInit(chainFuncName) }, } var chaincodePathArgumentSpecifier = fmt.Sprintf("%s_PATH", strings.ToUpper(chainFuncName)) var chaincodeDeployCmd = &cobra.Command{ Use: "deploy", Short: fmt.Sprintf("Deploy the specified %s to the network.", chainFuncName), Long: fmt.Sprintf(`Deploy the specified %s to the network.`, chainFuncName), ValidArgs: []string{"1"}, RunE: func(cmd *cobra.Command, args []string) error { return chaincodeDeploy(cmd, args) }, } var chaincodeInvokeCmd = &cobra.Command{ Use: "invoke", Short: fmt.Sprintf("Invoke the specified %s.", chainFuncName), Long: fmt.Sprintf(`Invoke the specified %s.`, chainFuncName), ValidArgs: []string{"1"}, RunE: func(cmd *cobra.Command, args []string) error { return chaincodeInvoke(cmd, args) }, } var chaincodeQueryCmd = &cobra.Command{ Use: "query", Short: fmt.Sprintf("Query using the specified %s.", chainFuncName), Long: fmt.Sprintf(`Query using the specified %s.`, chainFuncName), ValidArgs: []string{"1"}, RunE: func(cmd *cobra.Command, args []string) error { return chaincodeQuery(cmd, args) }, } func main() { runtime.GOMAXPROCS(2) // For environment variables. viper.SetEnvPrefix(cmdRoot) viper.AutomaticEnv() replacer := strings.NewReplacer(".", "_") viper.SetEnvKeyReplacer(replacer) // Define command-line flags that are valid for all obc-peer commands and // subcommands. mainFlags := mainCmd.PersistentFlags() mainFlags.String("logging-level", "", "Default logging level and overrides, see openchain.yaml for full syntax") viper.BindPFlag("logging_level", mainFlags.Lookup("logging-level")) // Set the flags on the peer command. flags := peerCmd.Flags() flags.Bool("peer-tls-enabled", false, "Connection uses TLS if true, else plain TCP") flags.String("peer-tls-cert-file", "testdata/server1.pem", "TLS cert file") flags.String("peer-tls-key-file", "testdata/server1.key", "TLS key file") flags.Int("peer-port", 30303, "Port this peer listens to for incoming connections") flags.Int("peer-gomaxprocs", 2, "The maximum number threads excuting peer code") flags.Bool("peer-discovery-enabled", true, "Whether peer discovery is enabled") flags.BoolVarP(&chaincodeDevMode, "peer-chaincodedev", "", false, "Whether peer in chaincode development mode") viper.BindPFlag("peer_tls_enabled", flags.Lookup("peer-tls-enabled")) viper.BindPFlag("peer_tls_cert_file", flags.Lookup("peer-tls-cert-file")) viper.BindPFlag("peer_tls_key_file", flags.Lookup("peer-tls-key-file")) viper.BindPFlag("peer_port", flags.Lookup("peer-port")) viper.BindPFlag("peer_gomaxprocs", flags.Lookup("peer-gomaxprocs")) viper.BindPFlag("peer_discovery_enabled", flags.Lookup("peer-discovery-enabled")) // Now set the configuration file. viper.SetConfigName(cmdRoot) // Name of config file (without extension) viper.AddConfigPath("./") // Path to look for the config file in err := viper.ReadInConfig() // Find and read the config file if err != nil { // Handle errors reading the config file panic(fmt.Errorf("Fatal error when reading %s config file: %s \n", cmdRoot, err)) } mainCmd.AddCommand(peerCmd) mainCmd.AddCommand(statusCmd) mainCmd.AddCommand(stopCmd) mainCmd.AddCommand(loginCmd) vmCmd.AddCommand(vmPrimeCmd) mainCmd.AddCommand(vmCmd) chaincodeCmd.PersistentFlags().StringVarP(&chaincodeLang, "lang", "l", "golang", fmt.Sprintf("Language the %s is written in", chainFuncName)) chaincodeCmd.PersistentFlags().StringVarP(&chaincodeCtorJSON, "ctor", "c", "{}", fmt.Sprintf("Constructor message for the %s in JSON format", chainFuncName)) chaincodeCmd.PersistentFlags().StringVarP(&chaincodePath, "path", "p", undefinedParamValue, fmt.Sprintf("Path to %s", chainFuncName)) chaincodeCmd.PersistentFlags().StringVarP(&chaincodeName, "name", "n", undefinedParamValue, fmt.Sprintf("Name of the chaincode returned by the deploy transaction")) chaincodeCmd.PersistentFlags().StringVarP(&chaincodeUsr, "username", "u", undefinedParamValue, fmt.Sprintf("Username for chaincode operations when security is enabled")) chaincodeQueryCmd.Flags().BoolVarP(&chaincodeQueryRaw, "raw", "r", false, "If true, output the query value as raw bytes, otherwise format as a printable string") chaincodeQueryCmd.Flags().BoolVarP(&chaincodeQueryHex, "hex", "x", false, "If true, output the query value byte array in hexadecimal. Incompatible with --raw") chaincodeCmd.AddCommand(chaincodeDeployCmd) chaincodeCmd.AddCommand(chaincodeInvokeCmd) chaincodeCmd.AddCommand(chaincodeQueryCmd) mainCmd.AddCommand(chaincodeCmd) // Init the crypto layer if err := crypto.Init(); err != nil { panic(fmt.Errorf("Failed initializing the crypto layer [%s]%", err)) } // On failure Cobra prints the usage message and error string, so we only // need to exit with a non-0 status if mainCmd.Execute() != nil { os.Exit(1) } } func createEventHubServer() (net.Listener, *grpc.Server, error) { var lis net.Listener var grpcServer *grpc.Server var err error if viper.GetBool("peer.validator.enabled") { lis, err = net.Listen("tcp", viper.GetString("peer.validator.events.address")) if err != nil { return nil, nil, fmt.Errorf("failed to listen: %v", err) } //TODO - do we need different SSL material for events ? var opts []grpc.ServerOption if viper.GetBool("peer.tls.enabled") { creds, err := credentials.NewServerTLSFromFile(viper.GetString("peer.tls.cert.file"), viper.GetString("peer.tls.key.file")) if err != nil { return nil, nil, fmt.Errorf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer = grpc.NewServer(opts...) ehServer := producer.NewOpenchainEventsServer(uint(viper.GetInt("peer.validator.events.buffersize")), viper.GetInt("peer.validator.events.timeout")) pb.RegisterOpenchainEventsServer(grpcServer, ehServer) } return lis, grpcServer, err } func serve(args []string) error { peerEndpoint, err := peer.GetPeerEndpoint() if err != nil { err = fmt.Errorf("Failed to get Peer Endpoint: %s", err) return err } listenAddr := viper.GetString("peer.listenaddress") if "" == listenAddr { logger.Debug("Listen address not specified, using peer endpoint address") listenAddr = peerEndpoint.Address } lis, err := net.Listen("tcp", listenAddr) if err != nil { grpclog.Fatalf("Failed to listen: %v", err) } ehubLis, ehubGrpcServer, err := createEventHubServer() if err != nil { grpclog.Fatalf("Failed to create ehub server: %v", err) } if chaincodeDevMode { logger.Info("Running in chaincode development mode") logger.Info("Set consensus to NOOPS and user starts chaincode") logger.Info("Disable loading validity system chaincode") viper.Set("peer.validator.enabled", "true") viper.Set("peer.validator.consensus", "noops") viper.Set("chaincode.mode", chaincode.DevModeUserRunsChaincode) // Disable validity system chaincode in dev mode. Also if security is enabled, // in obcca.yaml, manually set pki.validity-period.update to false to prevent // obcca from calling validity system chaincode -- though no harm otherwise viper.Set("ledger.blockchain.deploy-system-chaincode", "false") viper.Set("validator.validity-period.verification", "false") } logger.Info("Security enabled status: %t", viper.GetBool("security.enabled")) logger.Info("Privacy enabled status: %t", viper.GetBool("security.privacy")) var opts []grpc.ServerOption if viper.GetBool("peer.tls.enabled") { creds, err := credentials.NewServerTLSFromFile(viper.GetString("peer.tls.cert.file"), viper.GetString("peer.tls.key.file")) if err != nil { grpclog.Fatalf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer := grpc.NewServer(opts...) var peerServer *peer.PeerImpl if viper.GetBool("peer.validator.enabled") { logger.Debug("Running as validating peer - installing consensus %s", viper.GetString("peer.validator.consensus")) peerServer, err = peer.NewPeerWithHandler(helper.NewConsensusHandler) } else { logger.Debug("Running as non-validating peer") peerServer, err = peer.NewPeerWithHandler(peer.NewPeerHandler) } if err != nil { logger.Fatalf("Failed creating new peer with handler %v", err) return err } // Register the Peer server //pb.RegisterPeerServer(grpcServer, openchain.NewPeer()) pb.RegisterPeerServer(grpcServer, peerServer) // Register the Admin server pb.RegisterAdminServer(grpcServer, openchain.NewAdminServer()) // Register ChaincodeSupport server... // TODO : not the "DefaultChain" ... we have to revisit when we do multichain // The ChaincodeSupport needs security helper to encrypt/decrypt state when // privacy is enabled var secHelper crypto.Peer if viper.GetBool("security.privacy") { secHelper = peerServer.GetSecHelper() } else { secHelper = nil } registerChaincodeSupport(chaincode.DefaultChain, grpcServer, secHelper) // Register Devops server serverDevops := openchain.NewDevopsServer(peerServer) pb.RegisterDevopsServer(grpcServer, serverDevops) // Register the ServerOpenchain server serverOpenchain, err := openchain.NewOpenchainServerWithPeerInfo(peerServer) if err != nil { err = fmt.Errorf("Error creating OpenchainServer: %s", err) return err } pb.RegisterOpenchainServer(grpcServer, serverOpenchain) // Create and register the REST service if configured if viper.GetBool("rest.enabled") { go rest.StartOpenchainRESTServer(serverOpenchain, serverDevops) } rootNode, err := openchain.GetRootNode() if err != nil { grpclog.Fatalf("Failed to get peer.discovery.rootnode valey: %s", err) } logger.Info("Starting peer with id=%s, network id=%s, address=%s, discovery.rootnode=%s, validator=%v", peerEndpoint.ID, viper.GetString("peer.networkId"), peerEndpoint.Address, rootNode, viper.GetBool("peer.validator.enabled")) // Start the grpc server. Done in a goroutine so we can deploy the // genesis block if needed. serve := make(chan error) go func() { var grpcErr error if grpcErr = grpcServer.Serve(lis); grpcErr != nil { grpcErr = fmt.Errorf("grpc server exited with error: %s", grpcErr) } else { logger.Info("grpc server exited") } serve <- grpcErr }() // Deploy the genesis block if needed. if viper.GetBool("peer.validator.enabled") { makeGenesisError := genesis.MakeGenesis() if makeGenesisError != nil { return makeGenesisError } } //start the event hub server if ehubGrpcServer != nil && ehubLis != nil { go ehubGrpcServer.Serve(ehubLis) } // Block until grpc server exits return <-serve } func status() (err error) { clientConn, err := peer.NewPeerClientConnection() if err != nil { err = fmt.Errorf("Error trying to connect to local peer:", err) return } serverClient := pb.NewAdminClient(clientConn) status, err := serverClient.GetStatus(context.Background(), &google_protobuf.Empty{}) if err != nil { return } fmt.Println(status) return nil } func stop() (err error) { clientConn, err := peer.NewPeerClientConnection() if err != nil { err = fmt.Errorf("Error trying to connect to local peer:", err) return } logger.Info("Stopping peer...") serverClient := pb.NewAdminClient(clientConn) status, err := serverClient.StopServer(context.Background(), &google_protobuf.Empty{}) if err != nil { return } fmt.Println(status) return nil } // login confirms the enrollmentID and secret password of the client with the // CA and stores the enrollment certificate and key in the Devops server. func login(args []string) (err error) { logger.Info("CLI client login...") // Check for username argument if len(args) == 0 { err = fmt.Errorf("Must supply username") return } // Check for other extraneous arguments if len(args) != 1 { err = fmt.Errorf("Must supply username as the 1st and only parameter") return } // Retrieve the CLI data storage path // Returns /var/openchain/production/client/ localStore := getCliFilePath() logger.Info("Local data store for client loginToken: %s", localStore) // If the user is already logged in, return if _, err = os.Stat(localStore + "loginToken_" + args[0]); err == nil { logger.Info("User '%s' is already logged in.\n", args[0]) return } // User is not logged in, prompt for password fmt.Printf("Enter password for user '%s': ", args[0]) pw := gopass.GetPasswdMasked() // Log in the user logger.Info("Logging in user '%s' on CLI interface...\n", args[0]) // Get a devopsClient to perform the login clientConn, err := peer.NewPeerClientConnection() if err != nil { err = fmt.Errorf("Error trying to connect to local peer: %s", err) return } devopsClient := pb.NewDevopsClient(clientConn) // Build the login spec and login loginSpec := &pb.Secret{EnrollId: args[0], EnrollSecret: string(pw)} loginResult, err := devopsClient.Login(context.Background(), loginSpec) // Check if login is successful if loginResult.Status == pb.Response_SUCCESS { // If /var/openchain/production/client/ directory does not exist, create it if _, err := os.Stat(localStore); err != nil { if os.IsNotExist(err) { // Directory does not exist, create it if err := os.Mkdir(localStore, 0755); err != nil { panic(fmt.Errorf("Fatal error when creating %s directory: %s\n", localStore, err)) } } else { // Unexpected error panic(fmt.Errorf("Fatal error on os.Stat of %s directory: %s\n", localStore, err)) } } // Store client security context into a file logger.Info("Storing login token for user '%s'.\n", args[0]) err = ioutil.WriteFile(localStore+"loginToken_"+args[0], []byte(args[0]), 0755) if err != nil { panic(fmt.Errorf("Fatal error when storing client login token: %s\n", err)) } logger.Info("Login successful for user '%s'.\n", args[0]) } else { err = fmt.Errorf("Error on client login: %s", string(loginResult.Msg)) return } return nil } // getCliFilePath is a helper function to retrieve the local storage directory // of client login tokens. func getCliFilePath() string { localStore := viper.GetString("peer.fileSystemPath") if !strings.HasSuffix(localStore, "/") { localStore = localStore + "/" } localStore = localStore + "client/" return localStore } func registerChaincodeSupport(chainname chaincode.ChainName, grpcServer *grpc.Server, secHelper crypto.Peer) { //get user mode userRunsCC := false if viper.GetString("chaincode.mode") == chaincode.DevModeUserRunsChaincode { userRunsCC = true } //get chaincode startup timeout tOut, err := strconv.Atoi(viper.GetString("chaincode.startuptimeout")) if err != nil { //what went wrong ? fmt.Printf("could not retrive timeout var...setting to 5secs\n") tOut = 5000 } ccStartupTimeout := time.Duration(tOut) * time.Millisecond pb.RegisterChaincodeSupportServer(grpcServer, chaincode.NewChaincodeSupport(chainname, peer.GetPeerEndpoint, userRunsCC, ccStartupTimeout, secHelper)) } func checkChaincodeCmdParams(cmd *cobra.Command) (err error) { if chaincodeName == undefinedParamValue { if chaincodePath == undefinedParamValue { err = fmt.Errorf("Must supply value for %s path parameter.\n", chainFuncName) return } } // Check that non-empty chaincode parameters contain only Function and // Args keys. Type checking is done later when the JSON is actually // unmarshaled into a pb.ChaincodeInput. To better understand what's going // on here with JSON parsing see http://blog.golang.org/json-and-go - // Generic JSON with interface{} if chaincodeCtorJSON != "{}" { var f interface{} err = json.Unmarshal([]byte(chaincodeCtorJSON), &f) if err != nil { err = fmt.Errorf("Chaincode argument error : %s", err) return } m := f.(map[string]interface{}) if len(m) != 2 { err = fmt.Errorf("Non-empty JSON chaincode parameters must contain exactly 2 keys - 'Function' and 'Args'") return } for k, _ := range m { switch strings.ToLower(k) { case "function": case "args": default: err = fmt.Errorf("Illegal chaincode key '%s' - must be either 'Function' or 'Args'", k) return } } } else { err = fmt.Errorf("Empty JSON chaincode parameters must contain exactly 2 keys - 'Function' and 'Args'") return } return } func getDevopsClient(cmd *cobra.Command) (pb.DevopsClient, error) { clientConn, err := peer.NewPeerClientConnection() if err != nil { return nil, fmt.Errorf("Error trying to connect to local peer: %s", err) } devopsClient := pb.NewDevopsClient(clientConn) return devopsClient, nil } // chaincodeDeploy deploys the chaincode. On success, the chaincode name // (hash) is printed to STDOUT for use by subsequent chaincode-related CLI // commands. func chaincodeDeploy(cmd *cobra.Command, args []string) (err error) { if err = checkChaincodeCmdParams(cmd); err != nil { return } devopsClient, err := getDevopsClient(cmd) if err != nil { err = fmt.Errorf("Error building %s: %s", chainFuncName, err) return } // Build the spec input := &pb.ChaincodeInput{} if err = json.Unmarshal([]byte(chaincodeCtorJSON), &input); err != nil { err = fmt.Errorf("Chaincode argument error: %s", err) return } chaincodeLang = strings.ToUpper(chaincodeLang) spec := &pb.ChaincodeSpec{Type: pb.ChaincodeSpec_Type(pb.ChaincodeSpec_Type_value[chaincodeLang]), ChaincodeID: &pb.ChaincodeID{Path: chaincodePath, Name: chaincodeName}, CtorMsg: input} // If security is enabled, add client login token if viper.GetBool("security.enabled") { logger.Debug("Security is enabled. Include security context in deploy spec") if chaincodeUsr == undefinedParamValue { err = errors.New("Must supply username for chaincode when security is enabled") return } // Retrieve the CLI data storage path // Returns /var/openchain/production/client/ localStore := getCliFilePath() // Check if the user is logged in before sending transaction if _, err = os.Stat(localStore + "loginToken_" + chaincodeUsr); err == nil { logger.Info("Local user '%s' is already logged in. Retrieving login token.\n", chaincodeUsr) // Read in the login token token, err := ioutil.ReadFile(localStore + "loginToken_" + chaincodeUsr) if err != nil { panic(fmt.Errorf("Fatal error when reading client login token: %s\n", err)) } // Add the login token to the chaincodeSpec spec.SecureContext = string(token) // If privacy is enabled, mark chaincode as confidential if viper.GetBool("security.privacy") { logger.Info("Set confidentiality level to CONFIDENTIAL.\n") spec.ConfidentialityLevel = pb.ConfidentialityLevel_CONFIDENTIAL } } else { // Check if the token is not there and fail if os.IsNotExist(err) { err = fmt.Errorf("User '%s' not logged in. Use the 'login' command to obtain a security token.", chaincodeUsr) return } // Unexpected error panic(fmt.Errorf("Fatal error when checking for client login token: %s\n", err)) } } chaincodeDeploymentSpec, err := devopsClient.Deploy(context.Background(), spec) if err != nil { err = fmt.Errorf("Error building %s: %s\n", chainFuncName, err) return } logger.Info("Deploy result: %s", chaincodeDeploymentSpec.ChaincodeSpec) fmt.Println(chaincodeDeploymentSpec.ChaincodeSpec.ChaincodeID.Name) return nil } func chaincodeInvoke(cmd *cobra.Command, args []string) error { return chaincodeInvokeOrQuery(cmd, args, true) } func chaincodeQuery(cmd *cobra.Command, args []string) error { return chaincodeInvokeOrQuery(cmd, args, false) } // chaincodeInvokeOrQuery invokes or queries the chaincode. If successful, the // INVOKE form prints the transaction ID on STDOUT, and the QUERY form prints // the query result on STDOUT. A command-line flag (-r, --raw) determines // whether the query result is output as raw bytes, or as a printable string. // The printable form is optionally (-x, --hex) a hexadecimal representation // of the query response. If the query response is NIL, nothing is output. func chaincodeInvokeOrQuery(cmd *cobra.Command, args []string, invoke bool) (err error) { if err = checkChaincodeCmdParams(cmd); err != nil { return } if chaincodeName == "" { err = errors.New("Name not given for invoke/query") return } devopsClient, err := getDevopsClient(cmd) if err != nil { err = fmt.Errorf("Error building %s: %s", chainFuncName, err) return } // Build the spec input := &pb.ChaincodeInput{} if err = json.Unmarshal([]byte(chaincodeCtorJSON), &input); err != nil { err = fmt.Errorf("Chaincode argument error: %s", err) return } chaincodeLang = strings.ToUpper(chaincodeLang) spec := &pb.ChaincodeSpec{Type: pb.ChaincodeSpec_Type(pb.ChaincodeSpec_Type_value[chaincodeLang]), ChaincodeID: &pb.ChaincodeID{Name: chaincodeName}, CtorMsg: input} // If security is enabled, add client login token if viper.GetBool("security.enabled") { if chaincodeUsr == undefinedParamValue { err = errors.New("Must supply username for chaincode when security is enabled") return } // Retrieve the CLI data storage path // Returns /var/openchain/production/client/ localStore := getCliFilePath() // Check if the user is logged in before sending transaction if _, err = os.Stat(localStore + "loginToken_" + chaincodeUsr); err == nil { logger.Info("Local user '%s' is already logged in. Retrieving login token.\n", chaincodeUsr) // Read in the login token token, err := ioutil.ReadFile(localStore + "loginToken_" + chaincodeUsr) if err != nil { panic(fmt.Errorf("Fatal error when reading client login token: %s\n", err)) } // Add the login token to the chaincodeSpec spec.SecureContext = string(token) // If privacy is enabled, mark chaincode as confidential if viper.GetBool("security.privacy") { logger.Info("Set confidentiality level to CONFIDENTIAL.\n") spec.ConfidentialityLevel = pb.ConfidentialityLevel_CONFIDENTIAL } } else { // Check if the token is not there and fail if os.IsNotExist(err) { err = fmt.Errorf("User '%s' not logged in. Use the 'login' command to obtain a security token.", chaincodeUsr) return } // Unexpected error panic(fmt.Errorf("Fatal error when checking for client login token: %s\n", err)) } } // Build the ChaincodeInvocationSpec message invocation := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec} var resp *pb.Response if invoke { resp, err = devopsClient.Invoke(context.Background(), invocation) } else { resp, err = devopsClient.Query(context.Background(), invocation) } if err != nil { if invoke { err = fmt.Errorf("Error invoking %s: %s\n", chainFuncName, err) } else { err = fmt.Errorf("Error querying %s: %s\n", chainFuncName, err) } return } if invoke { transactionID := string(resp.Msg) logger.Info("Successfully invoked transaction: %s(%s)", invocation, transactionID) fmt.Println(transactionID) } else { logger.Info("Successfully queried transaction: %s", invocation) if resp != nil { if chaincodeQueryRaw { if chaincodeQueryHex { err = errors.New("Options --raw (-r) and --hex (-x) are not compatible\n") return } os.Stdout.Write(resp.Msg) } else { if chaincodeQueryHex { fmt.Printf("%x\n", resp.Msg) } else { fmt.Println(string(resp.Msg)) } } } } return nil }
{ "content_hash": "e9d8b478c7dd24498011f350f25d40c3", "timestamp": "", "source": "github", "line_count": 808, "max_line_length": 170, "avg_line_length": 33.26361386138614, "alnum_prop": 0.7160769431112103, "repo_name": "sumanair/obc-peer", "id": "de804c9a9f1b313ac40e0bb6f2d4087116c54d2c", "size": "27637", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main.go", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Cucumber", "bytes": "31616" }, { "name": "Gnuplot", "bytes": "1827" }, { "name": "Go", "bytes": "1547043" }, { "name": "Protocol Buffer", "bytes": "32583" }, { "name": "Python", "bytes": "28221" }, { "name": "Shell", "bytes": "16099" } ], "symlink_target": "" }
package android.webkit; import org.robolectric.internal.DoNotInstrument; import org.robolectric.internal.Implementation; /** * Concrete implementation of the abstract WebSettings class. */ @DoNotInstrument public class TestWebSettings extends WebSettings { private boolean allowFileAccess = true; private boolean allowFileAccessFromFile = true; private boolean allowUniversalAccessFromFile = true; private boolean blockNetworkImage = false; private boolean blockNetworkLoads = false; private boolean builtInZoomControls = true; private boolean databaseEnabled = false; private boolean domStorageEnabled = false; private boolean javaScriptEnabled = false; private boolean lightTouchEnabled = false; private boolean loadWithOverviewMode = false; private boolean needInitialFocus = false; private boolean pluginsEnabled = false; private WebSettings.PluginState pluginState = WebSettings.PluginState.OFF; private boolean supportMultipleWindows = false; private boolean supportZoom = true; public TestWebSettings() { } public boolean getAllowFileAccessFromFileURLs() { return allowFileAccessFromFile; } public boolean getAllowUniversalAccessFromFileURLs() { return allowUniversalAccessFromFile; } public void setAllowFileAccessFromFileURLs(boolean allow) { allowFileAccessFromFile = allow; } public void setAllowUniversalAccessFromFileURLs(boolean allow) { allowUniversalAccessFromFile = allow; } @Implementation public boolean getAllowFileAccess() { return allowFileAccess; } @Implementation public void setAllowFileAccess(boolean allow) { allowFileAccess = allow; } @Implementation public synchronized boolean getBlockNetworkImage() { return blockNetworkImage; } @Implementation public synchronized void setBlockNetworkImage(boolean flag) { blockNetworkImage = flag; } @Implementation public synchronized boolean getBlockNetworkLoads() { return blockNetworkLoads; } @Implementation public synchronized void setBlockNetworkLoads(boolean flag) { blockNetworkLoads = flag; } @Implementation public boolean getBuiltInZoomControls() { return builtInZoomControls; } @Implementation public void setBuiltInZoomControls(boolean enabled) { builtInZoomControls = enabled; } @Implementation public synchronized boolean getDatabaseEnabled() { return databaseEnabled; } @Implementation public synchronized void setDatabaseEnabled(boolean flag) { databaseEnabled = flag; } @Implementation public synchronized boolean getDomStorageEnabled() { return domStorageEnabled; } @Implementation public synchronized void setDomStorageEnabled(boolean flag) { domStorageEnabled = flag; } @Implementation public synchronized boolean getJavaScriptEnabled() { return javaScriptEnabled; } @Implementation public synchronized void setJavaScriptEnabled(boolean flag) { javaScriptEnabled = flag; } @Implementation public boolean getLightTouchEnabled() { return lightTouchEnabled; } @Implementation public void setLightTouchEnabled(boolean flag) { lightTouchEnabled = flag; } @Implementation public boolean getLoadWithOverviewMode() { return loadWithOverviewMode; } @Implementation public void setLoadWithOverviewMode(boolean flag) { loadWithOverviewMode = flag; } public boolean getNeedInitialFocus() { return needInitialFocus; } @Implementation public void setNeedInitialFocus(boolean flag) { needInitialFocus = flag; } @Implementation public synchronized boolean getPluginsEnabled() { return pluginsEnabled; } @Implementation public synchronized void setPluginsEnabled(boolean flag) { pluginsEnabled = flag; } @Implementation public synchronized WebSettings.PluginState getPluginState() { return pluginState; } @Implementation public synchronized void setPluginState(WebSettings.PluginState state) { pluginState = state; } public boolean getSupportMultipleWindows() { return supportMultipleWindows; } @Implementation public synchronized void setSupportMultipleWindows(boolean support) { supportMultipleWindows = support; } public boolean getSupportZoom() { return supportZoom; } @Implementation public void setSupportZoom(boolean support) { supportZoom = support; } }
{ "content_hash": "a9e182f7681ed4db1f280d6fde4ac119", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 78, "avg_line_length": 25.956521739130434, "alnum_prop": 0.7049832495812395, "repo_name": "jeffreyzh/robolectric", "id": "0e6256dd8ea1018f285f452e8b05782625a6d27d", "size": "4776", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/main/java/android/webkit/TestWebSettings.java", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
(function(model){ var Event = new EventObject(); Event.newEvent = function(eventName, callback) { this.createEvent(eventName,function(result) { Event = result; if(callback) callback(Event); }); }; Event.initEventPage = function(ctx,next) { Event.prepHandlebars(); Handlebars.registerHelper('css', function(status) { if (status === -1) return 'disapprove'; if (status === 0) return ''; if (status === 1) return 'maybe'; if (status === 2) return 'approve'; }); Handlebars.registerHelper('text', function(status) { if (status === -1) return 'nope'; if (status === 0) return 'no response'; if (status === 1) return 'maybe'; if (status === 2) return 'attending'; }); EventView.initEventView(next); }; Event.getEventFromHash = function(ctx,next) { Event.hash = ctx.params.eventHash; Event.loadEventFromDB(function(result) { if (result && result.name) { Event = result; getTopicId(Event._id,function(){ if (next) next(); }); } else { console.error('Problem retrieving Event from Hash:',ctx.params); // TODO: Display a message to the user about the bad hash // Give button to start at home page? } }); // TODO: Move to topic-controller function getTopicId(eventHash,callback) { $.ajax({ url: '/api/topics/', type: 'GET', cache: false }) .done( function (data) { // call the callback function here console.log('getTopicId data:',data); var topicId = data.topics.filter(function(topic){ if(topic.eventHash == eventHash) return true; }); if (topicId.length) { $('#timing').attr('data-topicId',topicId[0]._id); if (callback) callback(); } else { // Hopefully this will never happen. console.error('GET /api/topics/ Ajax call successful, but no topicIds returned!'); if (callback) callback(); }; }) .fail( function(jqXHR, textStatus, errorThrown) { console.warn('Ajax call failed: GET /api/events/' + eventHash); console.log('jqXHR.responseText:',jqXHR.responseText); console.log('textStatus:',textStatus); console.log('errorThrown:',errorThrown); // call the error version of the callback if any if (callback) callback(); }); } }; Event.handleSubmitComment = function(clickEvent) { clickEvent.preventDefault(); Event.date = $('#date').val().trim(); Event.times = $('#times').val().trim(); Event.description = $('#event-description').val().trim(); Event.updateEventInDB(function(updatedEvent){ EventView.updateDetails(updatedEvent); }); }; Event.prepHandlebars = function(){ var rsvpTemplate = $('#guests').html(); Event.rsvpsToHtml = Handlebars.compile(rsvpTemplate); }; Event.updateRsvps = function(){ this.getRsvpListFromDB(function(updatedRsvpList){ var guestListHtml = Event.rsvpsToHtml({rsvp:updatedRsvpList}); EventView.updateRsvpList(guestListHtml); }); }; model.Event = Event; })(window);
{ "content_hash": "e134daa8377d52865cffdcaa03b44874", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 92, "avg_line_length": 31.067961165048544, "alnum_prop": 0.59875, "repo_name": "GeoffreyEmerson/301-final-project", "id": "c816886426e73ec83442ee2cdfa551c1b732ad78", "size": "3200", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/js/event-controller.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "38876" }, { "name": "HTML", "bytes": "35421" }, { "name": "JavaScript", "bytes": "118762" } ], "symlink_target": "" }
package r_kvstore //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. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // DescribeRedisLogConfig invokes the r_kvstore.DescribeRedisLogConfig API synchronously // api document: https://help.aliyun.com/api/r-kvstore/describeredislogconfig.html func (client *Client) DescribeRedisLogConfig(request *DescribeRedisLogConfigRequest) (response *DescribeRedisLogConfigResponse, err error) { response = CreateDescribeRedisLogConfigResponse() err = client.DoAction(request, response) return } // DescribeRedisLogConfigWithChan invokes the r_kvstore.DescribeRedisLogConfig API asynchronously // api document: https://help.aliyun.com/api/r-kvstore/describeredislogconfig.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) DescribeRedisLogConfigWithChan(request *DescribeRedisLogConfigRequest) (<-chan *DescribeRedisLogConfigResponse, <-chan error) { responseChan := make(chan *DescribeRedisLogConfigResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.DescribeRedisLogConfig(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // DescribeRedisLogConfigWithCallback invokes the r_kvstore.DescribeRedisLogConfig API asynchronously // api document: https://help.aliyun.com/api/r-kvstore/describeredislogconfig.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) DescribeRedisLogConfigWithCallback(request *DescribeRedisLogConfigRequest, callback func(response *DescribeRedisLogConfigResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *DescribeRedisLogConfigResponse var err error defer close(result) response, err = client.DescribeRedisLogConfig(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // DescribeRedisLogConfigRequest is the request struct for api DescribeRedisLogConfig type DescribeRedisLogConfigRequest struct { *requests.RpcRequest ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` SecurityToken string `position:"Query" name:"SecurityToken"` ResourceOwnerAccount string `position:"Query" name:"ResourceOwnerAccount"` OwnerAccount string `position:"Query" name:"OwnerAccount"` OwnerId requests.Integer `position:"Query" name:"OwnerId"` InstanceId string `position:"Query" name:"InstanceId"` } // DescribeRedisLogConfigResponse is the response struct for api DescribeRedisLogConfig type DescribeRedisLogConfigResponse struct { *responses.BaseResponse RequestId string `json:"RequestId" xml:"RequestId"` IsEtlMetaExist int `json:"IsEtlMetaExist" xml:"IsEtlMetaExist"` IsUserProjectLogstoreExist int `json:"IsUserProjectLogstoreExist" xml:"IsUserProjectLogstoreExist"` UserProjectName int `json:"UserProjectName" xml:"UserProjectName"` UserLogstoreName string `json:"UserLogstoreName" xml:"UserLogstoreName"` } // CreateDescribeRedisLogConfigRequest creates a request to invoke DescribeRedisLogConfig API func CreateDescribeRedisLogConfigRequest() (request *DescribeRedisLogConfigRequest) { request = &DescribeRedisLogConfigRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("R-kvstore", "2015-01-01", "DescribeRedisLogConfig", "redisa", "openAPI") return } // CreateDescribeRedisLogConfigResponse creates a response to parse from DescribeRedisLogConfig response func CreateDescribeRedisLogConfigResponse() (response *DescribeRedisLogConfigResponse) { response = &DescribeRedisLogConfigResponse{ BaseResponse: &responses.BaseResponse{}, } return }
{ "content_hash": "f6320b67f52708420ed4b83bfc4491b6", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 177, "avg_line_length": 42.419642857142854, "alnum_prop": 0.7680488318248789, "repo_name": "aliyun/alibaba-cloud-sdk-go", "id": "4d1087cce393a0de7506dc46418bf0fe41e3c4da", "size": "4751", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services/r_kvstore/describe_redis_log_config.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "734307" }, { "name": "Makefile", "bytes": "183" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Globalization; using System.Net; using Mozu.Api; using Mozu.Api.Security; using Mozu.Api.Test.Helpers; using System.Diagnostics; using Newtonsoft.Json.Linq; using System.Threading; #endregion namespace Mozu.Api.Test.Factories.Commerce.Customer { /// <summary> /// Use the Customer Segments resource to manage the segments that enable a client to manage groups of customers and target discounts for these segments. After a customer segment is defined, you can associate any number of customer accounts with it. /// </summary> public partial class CustomerSegmentFactory : BaseDataFactory { /// <summary> /// /// <example> /// <code> /// var result = CustomerSegmentFactory.GetSegments(handler : handler, startIndex : startIndex, pageSize : pageSize, sortBy : sortBy, filter : filter, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<CustomerSegmentCollection/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static Mozu.Api.Contracts.Customer.CustomerSegmentCollection GetSegments(ServiceClientMessageHandler handler, int? startIndex = null, int? pageSize = null, string sortBy = null, string filter = null, string responseFields = null, HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Customer.CustomerSegmentClient.GetSegmentsClient( startIndex : startIndex, pageSize : pageSize, sortBy : sortBy, filter : filter, responseFields : responseFields ); try { apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; return null; } return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// /// <example> /// <code> /// var result = CustomerSegmentFactory.GetSegment(handler : handler, id : id, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<CustomerSegment/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static Mozu.Api.Contracts.Customer.CustomerSegment GetSegment(ServiceClientMessageHandler handler, int id, string responseFields = null, HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Customer.CustomerSegmentClient.GetSegmentClient( id : id, responseFields : responseFields ); try { apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; return null; } return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// /// <example> /// <code> /// var result = CustomerSegmentFactory.AddSegment(handler : handler, segment : segment, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<CustomerSegment/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static Mozu.Api.Contracts.Customer.CustomerSegment AddSegment(ServiceClientMessageHandler handler, Mozu.Api.Contracts.Customer.CustomerSegment segment, string responseFields = null, HttpStatusCode expectedCode = HttpStatusCode.Created, HttpStatusCode successCode = HttpStatusCode.Created) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Customer.CustomerSegmentClient.AddSegmentClient( segment : segment, responseFields : responseFields ); try { apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; return null; } return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// /// <example> /// <code> /// var result = CustomerSegmentFactory.AddSegmentAccounts(handler : handler, accountIds : accountIds, id : id, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<void/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static void AddSegmentAccounts(ServiceClientMessageHandler handler, List<int> accountIds, int id, HttpStatusCode expectedCode = HttpStatusCode.NoContent, HttpStatusCode successCode = HttpStatusCode.NoContent) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Customer.CustomerSegmentClient.AddSegmentAccountsClient( accountIds : accountIds, id : id ); try { apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; } var noResponse = ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// /// <example> /// <code> /// var result = CustomerSegmentFactory.UpdateSegment(handler : handler, segment : segment, id : id, responseFields : responseFields, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<CustomerSegment/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static Mozu.Api.Contracts.Customer.CustomerSegment UpdateSegment(ServiceClientMessageHandler handler, Mozu.Api.Contracts.Customer.CustomerSegment segment, int id, string responseFields = null, HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Customer.CustomerSegmentClient.UpdateSegmentClient( segment : segment, id : id, responseFields : responseFields ); try { apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; return null; } return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// /// <example> /// <code> /// var result = CustomerSegmentFactory.DeleteSegment(handler : handler, id : id, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<void/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static void DeleteSegment(ServiceClientMessageHandler handler, int id, HttpStatusCode expectedCode = HttpStatusCode.NoContent, HttpStatusCode successCode = HttpStatusCode.NoContent) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Customer.CustomerSegmentClient.DeleteSegmentClient( id : id ); try { apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; } var noResponse = ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } /// <summary> /// /// <example> /// <code> /// var result = CustomerSegmentFactory.RemoveSegmentAccount(handler : handler, id : id, accountId : accountId, expectedCode: expectedCode, successCode: successCode); /// var optionalCasting = ConvertClass<void/>(result); /// return optionalCasting; /// </code> /// </example> /// </summary> public static void RemoveSegmentAccount(ServiceClientMessageHandler handler, int id, int accountId, HttpStatusCode expectedCode = HttpStatusCode.NoContent, HttpStatusCode successCode = HttpStatusCode.NoContent) { SetSdKparameters(); var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name; var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Debug.WriteLine(currentMethodName + '.' + currentMethodName ); var apiClient = Mozu.Api.Clients.Commerce.Customer.CustomerSegmentClient.RemoveSegmentAccountClient( id : id, accountId : accountId ); try { apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait(); } catch (ApiException ex) { // Custom error handling for test cases can be placed here Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode); if (customException != null) throw customException; } var noResponse = ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode) ? (apiClient.Result()) : null; } } }
{ "content_hash": "79cded8861f8528305af3c2408cb3f39", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 252, "avg_line_length": 42.48965517241379, "alnum_prop": 0.7335659795487746, "repo_name": "rocky0904/mozu-dotnet", "id": "12d1454bad62523b2160f48739029a4250f10018", "size": "12707", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Mozu.Api.Test/Factories/Commerce/Customer/CustomerSegmentFactory.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "279" }, { "name": "C#", "bytes": "7078214" }, { "name": "F#", "bytes": "1750" }, { "name": "PowerShell", "bytes": "3311" } ], "symlink_target": "" }
// // ScanditSDKCommon.h // ScanditBarcodeScanner // // Created by Marco Biasini on 29/05/15. // Copyright (c) 2015 Scandit AG. All rights reserved. // #define SBS_DEPRECATED __attribute__((deprecated)) // we can't use NS_ENUM directly, but rather have to use a macro that gets replaced with // the proper meaning when generating the documentation. //! \{ #if defined(SBS_GENERATE_DOCS) # define SBS_ENUM_BEGIN(name) typedef enum # define SBS_ENUM_END(name) name #else # define SBS_ENUM_BEGIN(name) typedef NS_ENUM(NSInteger, name) # define SBS_ENUM_END(name) #endif //! \} /** * Enumeration of different camera orientations. * * \since 2.1.7 */ SBS_ENUM_BEGIN(SBSCameraFacingDirection) { SBSCameraFacingDirectionBack, /**< Default camera orientation - facing away from user */ SBSCameraFacingDirectionFront, /**< Facetime camera orientation - facing the user */ CAMERA_FACING_BACK SBS_DEPRECATED = SBSCameraFacingDirectionBack, CAMERA_FACING_FRONT SBS_DEPRECATED = SBSCameraFacingDirectionFront, } SBS_ENUM_END(SBSCameraFacingDirection); typedef SBSCameraFacingDirection CameraFacingDirection SBS_DEPRECATED; SBS_ENUM_BEGIN(SBSOrientation) { SBSOrientationPortrait, SBSOrientationLandscape, ORIENTATION_PORTRAIT SBS_DEPRECATED = SBSOrientationPortrait, ORIENTATION_LANDSCAPE SBS_DEPRECATED = SBSOrientationLandscape } SBS_ENUM_END(SBSOrientation); typedef SBSOrientation Orientation SBS_DEPRECATED; /** * Enumerates the possible working ranges for the barcode picker * * \since 4.1.0 */ SBS_ENUM_BEGIN(SBSWorkingRange) { /** * The camera tries to focus on barcodes which are close to the camera. To scan far- * away codes (30-40cm+), user must tap the screen. This is the default working range * and works best for most use-cases. Only change the default value if you expect the * users to often scan codes which are far away. */ SBSWorkingRangeStandard, /** * The camera tries to focus on barcodes which are far from the camera. This will make * it easier to scan codes that are far away but degrade performance for very close * codes. */ SBSWorkingRangeLong, STANDARD_RANGE SBS_DEPRECATED = SBSWorkingRangeStandard, LONG_RANGE SBS_DEPRECATED = SBSWorkingRangeLong, /** * \deprecated This value has been deprecated in Scandit SDK 4.2+. Setting it has no effect. */ HIGH_DENSITY SBS_DEPRECATED } SBS_ENUM_END(SBSWorkingRange); typedef SBSWorkingRange WorkingRange; /** * \brief Enumeration of different MSI Checksums * * \since 3.0.0 */ SBS_ENUM_BEGIN(SBSMsiPlesseyChecksumType) { SBSMsiPlesseyChecksumTypeNone, SBSMsiPlesseyChecksumTypeMod10, /**< Default MSI Plessey Checksum */ SBSMsiPlesseyChecksumTypeMod1010, SBSMsiPlesseyChecksumTypeMod11, SBSMsiPlesseyChecksumTypeMod1110, NONE SBS_DEPRECATED = SBSMsiPlesseyChecksumTypeNone, CHECKSUM_MOD_10 SBS_DEPRECATED = SBSMsiPlesseyChecksumTypeMod10, CHECKSUM_MOD_1010 SBS_DEPRECATED = SBSMsiPlesseyChecksumTypeMod1010, CHECKSUM_MOD_11 SBS_DEPRECATED = SBSMsiPlesseyChecksumTypeMod11, CHECKSUM_MOD_1110 SBS_DEPRECATED = SBSMsiPlesseyChecksumTypeMod1110 } SBS_ENUM_END(SBSMsiPlesseyChecksumType); typedef SBSMsiPlesseyChecksumType MsiPlesseyChecksumType SBS_DEPRECATED; /** * \brief Enumeration of different GUI styles. * * \since 4.8.0 */ SBS_ENUM_BEGIN(SBSGuiStyle) { /** * A rectangular viewfinder with rounded corners is shown in the specified size. Recognized * codes are marked with four corners. */ SBSGuiStyleDefault, /** * A laser line is shown with the specified width while the height is not changeable. This mode * should generally not be used if the recognition is running on the whole screen as it * indicates that the code should be placed at the location of the laser line. */ SBSGuiStyleLaser, /** * No UI is shown to indicate where the barcode should be placed. Be aware that the Scandit * logo continues to be displayed as showing it is part of the license agreement. */ SBSGuiStyleNone } SBS_ENUM_END(SBSGuiStyle); /** * \brief Error domain for the ScanditBarcodeScanner framework * * \since 4.11.0 */ FOUNDATION_EXPORT NSString *SBSErrorDomain; /** * \brief enumeration of various error codes */ SBS_ENUM_BEGIN(SBSError) { /** * \brief An invalid argument has been passed to a method/function. */ SBSErrorInvalidArgument = 1 } SBS_ENUM_END(SBSError);
{ "content_hash": "0014583fb855548b0c940211302a9549", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 99, "avg_line_length": 32.12056737588652, "alnum_prop": 0.7315080591742107, "repo_name": "hashikuchi/TexchangeApp", "id": "905a560b33c7001ad3660eab3317548dcaf972a1", "size": "4529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/iphone/com.mirasense.scanditsdk/4.11.0/platform/ScanditBarcodeScanner.framework/Headers/SBSCommon.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "71" }, { "name": "CSS", "bytes": "1276" }, { "name": "JavaScript", "bytes": "94855" }, { "name": "Python", "bytes": "5251" } ], "symlink_target": "" }
//// [tests/cases/compiler/declFileAccessors.ts] //// //// [declFileAccessors_0.ts] /** This is comment for c1*/ export class c1 { /** getter property*/ public get p3() { return 10; } /** setter property*/ public set p3(/** this is value*/value: number) { } /** private getter property*/ private get pp3() { return 10; } /** private setter property*/ private set pp3(/** this is value*/value: number) { } /** static getter property*/ static get s3() { return 10; } /** setter property*/ static set s3( /** this is value*/value: number) { } public get nc_p3() { return 10; } public set nc_p3(value: number) { } private get nc_pp3() { return 10; } private set nc_pp3(value: number) { } static get nc_s3() { return ""; } static set nc_s3(value: string) { } // Only getter property public get onlyGetter() { return 10; } // Only setter property public set onlySetter(value: number) { } } //// [declFileAccessors_1.ts] /** This is comment for c2 - the global class*/ class c2 { /** getter property*/ public get p3() { return 10; } /** setter property*/ public set p3(/** this is value*/value: number) { } /** private getter property*/ private get pp3() { return 10; } /** private setter property*/ private set pp3(/** this is value*/value: number) { } /** static getter property*/ static get s3() { return 10; } /** setter property*/ static set s3( /** this is value*/value: number) { } public get nc_p3() { return 10; } public set nc_p3(value: number) { } private get nc_pp3() { return 10; } private set nc_pp3(value: number) { } static get nc_s3() { return ""; } static set nc_s3(value: string) { } // Only getter property public get onlyGetter() { return 10; } // Only setter property public set onlySetter(value: number) { } } //// [declFileAccessors_0.js] "use strict"; /** This is comment for c1*/ var c1 = (function () { function c1() { } Object.defineProperty(c1.prototype, "p3", { /** getter property*/ get: function () { return 10; }, /** setter property*/ set: function (/** this is value*/ value) { }, enumerable: true, configurable: true }); Object.defineProperty(c1.prototype, "pp3", { /** private getter property*/ get: function () { return 10; }, /** private setter property*/ set: function (/** this is value*/ value) { }, enumerable: true, configurable: true }); Object.defineProperty(c1, "s3", { /** static getter property*/ get: function () { return 10; }, /** setter property*/ set: function (/** this is value*/ value) { }, enumerable: true, configurable: true }); Object.defineProperty(c1.prototype, "nc_p3", { get: function () { return 10; }, set: function (value) { }, enumerable: true, configurable: true }); Object.defineProperty(c1.prototype, "nc_pp3", { get: function () { return 10; }, set: function (value) { }, enumerable: true, configurable: true }); Object.defineProperty(c1, "nc_s3", { get: function () { return ""; }, set: function (value) { }, enumerable: true, configurable: true }); Object.defineProperty(c1.prototype, "onlyGetter", { // Only getter property get: function () { return 10; }, enumerable: true, configurable: true }); Object.defineProperty(c1.prototype, "onlySetter", { // Only setter property set: function (value) { }, enumerable: true, configurable: true }); return c1; }()); exports.c1 = c1; //// [declFileAccessors_1.js] /** This is comment for c2 - the global class*/ var c2 = (function () { function c2() { } Object.defineProperty(c2.prototype, "p3", { /** getter property*/ get: function () { return 10; }, /** setter property*/ set: function (/** this is value*/ value) { }, enumerable: true, configurable: true }); Object.defineProperty(c2.prototype, "pp3", { /** private getter property*/ get: function () { return 10; }, /** private setter property*/ set: function (/** this is value*/ value) { }, enumerable: true, configurable: true }); Object.defineProperty(c2, "s3", { /** static getter property*/ get: function () { return 10; }, /** setter property*/ set: function (/** this is value*/ value) { }, enumerable: true, configurable: true }); Object.defineProperty(c2.prototype, "nc_p3", { get: function () { return 10; }, set: function (value) { }, enumerable: true, configurable: true }); Object.defineProperty(c2.prototype, "nc_pp3", { get: function () { return 10; }, set: function (value) { }, enumerable: true, configurable: true }); Object.defineProperty(c2, "nc_s3", { get: function () { return ""; }, set: function (value) { }, enumerable: true, configurable: true }); Object.defineProperty(c2.prototype, "onlyGetter", { // Only getter property get: function () { return 10; }, enumerable: true, configurable: true }); Object.defineProperty(c2.prototype, "onlySetter", { // Only setter property set: function (value) { }, enumerable: true, configurable: true }); return c2; }()); //// [declFileAccessors_0.d.ts] /** This is comment for c1*/ export declare class c1 { /** getter property*/ /** setter property*/ p3: number; /** private getter property*/ /** private setter property*/ private pp3; /** static getter property*/ /** setter property*/ static s3: number; nc_p3: number; private nc_pp3; static nc_s3: string; onlyGetter: number; onlySetter: number; } //// [declFileAccessors_1.d.ts] /** This is comment for c2 - the global class*/ declare class c2 { /** getter property*/ /** setter property*/ p3: number; /** private getter property*/ /** private setter property*/ private pp3; /** static getter property*/ /** setter property*/ static s3: number; nc_p3: number; private nc_pp3; static nc_s3: string; onlyGetter: number; onlySetter: number; }
{ "content_hash": "ae7b1caaab3cf0028e03f716aae5000d", "timestamp": "", "source": "github", "line_count": 307, "max_line_length": 55, "avg_line_length": 24.140065146579804, "alnum_prop": 0.49885305626771015, "repo_name": "mmoskal/TypeScript", "id": "e3616c79e389f6456fbed6900d5d281e3d05e1dd", "size": "7411", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "tests/baselines/reference/declFileAccessors.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "945" }, { "name": "HTML", "bytes": "4843" }, { "name": "JavaScript", "bytes": "175" }, { "name": "PowerShell", "bytes": "2855" }, { "name": "Shell", "bytes": "47" }, { "name": "TypeScript", "bytes": "27925474" } ], "symlink_target": "" }
(function(f, define){ define([ "./kendo.data" ], f); })(function(){ (function() { kendo.data.transports.signalr = kendo.data.RemoteTransport.extend({ init: function (options) { var signalr = options && options.signalr ? options.signalr : {}; var promise = signalr.promise; if (!promise) { throw new Error('The "promise" option must be set.'); } if (typeof promise.done != "function" || typeof promise.fail != "function") { throw new Error('The "promise" option must be a Promise.'); } this.promise = promise; var hub = signalr.hub; if (!hub) { throw new Error('The "hub" option must be set.'); } if (typeof hub.on != "function" || typeof hub.invoke != "function") { throw new Error('The "hub" option is not a valid SignalR hub proxy.'); } this.hub = hub; kendo.data.RemoteTransport.fn.init.call(this, options); }, push: function(callbacks) { var client = this.options.signalr.client || {}; if (client.create) { this.hub.on(client.create, callbacks.pushCreate); } if (client.update) { this.hub.on(client.update, callbacks.pushUpdate); } if (client.destroy) { this.hub.on(client.destroy, callbacks.pushDestroy); } }, _crud: function(options, type) { var hub = this.hub; var server = this.options.signalr.server; if (!server || !server[type]) { throw new Error(kendo.format('The "server.{0}" option must be set.', type)); } var args = [server[type]]; var data = this.parameterMap(options.data, type); if (!$.isEmptyObject(data)) { args.push(data); } this.promise.done(function() { hub.invoke.apply(hub, args) .done(options.success) .fail(options.error); }); }, read: function(options) { this._crud(options, "read"); }, create: function(options) { this._crud(options, "create"); }, update: function(options) { this._crud(options, "update"); }, destroy: function(options) { this._crud(options, "destroy"); } }); })(); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
{ "content_hash": "c971a623e761ffc9a7ef5d4602d0f8df", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 92, "avg_line_length": 27.53061224489796, "alnum_prop": 0.4844329132690882, "repo_name": "y-todorov/Inventory", "id": "15213dc7f00b8d7d30215ad70f1a8db315b6a650", "size": "3031", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Inventory.MVC/Scripts/Kendo/kendo.data.signalr.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "104" }, { "name": "C#", "bytes": "360203" }, { "name": "CSS", "bytes": "6203009" }, { "name": "JavaScript", "bytes": "24856359" } ], "symlink_target": "" }
package org.protempa.test; import java.util.Date; /** * Abstract class used as the super-type for various types of observations * related to an encounter. * * @author hrathod * */ public abstract class Observation extends Record { /** * The unique identifier for the observation. */ private String id; /** * The unique identifier for the encounter to which this observation is * associated. */ private Long encounterId; /** * The date of the observation. */ private Date timestamp; /** * The unique identifier for the entity associated with this observation. */ private String entityId; /** * Get the unique identifier for the observation. * * @return The unique identifier for the observation. */ public String getId() { return this.id; } /** * Set the unique identifier for the observation. * * @param inId The unique identifier for the observation. */ public void setId(String inId) { this.id = inId; } /** * Get the unique identifier for the encounter with which the observation is * associated. * * @return The unique identifier for the encounter. */ public Long getEncounterId() { return this.encounterId; } /** * Set the unique identifier for the encounter with which the observation is * associated. * * @param inEncounterId The unique identifier for the encounter. */ public void setEncounterId(Long inEncounterId) { this.encounterId = inEncounterId; } /** * Get the date of the observation. * * @return The date of the observation. */ public Date getTimestamp() { return this.timestamp; } /** * Set the date of the observation. * * @param inTimestamp The date of the observation. */ public void setTimestamp(Date inTimestamp) { this.timestamp = inTimestamp; } /** * Get the unique identifier for the entity associated with the observation. * * @return The unique identifier for the entity. */ public String getEntityId() { return this.entityId; } /** * Set the unique identifier for the entity associated with the observation. * * @param inEntityId The unique identifier for the entity. */ public void setEntityId(String inEntityId) { this.entityId = inEntityId; } }
{ "content_hash": "a1e493447f6a80fa02f1a9f09843e4c9", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 80, "avg_line_length": 23.60377358490566, "alnum_prop": 0.6191047162270183, "repo_name": "eurekaclinical/protempa", "id": "5d1e9890121b95797daf9ef21c861b2f037aec86", "size": "3161", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "protempa-test-suite/src/test/java/org/protempa/test/Observation.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3004405" }, { "name": "XSLT", "bytes": "5870" } ], "symlink_target": "" }
"""An Encoder class for Protocol Buffers that preserves sorting characteristics. This is used by datastore_sqlite_stub and datastore_types to match the ordering semantics of the production datastore. Broadly, there are four changes from regular PB encoding: - Strings are escaped and null terminated instead of length-prefixed. The escaping replaces \x00 with \x01\x01 and \x01 with \x01\x02, thus preserving the ordering of the original string. - Variable length integers are encoded using a variable length encoding that preserves order. The first byte stores the absolute value if it's between -119 to 119, otherwise it stores the number of bytes that follow. - Numbers are stored big endian instead of little endian. - Negative doubles are entirely negated, while positive doubles have their sign bit flipped. Warning: Due to the way nested Protocol Buffers are encoded, this encoder will NOT preserve sorting characteristics for embedded protocol buffers! """ import array import struct from google.net.proto import ProtocolBuffer _MAX_UNSIGNED_BYTE = 255 _MAX_LONG_BYTES = 8 _MAX_INLINE = (_MAX_UNSIGNED_BYTE - (2 * _MAX_LONG_BYTES)) / 2 _MIN_INLINE = -_MAX_INLINE _OFFSET = 1 + 8 _POS_OFFSET = _OFFSET + _MAX_INLINE * 2 class Encoder(ProtocolBuffer.Encoder): """Encodes Protocol Buffers in a form that sorts nicely.""" def put16(self, value): if value < 0 or value >= (1<<16): raise ProtocolBuffer.ProtocolBufferEncodeError('u16 too big') self.buf.append((value >> 8) & 0xff) self.buf.append((value >> 0) & 0xff) return def put32(self, value): if value < 0 or value >= (1<<32): raise ProtocolBuffer.ProtocolBufferEncodeError('u32 too big') self.buf.append((value >> 24) & 0xff) self.buf.append((value >> 16) & 0xff) self.buf.append((value >> 8) & 0xff) self.buf.append((value >> 0) & 0xff) return def put64(self, value): if value < 0 or value >= (1<<64): raise ProtocolBuffer.ProtocolBufferEncodeError('u64 too big') self.buf.append((value >> 56) & 0xff) self.buf.append((value >> 48) & 0xff) self.buf.append((value >> 40) & 0xff) self.buf.append((value >> 32) & 0xff) self.buf.append((value >> 24) & 0xff) self.buf.append((value >> 16) & 0xff) self.buf.append((value >> 8) & 0xff) self.buf.append((value >> 0) & 0xff) return def _PutVarInt(self, value): if value is None: self.buf.append(0) return if value >= _MIN_INLINE and value <= _MAX_INLINE: value = _OFFSET + (value - _MIN_INLINE) self.buf.append(value & 0xff) return negative = False if value < 0: value = _MIN_INLINE - value negative = True else: value = value - _MAX_INLINE len = 0 w = value while w > 0: w >>= 8 len += 1 if negative: head = _OFFSET - len else: head = _POS_OFFSET + len self.buf.append(head & 0xff) for i in range(len - 1, -1, -1): b = value >> (i * 8) if negative: b = _MAX_UNSIGNED_BYTE - (b & 0xff) self.buf.append(b & 0xff) def putVarInt32(self, value): if value >= 0x80000000 or value < -0x80000000: raise ProtocolBuffer.ProtocolBufferEncodeError('int32 too big') self._PutVarInt(value) def putVarInt64(self, value): if value >= 0x8000000000000000 or value < -0x8000000000000000: raise ProtocolBuffer.ProtocolBufferEncodeError('int64 too big') self._PutVarInt(value) def putVarUint64(self, value): if value < 0 or value >= 0x10000000000000000: raise ProtocolBuffer.ProtocolBufferEncodeError('uint64 too big') self._PutVarInt(value) def _isFloatNegative(self, value, encoded): if value == 0: return encoded[0] == 128 return value < 0 def putFloat(self, value): encoded = array.array('B') encoded.fromstring(struct.pack('>f', value)) if self._isFloatNegative(value, encoded): encoded[0] ^= 0xFF encoded[1] ^= 0xFF encoded[2] ^= 0xFF encoded[3] ^= 0xFF else: encoded[0] ^= 0x80 self.buf.extend(encoded) def putDouble(self, value): encoded = array.array('B') encoded.fromstring(struct.pack('>d', value)) if self._isFloatNegative(value, encoded): encoded[0] ^= 0xFF encoded[1] ^= 0xFF encoded[2] ^= 0xFF encoded[3] ^= 0xFF encoded[4] ^= 0xFF encoded[5] ^= 0xFF encoded[6] ^= 0xFF encoded[7] ^= 0xFF else: encoded[0] ^= 0x80 self.buf.extend(encoded) def putPrefixedString(self, value): self.buf.fromstring( value.replace('\x01', '\x01\x02').replace('\x00', '\x01\x01') + '\x00') class Decoder(ProtocolBuffer.Decoder): def __init__(self, buf, idx=0, limit=None): if not limit: limit = len(buf) ProtocolBuffer.Decoder.__init__(self, buf, idx, limit) def get16(self): if self.idx + 2 > self.limit: raise ProtocolBuffer.ProtocolBufferDecodeError('truncated') c = self.buf[self.idx] d = self.buf[self.idx + 1] self.idx += 2 return (c << 8) | d def get32(self): if self.idx + 4 > self.limit: raise ProtocolBuffer.ProtocolBufferDecodeError('truncated') c = int(self.buf[self.idx]) d = self.buf[self.idx + 1] e = self.buf[self.idx + 2] f = self.buf[self.idx + 3] self.idx += 4 return (c << 24) | (d << 16) | (e << 8) | f def get64(self): if self.idx + 8 > self.limit: raise ProtocolBuffer.ProtocolBufferDecodeError('truncated') c = int(self.buf[self.idx]) d = int(self.buf[self.idx + 1]) e = int(self.buf[self.idx + 2]) f = int(self.buf[self.idx + 3]) g = int(self.buf[self.idx + 4]) h = self.buf[self.idx + 5] i = self.buf[self.idx + 6] j = self.buf[self.idx + 7] self.idx += 8 return ((c << 56) | (d << 48) | (e << 40) | (f << 32) | (g << 24) | (h << 16) | (i << 8) | j) def getVarInt64(self): b = self.get8() if b >= _OFFSET and b <= _POS_OFFSET: return b - _OFFSET + _MIN_INLINE if b == 0: return None if b < _OFFSET: negative = True bytes = _OFFSET - b else: negative = False bytes = b - _POS_OFFSET ret = 0 for _ in range(bytes): b = self.get8() if negative: b = _MAX_UNSIGNED_BYTE - b ret = ret << 8 | b if negative: return _MIN_INLINE - ret else: return ret + _MAX_INLINE def getVarInt32(self): result = self.getVarInt64() if result >= 0x80000000 or result < -0x80000000: raise ProtocolBuffer.ProtocolBufferDecodeError('corrupted') return result def getVarUint64(self): result = self.getVarInt64() if result < 0: raise ProtocolBuffer.ProtocolBufferDecodeError('corrupted') return result def getFloat(self): if self.idx + 4 > self.limit: raise ProtocolBuffer.ProtocolBufferDecodeError('truncated') a = self.buf[self.idx:self.idx+4] self.idx += 4 if a[0] & 0x80: a[0] ^= 0x80 else: a = [x ^ 0xFF for x in a] return struct.unpack('>f', array.array('B', a).tostring())[0] def getDouble(self): if self.idx + 8 > self.limit: raise ProtocolBuffer.ProtocolBufferDecodeError('truncated') a = self.buf[self.idx:self.idx+8] self.idx += 8 if a[0] & 0x80: a[0] ^= 0x80 else: a = [x ^ 0xFF for x in a] return struct.unpack('>d', array.array('B', a).tostring())[0] def getPrefixedString(self): end_idx = self.idx while self.buf[end_idx] != 0: end_idx += 1 data = array.array('B', self.buf[self.idx:end_idx]).tostring() self.idx = end_idx + 1 return data.replace('\x01\x01', '\x00').replace('\x01\x02', '\x01')
{ "content_hash": "f20b8e891b2b745edef9f7c50b13a837", "timestamp": "", "source": "github", "line_count": 294, "max_line_length": 80, "avg_line_length": 26.346938775510203, "alnum_prop": 0.6148980118770978, "repo_name": "Suwmlee/XX-Net", "id": "6d7cbd092c17ca0b61747ca5579ac0b9d3d24c63", "size": "8352", "binary": false, "copies": "1", "ref": "refs/heads/python3", "path": "gae_proxy/server/lib/google/appengine/datastore/sortable_pb_encoder.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "200" }, { "name": "C", "bytes": "33097" }, { "name": "CSS", "bytes": "86345" }, { "name": "HTML", "bytes": "141382" }, { "name": "JavaScript", "bytes": "345991" }, { "name": "PHP", "bytes": "10671" }, { "name": "Python", "bytes": "17312939" }, { "name": "Shell", "bytes": "4647" }, { "name": "Visual Basic", "bytes": "382" } ], "symlink_target": "" }
layout: post title: "Welcome to Jekyll!" date: 2014-12-30 12:14 categories: announcement background-image: "/assets/backgrounds/FinkLooking.jpg" excerpt: "This is the default post that tells you..." --- You’ll find this post in your `_posts` directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run `jekyll serve --watch`, which launches a web server and auto-regenerates your site when a file is updated. To add new posts, simply add a file in the `_posts` directory that follows the convention `YYYY-MM-DD-name-of-post.ext` and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works. Jekyll also offers powerful support for code snippets: {% highlight ruby %} def print_hi(name) puts "Hi, #{name}" end print_hi('Tom') #=> prints 'Hi, Tom' to STDOUT. {% endhighlight %} Check out the [Jekyll docs][jekyll] for more info on how to get the most out of Jekyll. File all bugs/feature requests at [Jekyll’s GitHub repo][jekyll-gh]. If you have questions, you can ask them on [Jekyll’s dedicated Help repository][jekyll-help]. [jekyll]: http://jekyllrb.com [jekyll-gh]: https://github.com/jekyll/jekyll [jekyll-help]: https://github.com/jekyll/jekyll-help
{ "content_hash": "9dfaf1022822af75cc6556df29be48db", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 303, "avg_line_length": 49.111111111111114, "alnum_prop": 0.7413273001508296, "repo_name": "CharlesBean/Interpolate", "id": "87e565c3c6fe92cb6db6694512a96ee57522d8f4", "size": "1336", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Code/site/_posts/2014-12-30-welcome-to-jekyll.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "99157" }, { "name": "JavaScript", "bytes": "2244" } ], "symlink_target": "" }
var should = require('chai').should(); var lib = require('../src/lib.js'); var nock = require('nock'); var debug = require('debug')('test'); nock.disableNetConnect(); nock.enableNetConnect(/slacksecret.herokuapp.com/); describe("lib keepalive function", function() { before(function() { nock('https://slacksecret.herokuapp.com') .get('/') .reply(200, {message: "OK"}) .get("/error") .replyWithError('it was me'); }); it("should make successfull http request", function(done) { lib.wakeUp('https://slacksecret.herokuapp.com', function(err, responseCode) { responseCode.should.equal(200); done(); }); }); it("should handle errors gracefully", function(done) { lib.wakeUp('https://slacksecret.herokuapp.com/error', function(err, responseCode) { err.should.equal('Error calling self wakeup: Error: it was me'); done(); }); }); }); describe("lib JSON parsing function", function() { it("should return JSON if parse was successfull", function() { lib.safelyParseJson("{\"valid\":\"JSON\"}", function(json) { json.should.have.ownProperty("valid"); }); }); it("should return undefined if JSON parse failed", function() { lib.safelyParseJson("{\"invalid:\"JSON\"}", function(json) { should.not.exist(json); }); }); }); describe("send secret button to Slack channel", function() { before(function() { nock.cleanAll(); nock('https://hooks.slack.com') .post('/sendSecret') .reply(200, "wee") .post('/error') .replyWithError("it was me"); }); it("should return 200", function(done) { lib.sendSecret('https://hooks.slack.com/sendSecret', 'jordan.neufeld', 'a1B2c3D4', function(err, res) { res.should.equal(200); done(); }); }); it("should handle errors gracefully", function(done) { lib.sendSecret('https://hooks.slack.com/error', 'jordan.neufeld', 'a1B2c3D4', function(err, res) { debug(err); err.should.equal('Error posting secret button to slack Error: it was me'); done(); }); }); }); describe("send error message to slack channel", function() { before(function() { nock.cleanAll(); nock('https://hooks.slack.com') .post('/sendSecret') .reply(200, "wee"); }); it("should return 200", function(done) { lib.sendErrorMessage('https://hooks.slack.com/sendSecret', 'this is an error message', [], function(err, res) { res.should.equal(200); done(); }); }); });
{ "content_hash": "1a71af14f3214dac383f89a116439e2e", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 115, "avg_line_length": 31.3, "alnum_prop": 0.6178115015974441, "repo_name": "neufeldtech/secret-message", "id": "74aa51429130184e26816e60a1072bb61ab24fa3", "size": "2504", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/lib.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "133952" }, { "name": "HTML", "bytes": "18434" }, { "name": "JavaScript", "bytes": "47557" } ], "symlink_target": "" }
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'ProductTypeIcon.name' db.add_column('cmsplugin_configurableproduct_producttypeicon', 'name', self.gf('django.db.models.fields.CharField')(default='small', max_length=128), keep_default=False) def backwards(self, orm): # Deleting field 'ProductTypeIcon.name' db.delete_column('cmsplugin_configurableproduct_producttypeicon', 'name') models = { 'cms.cmsplugin': { 'Meta': {'object_name': 'CMSPlugin'}, 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}), 'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}), 'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}), 'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, 'cms.placeholder': { 'Meta': {'object_name': 'Placeholder'}, 'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}) }, 'cmsplugin_configurableproduct.cproductsplugin': { 'Meta': {'object_name': 'CProductsPlugin', 'db_table': "'cmsplugin_cproductsplugin'", '_ormbases': ['cms.CMSPlugin']}, 'categories': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['configurableproduct.ProductType']", 'symmetrical': 'False'}), 'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}), 'filter_action': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True', 'blank': 'True'}), 'filter_product_attributes': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}), 'hide_empty_categories': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'template': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}) }, 'cmsplugin_configurableproduct.cproducttypesplugin': { 'Meta': {'object_name': 'CProductTypesPlugin', 'db_table': "'cmsplugin_cproducttypesplugin'", '_ormbases': ['cms.CMSPlugin']}, 'categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['configurableproduct.ProductType']", 'null': 'True', 'blank': 'True'}), 'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}), 'hide_empty_categories': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'template': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}) }, 'cmsplugin_configurableproduct.producttypeicon': { 'Meta': {'object_name': 'ProductTypeIcon'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'default': "'small'", 'max_length': '128'}), 'product_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'icons'", 'to': "orm['configurableproduct.ProductType']"}) }, 'configurableproduct.productbooleanfield': { 'Meta': {'object_name': 'ProductBooleanField'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'configurableproduct.productcharfield': { 'Meta': {'object_name': 'ProductCharField'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'configurableproduct.productfloatfield': { 'Meta': {'object_name': 'ProductFloatField'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'configurableproduct.productimagefield': { 'Meta': {'object_name': 'ProductImageField'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'configurableproduct.producttype': { 'Meta': {'object_name': 'ProductType'}, 'boolean_fields': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['configurableproduct.ProductBooleanField']", 'null': 'True', 'through': "orm['configurableproduct.TypeBoolean']", 'blank': 'True'}), 'char_fields': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['configurableproduct.ProductCharField']", 'null': 'True', 'through': "orm['configurableproduct.TypeChar']", 'blank': 'True'}), 'float_fields': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['configurableproduct.ProductFloatField']", 'null': 'True', 'through': "orm['configurableproduct.TypeFloat']", 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image_fields': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['configurableproduct.ProductImageField']", 'null': 'True', 'through': "orm['configurableproduct.TypeImage']", 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}) }, 'configurableproduct.typeboolean': { 'Meta': {'ordering': "['order']", 'object_name': 'TypeBoolean'}, 'field': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['configurableproduct.ProductBooleanField']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['configurableproduct.ProductType']"}) }, 'configurableproduct.typechar': { 'Meta': {'ordering': "['order']", 'object_name': 'TypeChar'}, 'field': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['configurableproduct.ProductCharField']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['configurableproduct.ProductType']"}) }, 'configurableproduct.typefloat': { 'Meta': {'ordering': "['order']", 'object_name': 'TypeFloat'}, 'field': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['configurableproduct.ProductFloatField']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['configurableproduct.ProductType']"}) }, 'configurableproduct.typeimage': { 'Meta': {'ordering': "['order']", 'object_name': 'TypeImage'}, 'field': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['configurableproduct.ProductImageField']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['configurableproduct.ProductType']"}) } } complete_apps = ['cmsplugin_configurableproduct']
{ "content_hash": "dbd6082272cdbe0c316a9c093c80dbea", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 254, "avg_line_length": 76.28455284552845, "alnum_prop": 0.5855270169455398, "repo_name": "airtonix/cmsplugin-configurableproduct", "id": "36a6d7e17e26dd9819c58c0b240d983312354649", "size": "9401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmsplugin_configurableproduct/migrations/0005_auto__add_field_producttypeicon_name.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "89125" } ], "symlink_target": "" }
<?php namespace RcmAdminTest\EventListener; use RcmAdmin\EventListener\DispatchListener; use Zend\Mvc\MvcEvent; use Zend\Mvc\Router\Http\RouteMatch; use Zend\ServiceManager\ServiceManager; use Zend\View\Model\ViewModel; require_once __DIR__ . '/../autoload.php'; /** * Unit Test for Dispatch Listener Event * * Unit Test for Dispatch Listener Event * * @category Reliv * @package RcmAdmin * @author Westin Shafer <wshafer@relivinc.com> * @copyright 2012 Reliv International * @license License.txt New BSD License * @version Release: 1.0 * @link http://github.com/reliv */ class DispatchListenerTest extends \PHPUnit_Framework_TestCase { /** @var \PHPUnit_Framework_MockObject_MockObject */ protected $mockController; /** @var \RcmAdmin\EventListener\DispatchListener */ protected $listener; /** * Setup for tests * * @return void */ public function setup() { $this->mockController = $this ->getMockBuilder('\RcmAdmin\Controller\AdminPanelController') ->disableOriginalConstructor() ->getMock(); /** @var \RcmAdmin\Controller\AdminPanelController $mockController */ $mockController = $this->mockController; $serviceManager = new ServiceManager(); $serviceManager->setService('RcmAdmin\Controller\AdminPanelController', $mockController); $this->listener = new DispatchListener($serviceManager); } /** * Test Constructor * * @return void * * @covers \RcmAdmin\EventListener\DispatchListener::__construct */ public function testConstructor() { $this->assertTrue($this->listener instanceof DispatchListener); } /** * Test Get Admin Panel Returns Panel * * @return void * * @covers \RcmAdmin\EventListener\DispatchListener::getAdminPanel */ public function testGetAdminPanel() { $layoutViewMock = new ViewModel(); $event = new MvcEvent(); $routeMatch = new RouteMatch([]); $event->setRouteMatch($routeMatch); $event->setViewModel($layoutViewMock); $mockAdminPanel = new ViewModel(); $mockAdminPanel->setVariable('This-is-a-test', true); $this->mockController->expects($this->once()) ->method('getAdminWrapperAction') ->will($this->returnValue($mockAdminPanel)); $this->listener->getAdminPanel($event); /** @var \Zend\View\Model\ViewModel $panelView */ $children = $layoutViewMock->getChildrenByCaptureTo('rcmAdminPanel'); $this->assertNotEmpty($children); $this->assertCount(1, $children); $panelView = $children[0]; $this->assertTrue($panelView instanceof ViewModel); /* Verify correct model */ $testViewVar = $panelView->getVariable('This-is-a-test'); $this->assertTrue($testViewVar); // No Match $event = new MvcEvent(); $this->assertNull($this->listener->getAdminPanel($event)); } /** * Test Get Admin Panel No Panel Returned * * @return void * * @covers \RcmAdmin\EventListener\DispatchListener::getAdminPanel */ public function testGetAdminPanelReturnsNoView() { $layoutViewMock = new ViewModel(); $event = new MvcEvent(); $routeMatch = new RouteMatch([]); $event->setRouteMatch($routeMatch); $event->setViewModel($layoutViewMock); $this->mockController->expects($this->once()) ->method('getAdminWrapperAction') ->will($this->returnValue(null)); $this->listener->getAdminPanel($event); /** @var \Zend\View\Model\ViewModel $panelView */ $children = $layoutViewMock->getChildrenByCaptureTo('rcmAdminPanel'); $this->assertEmpty($children); } }
{ "content_hash": "19c09e444c0b37a402facd9ec0691138", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 97, "avg_line_length": 27.295774647887324, "alnum_prop": 0.6302889576883385, "repo_name": "bjanish/rcm-admin", "id": "d30a6680317b91c344ec2b74cd22ca0397458bd8", "size": "4280", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/EventListener/DispatchListenerTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "18204" }, { "name": "HTML", "bytes": "50792" }, { "name": "JavaScript", "bytes": "141262" }, { "name": "PHP", "bytes": "195302" } ], "symlink_target": "" }
// // ReadInfoVC.m // HppleDemo // // Created by zero on 15/7/20. // // #import "ReadInfoVC.h" #import "TFHpple.h" @interface ReadInfoVC () @property (nonatomic,strong) TFHpple* tfHpple; @property (nonatomic,strong) UITextView* textView; @property (nonatomic,strong) NSString* info; @property (nonatomic,strong) NSMutableArray* otherPageArray;; @end @implementation ReadInfoVC - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"%@",_url); _otherPageArray = [NSMutableArray array]; _info = @""; NSError* error = nil; NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_url] options:NSDataReadingMappedAlways error:&error]; NSLog(@"%@",error.description); if(data == nil){ return; } _tfHpple = [[TFHpple alloc]initWithHTMLData:data]; [self getInfoFromTF:_tfHpple]; _textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))]; _textView.text = _info; _textView.editable = NO; [self.view addSubview:_textView]; // [self getAllPage]; dispatch_async(dispatch_get_global_queue(0, 0), ^{ [self getAllPage]; }); } - (void)getInfoFromTF:(TFHpple*)tf{ NSArray* array = [tf searchWithXPathQuery:@"//div[@class='n_bd']"]; for(TFHppleElement* element in array){ NSLog(@"%@",element.content); _info = [NSString stringWithFormat:@"%@%@",_info,element.content]; } } - (void)getAllPage{ NSArray* array = [[_tfHpple searchWithXPathQuery:@"//div[@class='pagea']"][0]children]; for(TFHppleElement* element in array){ NSLog(@"%@",element.content); if([element.tagName isEqualToString:@"a"]){ NSString* string = [element.attributes objectForKeyedSubscript:@"href"]; if(string.length > 0){ [_otherPageArray addObject:[NSString stringWithFormat:@"http://www.1100lu.us%@",string]]; } } } for(NSString* string in _otherPageArray){ NSError* error = nil; NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:string] options:NSDataReadingMappedAlways error:&error]; NSLog(@"%@",error.description); TFHpple* tf = [[TFHpple alloc]initWithHTMLData:data]; [self getInfoFromTF:tf]; } dispatch_async(dispatch_get_main_queue(), ^{ _textView.text = _info; }); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end
{ "content_hash": "66866b1979ab1c7822e913c86f8eb04f", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 134, "avg_line_length": 31.358695652173914, "alnum_prop": 0.6589254766031196, "repo_name": "cliulang/hpple-master-XML", "id": "5f1935ea5325a30b5af517bb622e6464868314b4", "size": "2885", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/HppleDemo/ReadInfoVC.m", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "24203" }, { "name": "Objective-C", "bytes": "53777" }, { "name": "Ruby", "bytes": "607" } ], "symlink_target": "" }
@interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]; self.window.backgroundColor = [UIColor whiteColor]; ViewController * rootVc = [[ViewController alloc] init]; UINavigationController * navc = [[UINavigationController alloc] initWithRootViewController:rootVc]; self.window.rootViewController = navc; [self.window becomeKeyWindow]; [self.window makeKeyWindow]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @end
{ "content_hash": "58ce9265f28f86d8bbfdd1673cf3f19a", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 281, "avg_line_length": 48.91489361702128, "alnum_prop": 0.7785993910395824, "repo_name": "Jordan150513/OCDemos", "id": "981c07f3d88c284050aef91f33fd46b51c9dfb60", "size": "2491", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RoundCornerDemo/RoundCornerDemo/AppDelegate.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1207703" }, { "name": "Ruby", "bytes": "1273" } ], "symlink_target": "" }
package io.kraken.client.impl; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import io.kraken.client.KrakenIoClient; import io.kraken.client.exception.KrakenIoException; import io.kraken.client.exception.KrakenIoRequestException; import io.kraken.client.model.Auth; import io.kraken.client.model.AuthWrapper; import io.kraken.client.model.request.*; import io.kraken.client.model.response.AbstractUploadResponse; import io.kraken.client.model.response.FailedUploadResponse; import io.kraken.client.model.response.SuccessfulUploadCallbackUrlResponse; import io.kraken.client.model.response.SuccessfulUploadResponse; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.logging.LoggingFeature; import org.glassfish.jersey.media.multipart.BodyPart; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.MultiPart; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Feature; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.text.MessageFormat; import java.util.UUID; import java.util.logging.Level; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * @author Emir Dizdarevic * @since 1.0.0 */ public class DefaultKrakenIoClient implements KrakenIoClient { private static final java.util.logging.Logger JERSEY_LOGGER = java.util.logging.Logger.getLogger(DefaultKrakenIoClient.class.getCanonicalName()); private static final String DEFAULT_BASE_URL = "https://api.kraken.io"; private static final String DIRECT_UPLOAD_ENDPOINT = "{0}/v1/upload"; private static final String IMAGE_URL_ENDPOINT = "{0}/v1/url"; private static final String DATA_PART = "data"; private static final String UPLOAD_PART = "upload"; private static final int CLIENT_TIMEOUT = 3000; private final javax.ws.rs.client.Client client; private final String apiKey; private final String apiSecret; private final String directUploadUrl; private final String imageUrl; public DefaultKrakenIoClient(String apiKey, String apiSecret) { this(apiKey, apiSecret, DEFAULT_BASE_URL, CLIENT_TIMEOUT); } public DefaultKrakenIoClient(String apiKey, String apiSecret, String baseUrl) { this(apiKey, apiSecret, baseUrl, CLIENT_TIMEOUT); } public DefaultKrakenIoClient(String apiKey, String apiSecret, int timeout) { this(apiKey, apiSecret, DEFAULT_BASE_URL, timeout); } public DefaultKrakenIoClient(String apiKey, String apiSecret, String baseUrl, int timeout) { checkNotNull(apiKey, "apiKey must not be null"); checkArgument(!apiKey.isEmpty(), "apiKey must not be empty"); checkNotNull(apiSecret, "apiSecret must not be null"); checkArgument(!apiSecret.isEmpty(), "apiSecret must not be empty"); checkNotNull(baseUrl, "baseUrl must not be null"); checkArgument(!baseUrl.isEmpty(), "baseUrl must not be empty"); checkNotNull(timeout, "timeout must not be null"); this.apiKey = apiKey; this.apiSecret = apiSecret; this.directUploadUrl = MessageFormat.format(DIRECT_UPLOAD_ENDPOINT, baseUrl); this.imageUrl = MessageFormat.format(IMAGE_URL_ENDPOINT, baseUrl); this.client = createClient(createObjectMapper(), timeout); } private Client createClient(ObjectMapper objectMapper, int timeout) { final ClientConfig clientConfig = new ClientConfig(); clientConfig.property(ClientProperties.FOLLOW_REDIRECTS, true); clientConfig.property(ClientProperties.CONNECT_TIMEOUT, timeout); clientConfig.property(ClientProperties.READ_TIMEOUT, timeout); clientConfig.property(ClientProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); final JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider(objectMapper); final Client client = ClientBuilder.newClient(clientConfig).register(jacksonJsonProvider).register(MultiPartFeature.class); final Feature feature = new LoggingFeature(JERSEY_LOGGER, Level.FINE, LoggingFeature.Verbosity.PAYLOAD_ANY, null); client.register(feature); return client; } private ObjectMapper createObjectMapper() { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS); objectMapper.enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS); return objectMapper; } @Override public SuccessfulUploadResponse directUpload(DirectUploadRequest directUploadRequest) { return directUpload(directUploadRequest, new StreamDataBodyPart(UPLOAD_PART, directUploadRequest.getImage(), UUID.randomUUID().toString())); } @Override public SuccessfulUploadResponse directUpload(DirectFileUploadRequest directFileUploadRequest) { return directUpload(directFileUploadRequest, new FileDataBodyPart(UPLOAD_PART, directFileUploadRequest.getImage())); } @Override public SuccessfulUploadResponse imageUrlUpload(ImageUrlUploadRequest imageUrlUploadRequest) { final WebTarget webTarget = client.target(imageUrl); final Response response = webTarget.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(wrapAuth(imageUrlUploadRequest), MediaType.APPLICATION_JSON_TYPE)); return handleResponse(response); } @Override public SuccessfulUploadCallbackUrlResponse directUpload(DirectUploadCallbackUrlRequest directUploadCallbackUrlRequest) { return directCallbackUrlUpload(directUploadCallbackUrlRequest, new StreamDataBodyPart(UPLOAD_PART, directUploadCallbackUrlRequest.getImage(), UUID.randomUUID().toString())); } @Override public SuccessfulUploadCallbackUrlResponse directUpload(DirectFileUploadCallbackUrlRequest directFileUploadCallbackUrlRequest) { return directCallbackUrlUpload(directFileUploadCallbackUrlRequest, new FileDataBodyPart(UPLOAD_PART, directFileUploadCallbackUrlRequest.getImage())); } @Override public SuccessfulUploadCallbackUrlResponse imageUrlUpload(ImageUrlUploadCallbackUrlRequest imageUrlUploadCallbackUrlRequest) { final WebTarget webTarget = client.target(imageUrl); final Response response = webTarget.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(wrapAuth(imageUrlUploadCallbackUrlRequest), MediaType.APPLICATION_JSON_TYPE)); return handleCallbackUrlResponse(response); } private AuthWrapper wrapAuth(AbstractUploadRequest abstractUploadRequest) { return new AuthWrapper(new Auth(apiKey, apiSecret), abstractUploadRequest); } private SuccessfulUploadResponse directUpload(AbstractUploadRequest abstractUploadRequest, BodyPart bodyPart) { return handleResponse(handleRequest(abstractUploadRequest, bodyPart)); } private SuccessfulUploadCallbackUrlResponse directCallbackUrlUpload(AbstractUploadRequest abstractUploadRequest, BodyPart bodyPart) { return handleCallbackUrlResponse(handleRequest(abstractUploadRequest, bodyPart)); } private Response handleRequest(AbstractUploadRequest abstractUploadRequest, BodyPart bodyPart) { final WebTarget webTarget = client.target(directUploadUrl); final MultiPart multiPart = new MultiPart(); multiPart.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE); multiPart.bodyPart(new FormDataBodyPart(DATA_PART, wrapAuth(abstractUploadRequest), MediaType.APPLICATION_JSON_TYPE)); multiPart.bodyPart(bodyPart); return webTarget.request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(multiPart, multiPart.getMediaType())); } private SuccessfulUploadResponse handleResponse(Response response) { try { final AbstractUploadResponse abstractUploadResponse = response.readEntity(AbstractUploadResponse.class); abstractUploadResponse.setStatus(response.getStatus()); if (response.getStatus() == 200) { return (SuccessfulUploadResponse) abstractUploadResponse; } else { throw new KrakenIoRequestException("Kraken.io request failed", (FailedUploadResponse) abstractUploadResponse); } } catch (KrakenIoRequestException e) { throw e; } catch (Exception e) { throw new KrakenIoException("Failed to unmarshall response", e); } } private SuccessfulUploadCallbackUrlResponse handleCallbackUrlResponse(Response response) { try { if (response.getStatus() == 200) { return response.readEntity(SuccessfulUploadCallbackUrlResponse.class); } else { final FailedUploadResponse failedUploadResponse = response.readEntity(FailedUploadResponse.class); failedUploadResponse.setStatus(response.getStatus()); throw new KrakenIoRequestException("Kraken.io request failed", failedUploadResponse); } } catch (KrakenIoRequestException e) { throw e; } catch (Exception e) { throw new KrakenIoException("Failed to unmarshall response", e); } } }
{ "content_hash": "749da5c7a37e7d31973aa0e8490d3706", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 182, "avg_line_length": 48.923809523809524, "alnum_prop": 0.7588086431769515, "repo_name": "kraken-io/kraken-java", "id": "3b03527c9538ff33db01c39b00d6e3c3d73fd5ec", "size": "10891", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/io/kraken/client/impl/DefaultKrakenIoClient.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "109615" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "ee9d32f0abf977d9a4493ef3c4cbe369", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "7ec16bbeada3a5329033bbe25bbde55679e71002", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Scrophulariaceae/Tetraselago/Tetraselago nelsonii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<resources> <string name="app_name">Pulsator4Droid</string> <string name="image_description_android_phone">Android Phone Image</string> <string name="label_count">Count</string> <string name="label_duration">Duration</string> </resources>
{ "content_hash": "b5e7289fa187c04688e8b9404241beb7", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 79, "avg_line_length": 42.5, "alnum_prop": 0.7215686274509804, "repo_name": "booncol/Pulsator4Droid", "id": "f8665c787af01352fb1b126d381dd8d834c12dd5", "size": "255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo/src/main/res/values/strings.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "15903" } ], "symlink_target": "" }
package bio.terra.service.auth.iam; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import bio.terra.common.PdaoConstant; import bio.terra.common.TestUtils; import bio.terra.common.auth.AuthService; import bio.terra.common.category.OnDemand; import bio.terra.common.configuration.TestConfiguration; import bio.terra.common.iam.AuthenticatedUserRequest; import bio.terra.integration.BigQueryFixtures; import bio.terra.integration.DataRepoFixtures; import bio.terra.integration.DataRepoResponse; import bio.terra.integration.GcsFixtures; import bio.terra.integration.UsersBase; import bio.terra.model.DRSObject; import bio.terra.model.DatasetModel; import bio.terra.model.DatasetSummaryModel; import bio.terra.model.EnumerateDatasetModel; import bio.terra.model.FileModel; import bio.terra.model.IngestRequestModel; import bio.terra.model.IngestResponseModel; import bio.terra.model.SnapshotModel; import bio.terra.model.SnapshotRetrieveIncludeModel; import bio.terra.model.SnapshotSummaryModel; import bio.terra.service.configuration.ConfigEnum; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.ReadChannel; import com.google.cloud.WriteChannel; import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.TableResult; import com.google.cloud.storage.BlobId; import com.google.cloud.storage.BlobInfo; import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.apache.commons.lang.StringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles({"google", "integrationtest"}) @Category(OnDemand.class) @SuppressFBWarnings( value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "Spurious RCN check; related to Java 11") public class AccessTest extends UsersBase { private static final Logger logger = LoggerFactory.getLogger(AccessTest.class); @Autowired private DataRepoFixtures dataRepoFixtures; @Autowired private AuthService authService; @Autowired private IamProviderInterface iamService; @Autowired private TestConfiguration testConfiguration; private String discovererToken; private String readerToken; private String custodianToken; private DatasetSummaryModel datasetSummaryModel; private UUID datasetId; private UUID profileId; private List<UUID> snapshotIds; @Before public void setup() throws Exception { super.setup(); discovererToken = authService.getDirectAccessAuthToken(discoverer().getEmail()); readerToken = authService.getDirectAccessAuthToken(reader().getEmail()); custodianToken = authService.getDirectAccessAuthToken(custodian().getEmail()); profileId = dataRepoFixtures.createBillingProfile(steward()).getId(); datasetId = null; snapshotIds = new ArrayList<>(); } @After public void teardown() throws Exception { for (UUID snapshotId : snapshotIds) { dataRepoFixtures.deleteSnapshotLog(steward(), snapshotId); } if (datasetId != null) { dataRepoFixtures.deleteDatasetLog(steward(), datasetId); } } private void makeIngestTestDataset() throws Exception { datasetSummaryModel = dataRepoFixtures.createDataset(steward(), profileId, "ingest-test-dataset.json"); datasetId = datasetSummaryModel.getId(); } private void makeAclTestDataset() throws Exception { datasetSummaryModel = dataRepoFixtures.createDataset(steward(), profileId, "file-acl-test-dataset.json"); datasetId = datasetSummaryModel.getId(); } private Storage getStorage(String token) { GoogleCredentials googleCredentials = GoogleCredentials.create(new AccessToken(token, null)); return GcsFixtures.getStorage(googleCredentials); } @Test public void checkShared() throws Exception { makeIngestTestDataset(); IngestRequestModel request = dataRepoFixtures.buildSimpleIngest( "participant", "ingest-test/ingest-test-participant.json"); dataRepoFixtures.ingestJsonData(steward(), datasetId, request); request = dataRepoFixtures.buildSimpleIngest("sample", "ingest-test/ingest-test-sample.json"); dataRepoFixtures.ingestJsonData(steward(), datasetId, request); DatasetModel dataset = dataRepoFixtures.getDataset(steward(), datasetId); String datasetBqSnapshotName = "datarepo_" + dataset.getName(); BigQuery custodianBigQuery = BigQueryFixtures.getBigQuery(dataset.getDataProject(), custodianToken); try { BigQueryFixtures.datasetExists( custodianBigQuery, dataset.getDataProject(), datasetBqSnapshotName); fail("custodian shouldn't be able to access bq dataset before it is shared with them"); } catch (IllegalStateException e) { assertThat( "checking message for pdao exception error", e.getMessage(), equalTo("existence check failed for " + datasetBqSnapshotName)); } dataRepoFixtures.addDatasetPolicyMember( steward(), datasetId, IamRole.CUSTODIAN, custodian().getEmail()); DataRepoResponse<EnumerateDatasetModel> enumDatasets = dataRepoFixtures.enumerateDatasetsRaw(custodian()); assertThat( "Custodian is authorized to enumerate datasets", enumDatasets.getStatusCode(), equalTo(HttpStatus.OK)); boolean custodianHasAccess = BigQueryFixtures.hasAccess( custodianBigQuery, dataset.getDataProject(), datasetBqSnapshotName); assertThat( "custodian can access the bq snapshot after it has been shared", custodianHasAccess, equalTo(true)); SnapshotSummaryModel snapshotSummaryModel = dataRepoFixtures.createSnapshot( custodian(), datasetSummaryModel.getName(), profileId, "ingest-test-snapshot.json"); SnapshotModel snapshotModel = dataRepoFixtures.getSnapshot( custodian(), snapshotSummaryModel.getId(), List.of(SnapshotRetrieveIncludeModel.ACCESS_INFORMATION)); BigQuery bigQuery = BigQueryFixtures.getBigQuery(snapshotModel.getDataProject(), readerToken); try { BigQueryFixtures.datasetExists( bigQuery, snapshotModel.getAccessInformation().getBigQuery().getProjectId(), snapshotModel.getAccessInformation().getBigQuery().getDatasetName()); fail("reader shouldn't be able to access bq dataset before it is shared with them"); } catch (IllegalStateException e) { assertThat( "checking message for exception error", e.getMessage(), equalTo("existence check failed for ".concat(snapshotSummaryModel.getName()))); } dataRepoFixtures.addSnapshotPolicyMember( custodian(), snapshotSummaryModel.getId(), IamRole.READER, reader().getEmail()); AuthenticatedUserRequest authenticatedReaderRequest = AuthenticatedUserRequest.builder() .setEmail(reader().getEmail()) .setToken(readerToken) .build(); assertThat( "correctly added reader", iamService.isAuthorized( authenticatedReaderRequest, IamResourceType.DATASNAPSHOT, snapshotSummaryModel.getId().toString(), IamAction.READ_DATA), equalTo(true)); boolean readerHasAccess = BigQueryFixtures.hasAccess( bigQuery, snapshotModel.getDataProject(), snapshotModel.getName()); assertThat( "reader can access the snapshot after it has been shared", readerHasAccess, equalTo(true)); } @Test public void fileAclTest() throws Exception { makeAclTestDataset(); dataRepoFixtures.addDatasetPolicyMember( steward(), datasetSummaryModel.getId(), IamRole.CUSTODIAN, custodian().getEmail()); // Ingest a file into the dataset String gsPath = "gs://" + testConfiguration.getIngestbucket(); FileModel fileModel = dataRepoFixtures.ingestFile( steward(), datasetSummaryModel.getId(), profileId, gsPath + "/files/File Design Notes.pdf", "/foo/bar"); // Ingest one row into the study 'file' table with a reference to that ingested file String json = String.format("{\"file_id\":\"foo\",\"file_ref\":\"%s\"}", fileModel.getFileId()); String targetPath = "scratch/file" + UUID.randomUUID().toString() + ".json"; BlobInfo targetBlobInfo = BlobInfo.newBuilder(BlobId.of(testConfiguration.getIngestbucket(), targetPath)).build(); Storage storage = StorageOptions.getDefaultInstance().getService(); try (WriteChannel writer = storage.writer(targetBlobInfo)) { writer.write(ByteBuffer.wrap(json.getBytes(StandardCharsets.UTF_8))); } IngestRequestModel request = dataRepoFixtures.buildSimpleIngest("file", targetPath); IngestResponseModel ingestResponseModel = dataRepoFixtures.ingestJsonData(steward(), datasetSummaryModel.getId(), request); assertThat("1 Row was ingested", ingestResponseModel.getRowCount(), equalTo(1L)); // Create a snapshot exposing the one row and grant read access to our reader. SnapshotSummaryModel snapshotSummaryModel = dataRepoFixtures.createSnapshot( custodian(), datasetSummaryModel.getName(), profileId, "file-acl-test-snapshot.json"); snapshotIds.add(snapshotSummaryModel.getId()); SnapshotModel snapshotModel = dataRepoFixtures.getSnapshot(custodian(), snapshotSummaryModel.getId(), null); dataRepoFixtures.addSnapshotPolicyMember( custodian(), snapshotModel.getId(), IamRole.READER, reader().getEmail()); AuthenticatedUserRequest authenticatedReaderRequest = AuthenticatedUserRequest.builder() .setEmail(reader().getEmail()) .setToken(readerToken) .build(); boolean authorized = iamService.isAuthorized( authenticatedReaderRequest, IamResourceType.DATASNAPSHOT, snapshotModel.getId().toString(), IamAction.READ_DATA); assertTrue("correctly added reader", authorized); // The reader does not have permission to make queries in any project, // so we have to use the custodian to look up the DRS id. BigQuery bigQueryCustodian = BigQueryFixtures.getBigQuery(snapshotModel.getDataProject(), custodianToken); BigQueryFixtures.hasAccess( bigQueryCustodian, snapshotModel.getDataProject(), snapshotModel.getName()); /* * WARNING: if making any changes to this test make sure to notify the #dsp-batch channel! Describe the change * and any consequences downstream to DRS clients. */ // Read and validate the DRS URI from the file ref column in the 'file' table. String drsObjectId = BigQueryFixtures.queryForDrsId(bigQueryCustodian, snapshotModel, "file", "file_ref"); // Use DRS API to lookup the file by DRS ID (pulled out of the URI). DRSObject drsObject = dataRepoFixtures.drsGetObject(reader(), drsObjectId); String gsuri = TestUtils.validateDrsAccessMethods(drsObject.getAccessMethods(), custodianToken); // Try to read the file of the gs path as reader and discoverer String[] strings = gsuri.split("/", 4); String bucketName = strings[2]; String blobName = strings[3]; BlobId blobId = BlobId.of(bucketName, blobName); Storage readerStorage = getStorage(readerToken); assertTrue("Reader can read some bytes of the file", canReadBlobRetry(readerStorage, blobId)); Storage discovererStorage = getStorage(discovererToken); assertFalse("Discoverer can not read the file", canReadBlob(discovererStorage, blobId)); } @Test public void fileAclFaultTest() throws Exception { try { // Run the fileAclTest with the SNAPSHOT_GRANT_FILE_ACCESS_FAULT on dataRepoFixtures.setFault( steward(), ConfigEnum.SNAPSHOT_GRANT_FILE_ACCESS_FAULT.name(), true); fileAclTest(); } finally { dataRepoFixtures.resetConfig(steward()); } } @Test public void checkCustodianPermissions() throws Exception { makeIngestTestDataset(); IngestRequestModel request = dataRepoFixtures.buildSimpleIngest( "participant", "ingest-test/ingest-test-participant.json"); dataRepoFixtures.ingestJsonData(steward(), datasetId, request); request = dataRepoFixtures.buildSimpleIngest("sample", "ingest-test/ingest-test-sample.json"); dataRepoFixtures.ingestJsonData(steward(), datasetId, request); DatasetModel dataset = dataRepoFixtures.getDataset(steward(), datasetId); String datasetBqSnapshotName = PdaoConstant.PDAO_PREFIX + dataset.getName(); BigQuery custodianBigQuery = BigQueryFixtures.getBigQuery(dataset.getDataProject(), custodianToken); try { BigQueryFixtures.datasetExists( custodianBigQuery, dataset.getDataProject(), datasetBqSnapshotName); fail("custodian shouldn't be able to access bq dataset before it is shared with them"); } catch (IllegalStateException e) { assertThat( "checking message for pdao exception error", e.getMessage(), equalTo("existence check failed for " + datasetBqSnapshotName)); } dataRepoFixtures.addDatasetPolicyMember( steward(), datasetId, IamRole.CUSTODIAN, custodian().getEmail()); DataRepoResponse<EnumerateDatasetModel> enumDatasets = dataRepoFixtures.enumerateDatasetsRaw(custodian()); assertThat( "Custodian is authorized to enumerate datasets", enumDatasets.getStatusCode(), equalTo(HttpStatus.OK)); boolean custodianHasAccess = BigQueryFixtures.hasAccess( custodianBigQuery, dataset.getDataProject(), datasetBqSnapshotName); assertTrue("custodian can access the bq snapshot after it has been shared", custodianHasAccess); // gets the "sample" table and makes a table ref to use in the query String tableRef = BigQueryFixtures.makeTableRef(dataset, dataset.getSchema().getTables().get(1).getName()); String sql = String.format("SELECT * FROM %s LIMIT %s", tableRef, 1000); TableResult results = BigQueryFixtures.query(sql, custodianBigQuery); Assert.assertEquals(7, results.getTotalRows()); } private boolean canReadBlob(Storage storage, BlobId blobId) throws Exception { try (ReadChannel reader = storage.reader(blobId)) { ByteBuffer bytes = ByteBuffer.allocate(64 * 1024); int bytesRead = reader.read(bytes); return (bytesRead > 0); } catch (Exception ex) { logger.info("Caught exception", ex); } return false; } private static final int RETRY_INITIAL_INTERVAL_SECONDS = 2; private static final int RETRY_MAX_INTERVAL_SECONDS = 30; private static final int RETRY_MAX_SLEEP_SECONDS = 420; private boolean canReadBlobRetry(Storage storage, BlobId blobId) throws Exception { int sleptSeconds = 0; int sleepSeconds = RETRY_INITIAL_INTERVAL_SECONDS; while (true) { try (ReadChannel reader = storage.reader(blobId)) { ByteBuffer bytes = ByteBuffer.allocate(64 * 1024); int bytesRead = reader.read(bytes); return (bytesRead > 0); } catch (Exception ex) { logger.info("Caught IO exception: " + ex.getMessage()); if ((sleptSeconds < RETRY_MAX_SLEEP_SECONDS) && StringUtils.contains(ex.getMessage(), "Forbidden")) { TimeUnit.SECONDS.sleep(sleepSeconds); sleptSeconds += sleepSeconds; logger.info("Slept " + sleepSeconds + " total slept " + sleptSeconds); sleepSeconds = Math.min(2 * sleepSeconds, RETRY_MAX_INTERVAL_SECONDS); } else { throw ex; } } } } }
{ "content_hash": "21b32e49469e230f9fd7f8cefdbc3019", "timestamp": "", "source": "github", "line_count": 411, "max_line_length": 114, "avg_line_length": 40.632603406326034, "alnum_prop": 0.725688622754491, "repo_name": "DataBiosphere/jade-data-repo", "id": "5d369c2466595412d14a3cb17b2a76ca5eba94f8", "size": "16700", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/test/java/bio/terra/service/auth/iam/AccessTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ANTLR", "bytes": "7971" }, { "name": "HTML", "bytes": "5990" }, { "name": "Java", "bytes": "4573023" }, { "name": "Python", "bytes": "6461" }, { "name": "Shell", "bytes": "43170" } ], "symlink_target": "" }
static uint8_t g_pui8OversampleFactor[3]; //***************************************************************************** // //! Returns the interrupt number for a given ADC base address and sequence //! number. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! This function returns the interrupt number for the ADC module and sequence //! number provided in the \e ui32Base and \e ui32SequenceNum parameters. //! //! \return Returns the ADC sequence interrupt number or 0 if the interrupt //! does not exist. // //***************************************************************************** static uint_fast8_t _ADCIntNumberGet(uint32_t ui32Base, uint32_t ui32SequenceNum) { uint_fast8_t ui8Int; // // Determine the interrupt to register based on the sequence number. // if(CLASS_IS_TM4C123) { ui8Int = ((ui32Base == ADC0_BASE) ? (INT_ADC0SS0_TM4C123 + ui32SequenceNum) : (INT_ADC1SS0_TM4C123 + ui32SequenceNum)); } else if(CLASS_IS_TM4C129) { ui8Int = ((ui32Base == ADC0_BASE) ? (INT_ADC0SS0_TM4C129 + ui32SequenceNum) : (INT_ADC1SS0_TM4C129 + ui32SequenceNum)); } else { ui8Int = 0; } return(ui8Int); } //***************************************************************************** // //! Registers an interrupt handler for an ADC interrupt. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! \param pfnHandler is a pointer to the function to be called when the //! ADC sample sequence interrupt occurs. //! //! This function sets the handler to be called when a sample sequence //! interrupt occurs. This function enables the global interrupt in the //! interrupt controller; the sequence interrupt must be enabled with //! ADCIntEnable(). It is the interrupt handler's responsibility to clear the //! interrupt source via ADCIntClear(). //! //! \sa IntRegister() for important information about registering interrupt //! handlers. //! //! \return None. // //***************************************************************************** void ADCIntRegister(uint32_t ui32Base, uint32_t ui32SequenceNum, void (*pfnHandler)(void)) { uint_fast8_t ui8Int; // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Determine the interrupt to register based on the sequence number. // ui8Int = _ADCIntNumberGet(ui32Base, ui32SequenceNum); ASSERT(ui8Int != 0); // // Register the interrupt handler. // IntRegister(ui8Int, pfnHandler); // // Enable the timer interrupt. // IntEnable(ui8Int); } //***************************************************************************** // //! Unregisters the interrupt handler for an ADC interrupt. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! This function unregisters the interrupt handler. This function disables //! the global interrupt in the interrupt controller; the sequence interrupt //! must be disabled via ADCIntDisable(). //! //! \sa IntRegister() for important information about registering interrupt //! handlers. //! //! \return None. // //***************************************************************************** void ADCIntUnregister(uint32_t ui32Base, uint32_t ui32SequenceNum) { uint_fast8_t ui8Int; // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Determine the interrupt to unregister based on the sequence number. // ui8Int = _ADCIntNumberGet(ui32Base, ui32SequenceNum); ASSERT(ui8Int != 0); // // Disable the interrupt. // IntDisable(ui8Int); // // Unregister the interrupt handler. // IntUnregister(ui8Int); } //***************************************************************************** // //! Disables a sample sequence interrupt. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! This function disables the requested sample sequence interrupt. //! //! \return None. // //***************************************************************************** void ADCIntDisable(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Disable this sample sequence interrupt. // HWREG(ui32Base + ADC_O_IM) &= ~(1 << ui32SequenceNum); } //***************************************************************************** // //! Enables a sample sequence interrupt. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! This function enables the requested sample sequence interrupt. Any //! outstanding interrupts are cleared before enabling the sample sequence //! interrupt. //! //! \return None. // //***************************************************************************** void ADCIntEnable(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Clear any outstanding interrupts on this sample sequence. // HWREG(ui32Base + ADC_O_ISC) = 1 << ui32SequenceNum; // // Enable this sample sequence interrupt. // HWREG(ui32Base + ADC_O_IM) |= 1 << ui32SequenceNum; } //***************************************************************************** // //! Gets the current interrupt status. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! \param bMasked is false if the raw interrupt status is required and true if //! the masked interrupt status is required. //! //! This function returns the interrupt status for the specified sample //! sequence. Either the raw interrupt status or the status of interrupts that //! are allowed to reflect to the processor can be returned. //! //! \return The current raw or masked interrupt status. // //***************************************************************************** uint32_t ADCIntStatus(uint32_t ui32Base, uint32_t ui32SequenceNum, bool bMasked) { uint32_t ui32Temp; // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Return either the interrupt status or the raw interrupt status as // requested. // if(bMasked) { ui32Temp = HWREG(ui32Base + ADC_O_ISC) & (0x10001 << ui32SequenceNum); } else { ui32Temp = (HWREG(ui32Base + ADC_O_RIS) & (0x10000 | (1 << ui32SequenceNum))); // // If the digital comparator status bit is set, reflect it to the // appropriate sequence bit. // if(ui32Temp & 0x10000) { ui32Temp |= 0xF0000; ui32Temp &= ~(0x10000 << ui32SequenceNum); } } // // Return the interrupt status // return(ui32Temp); } //***************************************************************************** // //! Clears sample sequence interrupt source. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! The specified sample sequence interrupt is cleared, so that it no longer //! asserts. This function must be called in the interrupt handler to keep //! the interrupt from being triggered again immediately upon exit. //! //! \note Because there is a write buffer in the Cortex-M processor, it may //! take several clock cycles before the interrupt source is actually cleared. //! Therefore, it is recommended that the interrupt source be cleared early in //! the interrupt handler (as opposed to the very last action) to avoid //! returning from the interrupt handler before the interrupt source is //! actually cleared. Failure to do so may result in the interrupt handler //! being immediately reentered (because the interrupt controller still sees //! the interrupt source asserted). //! //! \return None. // //***************************************************************************** void ADCIntClear(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Clear the interrupt. // HWREG(ui32Base + ADC_O_ISC) = 1 << ui32SequenceNum; } //***************************************************************************** // //! Enables a sample sequence. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! Allows the specified sample sequence to be captured when its trigger is //! detected. A sample sequence must be configured before it is enabled. //! //! \return None. // //***************************************************************************** void ADCSequenceEnable(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Enable the specified sequence. // HWREG(ui32Base + ADC_O_ACTSS) |= 1 << ui32SequenceNum; } //***************************************************************************** // //! Disables a sample sequence. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! Prevents the specified sample sequence from being captured when its trigger //! is detected. A sample sequence must be disabled before it is configured. //! //! \return None. // //***************************************************************************** void ADCSequenceDisable(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Disable the specified sequences. // HWREG(ui32Base + ADC_O_ACTSS) &= ~(1 << ui32SequenceNum); } //***************************************************************************** // //! Configures the trigger source and priority of a sample sequence. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! \param ui32Trigger is the trigger source that initiates the sample //! sequence; must be one of the \b ADC_TRIGGER_* values. //! \param ui32Priority is the relative priority of the sample sequence with //! respect to the other sample sequences. //! //! This function configures the initiation criteria for a sample sequence. //! Valid sample sequencers range from zero to three; sequencer zero captures //! up to eight samples, sequencers one and two capture up to four samples, //! and sequencer three captures a single sample. The trigger condition and //! priority (with respect to other sample sequencer execution) are set. //! //! The \e ui32Trigger parameter can take on the following values: //! //! - \b ADC_TRIGGER_PROCESSOR - A trigger generated by the processor, via the //! ADCProcessorTrigger() function. //! - \b ADC_TRIGGER_COMP0 - A trigger generated by the first analog //! comparator; configured with ComparatorConfigure(). //! - \b ADC_TRIGGER_COMP1 - A trigger generated by the second analog //! comparator; configured with ComparatorConfigure(). //! - \b ADC_TRIGGER_COMP2 - A trigger generated by the third analog //! comparator; configured with ComparatorConfigure(). //! - \b ADC_TRIGGER_EXTERNAL - A trigger generated by an input from the Port //! B4 pin. Note that some microcontrollers can //! select from any GPIO using the //! GPIOADCTriggerEnable() function. //! - \b ADC_TRIGGER_TIMER - A trigger generated by a timer; configured with //! TimerControlTrigger(). //! - \b ADC_TRIGGER_PWM0 - A trigger generated by the first PWM generator; //! configured with PWMGenIntTrigEnable(). //! - \b ADC_TRIGGER_PWM1 - A trigger generated by the second PWM generator; //! configured with PWMGenIntTrigEnable(). //! - \b ADC_TRIGGER_PWM2 - A trigger generated by the third PWM generator; //! configured with PWMGenIntTrigEnable(). //! - \b ADC_TRIGGER_PWM3 - A trigger generated by the fourth PWM generator; //! configured with PWMGenIntTrigEnable(). //! - \b ADC_TRIGGER_ALWAYS - A trigger that is always asserted, causing the //! sample sequence to capture repeatedly (so long as //! there is not a higher priority source active). //! //! When \b ADC_TRIGGER_PWM0, \b ADC_TRIGGER_PWM1, \b ADC_TRIGGER_PWM2 or //! \b ADC_TRIGGER_PWM3 is specified, one of the following should be ORed into //! \e ui32Trigger to select the PWM module from which the triggers will be //! routed for this sequence: //! //! - \b ADC_TRIGGER_PWM_MOD0 - Selects PWM module 0 as the source of the //! PWM0 to PWM3 triggers for this sequence. //! - \b ADC_TRIGGER_PWM_MOD1 - Selects PWM module 1 as the source of the //! PWM0 to PWM3 triggers for this sequence. //! //! Note that not all trigger sources are available on all Tiva family //! members; consult the data sheet for the device in question to determine the //! availability of triggers. //! //! The \e ui32Priority parameter is a value between 0 and 3, where 0 //! represents the highest priority and 3 the lowest. Note that when //! programming the priority among a set of sample sequences, each must have //! unique priority; it is up to the caller to guarantee the uniqueness of the //! priorities. //! //! \return None. // //***************************************************************************** void ADCSequenceConfigure(uint32_t ui32Base, uint32_t ui32SequenceNum, uint32_t ui32Trigger, uint32_t ui32Priority) { uint32_t ui32Gen; // // Check the arugments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); ASSERT(((ui32Trigger & 0xF) == ADC_TRIGGER_PROCESSOR) || ((ui32Trigger & 0xF) == ADC_TRIGGER_COMP0) || ((ui32Trigger & 0xF) == ADC_TRIGGER_COMP1) || ((ui32Trigger & 0xF) == ADC_TRIGGER_COMP2) || ((ui32Trigger & 0xF) == ADC_TRIGGER_EXTERNAL) || ((ui32Trigger & 0xF) == ADC_TRIGGER_TIMER) || ((ui32Trigger & 0xF) == ADC_TRIGGER_PWM0) || ((ui32Trigger & 0xF) == ADC_TRIGGER_PWM1) || ((ui32Trigger & 0xF) == ADC_TRIGGER_PWM2) || ((ui32Trigger & 0xF) == ADC_TRIGGER_PWM3) || ((ui32Trigger & 0xF) == ADC_TRIGGER_ALWAYS) || ((ui32Trigger & 0x30) == ADC_TRIGGER_PWM_MOD0) || ((ui32Trigger & 0x30) == ADC_TRIGGER_PWM_MOD1)); ASSERT(ui32Priority < 4); // // Compute the shift for the bits that control this sample sequence. // ui32SequenceNum *= 4; // // Set the trigger event for this sample sequence. // HWREG(ui32Base + ADC_O_EMUX) = ((HWREG(ui32Base + ADC_O_EMUX) & ~(0xf << ui32SequenceNum)) | ((ui32Trigger & 0xf) << ui32SequenceNum)); // // Set the priority for this sample sequence. // HWREG(ui32Base + ADC_O_SSPRI) = ((HWREG(ui32Base + ADC_O_SSPRI) & ~(0xf << ui32SequenceNum)) | ((ui32Priority & 0x3) << ui32SequenceNum)); // // Set the source PWM module for this sequence's PWM triggers. // ui32Gen = ui32Trigger & 0x0f; if(ui32Gen >= ADC_TRIGGER_PWM0 && ui32Gen <= ADC_TRIGGER_PWM3) { // // Set the shift for the module and generator // ui32Gen = (ui32Gen - ADC_TRIGGER_PWM0) * 8; HWREG(ADC0_BASE + ADC_O_TSSEL) = ((HWREG(ADC0_BASE + ADC_O_TSSEL) & ~(0x30 << ui32Gen)) | ((ui32Trigger & 0x30) << ui32Gen)); } } //***************************************************************************** // //! Configure a step of the sample sequencer. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! \param ui32Step is the step to be configured. //! \param ui32Config is the configuration of this step; must be a logical OR //! of \b ADC_CTL_TS, \b ADC_CTL_IE, \b ADC_CTL_END, \b ADC_CTL_D, one of the //! input channel selects (\b ADC_CTL_CH0 through \b ADC_CTL_CH23), and one of //! the digital comparator selects (\b ADC_CTL_CMP0 through \b ADC_CTL_CMP7). //! //! This function configures the ADC for one step of a sample sequence. The //! ADC can be configured for single-ended or differential operation (the //! \b ADC_CTL_D bit selects differential operation when set), the channel to //! be sampled can be chosen (the \b ADC_CTL_CH0 through \b ADC_CTL_CH23 //! values), and the internal temperature sensor can be selected (the //! \b ADC_CTL_TS bit). Additionally, this step can be defined as the last in //! the sequence (the \b ADC_CTL_END bit) and it can be configured to cause an //! interrupt when the step is complete (the \b ADC_CTL_IE bit). If the //! digital comparators are present on the device, this step may also be //! configured to send the ADC sample to the selected comparator using //! \b ADC_CTL_CMP0 through \b ADC_CTL_CMP7. The configuration is used by the //! ADC at the appropriate time when the trigger for this sequence occurs. //! //! \note If the Digital Comparator is present and enabled using the //! \b ADC_CTL_CMP0 through \b ADC_CTL_CMP7 selects, the ADC sample is NOT //! written into the ADC sequence data FIFO. //! //! The \e ui32Step parameter determines the order in which the samples are //! captured by the ADC when the trigger occurs. It can range from zero to //! seven for the first sample sequencer, from zero to three for the second and //! third sample sequencer, and can only be zero for the fourth sample //! sequencer. //! //! Differential mode only works with adjacent channel pairs (for example, 0 //! and 1). The channel select must be the number of the channel pair to //! sample (for example, \b ADC_CTL_CH0 for 0 and 1, or \b ADC_CTL_CH1 for 2 //! and 3) or undefined results are returned by the ADC. Additionally, if //! differential mode is selected when the temperature sensor is being sampled, //! undefined results are returned by the ADC. //! //! It is the responsibility of the caller to ensure that a valid configuration //! is specified; this function does not check the validity of the specified //! configuration. //! //! \return None. // //***************************************************************************** void ADCSequenceStepConfigure(uint32_t ui32Base, uint32_t ui32SequenceNum, uint32_t ui32Step, uint32_t ui32Config) { uint32_t ui32Temp; // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); ASSERT(((ui32SequenceNum == 0) && (ui32Step < 8)) || ((ui32SequenceNum == 1) && (ui32Step < 4)) || ((ui32SequenceNum == 2) && (ui32Step < 4)) || ((ui32SequenceNum == 3) && (ui32Step < 1))); // // Get the offset of the sequence to be configured. // ui32Base += ADC_SEQ + (ADC_SEQ_STEP * ui32SequenceNum); // // Compute the shift for the bits that control this step. // ui32Step *= 4; // // Set the analog mux value for this step. // HWREG(ui32Base + ADC_SSMUX) = ((HWREG(ui32Base + ADC_SSMUX) & ~(0x0000000f << ui32Step)) | ((ui32Config & 0x0f) << ui32Step)); // // Set the upper bits of the analog mux value for this step. // HWREG(ui32Base + ADC_SSEMUX) = ((HWREG(ui32Base + ADC_SSEMUX) & ~(0x0000000f << ui32Step)) | (((ui32Config & 0xf00) >> 8) << ui32Step)); // // Set the control value for this step. // HWREG(ui32Base + ADC_SSCTL) = ((HWREG(ui32Base + ADC_SSCTL) & ~(0x0000000f << ui32Step)) | (((ui32Config & 0xf0) >> 4) << ui32Step)); // // Set the sample and hold time for this step. This is not available on // all devices, however on devices that do not support this feature these // reserved bits are ignored on write access. // HWREG(ui32Base + ADC_SSTSH) = ((HWREG(ui32Base + ADC_SSTSH) & ~(0x0000000f << ui32Step)) | (((ui32Config & 0xf00000) >> 20) << ui32Step)); // // Enable digital comparator if specified in the ui32Config bit-fields. // if(ui32Config & 0x000F0000) { // // Program the comparator for the specified step. // ui32Temp = HWREG(ui32Base + ADC_SSDC); ui32Temp &= ~(0xF << ui32Step); ui32Temp |= (((ui32Config & 0x00070000) >> 16) << ui32Step); HWREG(ui32Base + ADC_SSDC) = ui32Temp; // // Enable the comparator. // HWREG(ui32Base + ADC_SSOP) |= (1 << ui32Step); } // // Disable digital comparator if not specified. // else { HWREG(ui32Base + ADC_SSOP) &= ~(1 << ui32Step); } } //***************************************************************************** // //! Determines if a sample sequence overflow occurred. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! This function determines if a sample sequence overflow has occurred. //! Overflow happens if the captured samples are not read from the FIFO before //! the next trigger occurs. //! //! \return Returns zero if there was not an overflow, and non-zero if there //! was. // //***************************************************************************** int32_t ADCSequenceOverflow(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Determine if there was an overflow on this sequence. // return(HWREG(ui32Base + ADC_O_OSTAT) & (1 << ui32SequenceNum)); } //***************************************************************************** // //! Clears the overflow condition on a sample sequence. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! This function clears an overflow condition on one of the sample sequences. //! The overflow condition must be cleared in order to detect a subsequent //! overflow condition (it otherwise causes no harm). //! //! \return None. // //***************************************************************************** void ADCSequenceOverflowClear(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Clear the overflow condition for this sequence. // HWREG(ui32Base + ADC_O_OSTAT) = 1 << ui32SequenceNum; } //***************************************************************************** // //! Determines if a sample sequence underflow occurred. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! This function determines if a sample sequence underflow has occurred. //! Underflow happens if too many samples are read from the FIFO. //! //! \return Returns zero if there was not an underflow, and non-zero if there //! was. // //***************************************************************************** int32_t ADCSequenceUnderflow(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Determine if there was an underflow on this sequence. // return(HWREG(ui32Base + ADC_O_USTAT) & (1 << ui32SequenceNum)); } //***************************************************************************** // //! Clears the underflow condition on a sample sequence. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! This function clears an underflow condition on one of the sample //! sequencers. The underflow condition must be cleared in order to detect a //! subsequent underflow condition (it otherwise causes no harm). //! //! \return None. // //***************************************************************************** void ADCSequenceUnderflowClear(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Clear the underflow condition for this sequence. // HWREG(ui32Base + ADC_O_USTAT) = 1 << ui32SequenceNum; } //***************************************************************************** // //! Gets the captured data for a sample sequence. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! \param pui32Buffer is the address where the data is stored. //! //! This function copies data from the specified sample sequencer output FIFO //! to a memory resident buffer. The number of samples available in the //! hardware FIFO are copied into the buffer, which is assumed to be large //! enough to hold that many samples. This function only returns the samples //! that are presently available, which may not be the entire sample sequence //! if it is in the process of being executed. //! //! \return Returns the number of samples copied to the buffer. // //***************************************************************************** int32_t ADCSequenceDataGet(uint32_t ui32Base, uint32_t ui32SequenceNum, uint32_t *pui32Buffer) { uint32_t ui32Count; // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Get the offset of the sequence to be read. // ui32Base += ADC_SEQ + (ADC_SEQ_STEP * ui32SequenceNum); // // Read samples from the FIFO until it is empty. // ui32Count = 0; while(!(HWREG(ui32Base + ADC_SSFSTAT) & ADC_SSFSTAT0_EMPTY) && (ui32Count < 8)) { // // Read the FIFO and copy it to the destination. // *pui32Buffer++ = HWREG(ui32Base + ADC_SSFIFO); // // Increment the count of samples read. // ui32Count++; } // // Return the number of samples read. // return(ui32Count); } //***************************************************************************** // //! Causes a processor trigger for a sample sequence. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number, with //! \b ADC_TRIGGER_WAIT or \b ADC_TRIGGER_SIGNAL optionally ORed into it. //! //! This function triggers a processor-initiated sample sequence if the sample //! sequence trigger is configured to \b ADC_TRIGGER_PROCESSOR. If //! \b ADC_TRIGGER_WAIT is ORed into the sequence number, the //! processor-initiated trigger is delayed until a later processor-initiated //! trigger to a different ADC module that specifies \b ADC_TRIGGER_SIGNAL, //! allowing multiple ADCs to start from a processor-initiated trigger in a //! synchronous manner. //! //! \return None. // //***************************************************************************** void ADCProcessorTrigger(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Generate a processor trigger for this sample sequence. // HWREG(ui32Base + ADC_O_PSSI) |= ((ui32SequenceNum & 0xffff0000) | (1 << (ui32SequenceNum & 0xf))); } //***************************************************************************** // //! Configures the software oversampling factor of the ADC. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! \param ui32Factor is the number of samples to be averaged. //! //! This function configures the software oversampling for the ADC, which can //! be used to provide better resolution on the sampled data. Oversampling is //! accomplished by averaging multiple samples from the same analog input. //! Three different oversampling rates are supported; 2x, 4x, and 8x. //! //! Oversampling is only supported on the sample sequencers that are more than //! one sample in depth (that is, the fourth sample sequencer is not //! supported). Oversampling by 2x (for example) divides the depth of the //! sample sequencer by two; so 2x oversampling on the first sample sequencer //! can only provide four samples per trigger. This also means that 8x //! oversampling is only available on the first sample sequencer. //! //! \return None. // //***************************************************************************** void ADCSoftwareOversampleConfigure(uint32_t ui32Base, uint32_t ui32SequenceNum, uint32_t ui32Factor) { uint32_t ui32Value; // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 3); ASSERT(((ui32Factor == 2) || (ui32Factor == 4) || (ui32Factor == 8)) && ((ui32SequenceNum == 0) || (ui32Factor != 8))); // // Convert the oversampling factor to a shift factor. // for(ui32Value = 0, ui32Factor >>= 1; ui32Factor; ui32Value++, ui32Factor >>= 1) { } // // Save the shift factor. // g_pui8OversampleFactor[ui32SequenceNum] = ui32Value; } //***************************************************************************** // //! Configures a step of the software oversampled sequencer. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! \param ui32Step is the step to be configured. //! \param ui32Config is the configuration of this step. //! //! This function configures a step of the sample sequencer when using the //! software oversampling feature. The number of steps available depends on //! the oversampling factor set by ADCSoftwareOversampleConfigure(). The value //! of \e ui32Config is the same as defined for ADCSequenceStepConfigure(). //! //! \return None. // //***************************************************************************** void ADCSoftwareOversampleStepConfigure(uint32_t ui32Base, uint32_t ui32SequenceNum, uint32_t ui32Step, uint32_t ui32Config) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 3); ASSERT(((ui32SequenceNum == 0) && (ui32Step < (8 >> g_pui8OversampleFactor[ui32SequenceNum]))) || (ui32Step < (4 >> g_pui8OversampleFactor[ui32SequenceNum]))); // // Get the offset of the sequence to be configured. // ui32Base += ADC_SEQ + (ADC_SEQ_STEP * ui32SequenceNum); // // Compute the shift for the bits that control this step. // ui32Step *= 4 << g_pui8OversampleFactor[ui32SequenceNum]; // // Loop through the hardware steps that make up this step of the software // oversampled sequence. // for(ui32SequenceNum = 1 << g_pui8OversampleFactor[ui32SequenceNum]; ui32SequenceNum; ui32SequenceNum--) { // // Set the analog mux value for this step. // HWREG(ui32Base + ADC_SSMUX) = ((HWREG(ui32Base + ADC_SSMUX) & ~(0x0000000f << ui32Step)) | ((ui32Config & 0x0f) << ui32Step)); // // Set the upper bits of the analog mux value for this step. // HWREG(ui32Base + ADC_SSEMUX) = ((HWREG(ui32Base + ADC_SSEMUX) & ~(0x0000000f << ui32Step)) | (((ui32Config & 0xf00) >> 8) << ui32Step)); // // Set the control value for this step. // HWREG(ui32Base + ADC_SSCTL) = ((HWREG(ui32Base + ADC_SSCTL) & ~(0x0000000f << ui32Step)) | (((ui32Config & 0xf0) >> 4) << ui32Step)); if(ui32SequenceNum != 1) { HWREG(ui32Base + ADC_SSCTL) &= ~((ADC_SSCTL0_IE0 | ADC_SSCTL0_END0) << ui32Step); } // // Go to the next hardware step. // ui32Step += 4; } } //***************************************************************************** // //! Gets the captured data for a sample sequence using software oversampling. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! \param pui32Buffer is the address where the data is stored. //! \param ui32Count is the number of samples to be read. //! //! This function copies data from the specified sample sequence output FIFO to //! a memory resident buffer with software oversampling applied. The requested //! number of samples are copied into the data buffer; if there are not enough //! samples in the hardware FIFO to satisfy this many oversampled data items, //! then incorrect results are returned. It is the caller's responsibility to //! read only the samples that are available and wait until enough data is //! available, for example as a result of receiving an interrupt. //! //! \return None. // //***************************************************************************** void ADCSoftwareOversampleDataGet(uint32_t ui32Base, uint32_t ui32SequenceNum, uint32_t *pui32Buffer, uint32_t ui32Count) { uint32_t ui32Idx, ui32Accum; // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 3); ASSERT(((ui32SequenceNum == 0) && (ui32Count < (8 >> g_pui8OversampleFactor[ui32SequenceNum]))) || (ui32Count < (4 >> g_pui8OversampleFactor[ui32SequenceNum]))); // // Get the offset of the sequence to be read. // ui32Base += ADC_SEQ + (ADC_SEQ_STEP * ui32SequenceNum); // // Read the samples from the FIFO until it is empty. // while(ui32Count--) { // // Compute the sum of the samples. // ui32Accum = 0; for(ui32Idx = 1 << g_pui8OversampleFactor[ui32SequenceNum]; ui32Idx; ui32Idx--) { // // Read the FIFO and add it to the accumulator. // ui32Accum += HWREG(ui32Base + ADC_SSFIFO); } // // Write the averaged sample to the output buffer. // *pui32Buffer++ = ui32Accum >> g_pui8OversampleFactor[ui32SequenceNum]; } } //***************************************************************************** // //! Configures the hardware oversampling factor of the ADC. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32Factor is the number of samples to be averaged. //! //! This function configures the hardware oversampling for the ADC, which can //! be used to provide better resolution on the sampled data. Oversampling is //! accomplished by averaging multiple samples from the same analog input. Six //! different oversampling rates are supported; 2x, 4x, 8x, 16x, 32x, and 64x. //! Specifying an oversampling factor of zero disables hardware //! oversampling. //! //! Hardware oversampling applies uniformly to all sample sequencers. It does //! not reduce the depth of the sample sequencers like the software //! oversampling APIs; each sample written into the sample sequencer FIFO is a //! fully oversampled analog input reading. //! //! Enabling hardware averaging increases the precision of the ADC at the cost //! of throughput. For example, enabling 4x oversampling reduces the //! throughput of a 250 k samples/second ADC to 62.5 k samples/second. //! //! \return None. // //***************************************************************************** void ADCHardwareOversampleConfigure(uint32_t ui32Base, uint32_t ui32Factor) { uint32_t ui32Value; // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(((ui32Factor == 0) || (ui32Factor == 2) || (ui32Factor == 4) || (ui32Factor == 8) || (ui32Factor == 16) || (ui32Factor == 32) || (ui32Factor == 64))); // // Convert the oversampling factor to a shift factor. // for(ui32Value = 0, ui32Factor >>= 1; ui32Factor; ui32Value++, ui32Factor >>= 1) { } // // Write the shift factor to the ADC to configure the hardware oversampler. // HWREG(ui32Base + ADC_O_SAC) = ui32Value; } //***************************************************************************** // //! Configures an ADC digital comparator. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32Comp is the index of the comparator to configure. //! \param ui32Config is the configuration of the comparator. //! //! This function configures a comparator. The \e ui32Config parameter is //! the result of a logical OR operation between the \b ADC_COMP_TRIG_xxx, and //! \b ADC_COMP_INT_xxx values. //! //! The \b ADC_COMP_TRIG_xxx term can take on the following values: //! //! - \b ADC_COMP_TRIG_NONE to never trigger PWM fault condition. //! - \b ADC_COMP_TRIG_LOW_ALWAYS to always trigger PWM fault condition when //! ADC output is in the low-band. //! - \b ADC_COMP_TRIG_LOW_ONCE to trigger PWM fault condition once when ADC //! output transitions into the low-band. //! - \b ADC_COMP_TRIG_LOW_HALWAYS to always trigger PWM fault condition when //! ADC output is in the low-band only if ADC output has been in the high-band //! since the last trigger output. //! - \b ADC_COMP_TRIG_LOW_HONCE to trigger PWM fault condition once when ADC //! output transitions into low-band only if ADC output has been in the //! high-band since the last trigger output. //! - \b ADC_COMP_TRIG_MID_ALWAYS to always trigger PWM fault condition when //! ADC output is in the mid-band. //! - \b ADC_COMP_TRIG_MID_ONCE to trigger PWM fault condition once when ADC //! output transitions into the mid-band. //! - \b ADC_COMP_TRIG_HIGH_ALWAYS to always trigger PWM fault condition when //! ADC output is in the high-band. //! - \b ADC_COMP_TRIG_HIGH_ONCE to trigger PWM fault condition once when ADC //! output transitions into the high-band. //! - \b ADC_COMP_TRIG_HIGH_HALWAYS to always trigger PWM fault condition when //! ADC output is in the high-band only if ADC output has been in the low-band //! since the last trigger output. //! - \b ADC_COMP_TRIG_HIGH_HONCE to trigger PWM fault condition once when ADC //! output transitions into high-band only if ADC output has been in the //! low-band since the last trigger output. //! //! The \b ADC_COMP_INT_xxx term can take on the following values: //! //! - \b ADC_COMP_INT_NONE to never generate ADC interrupt. //! - \b ADC_COMP_INT_LOW_ALWAYS to always generate ADC interrupt when ADC //! output is in the low-band. //! - \b ADC_COMP_INT_LOW_ONCE to generate ADC interrupt once when ADC output //! transitions into the low-band. //! - \b ADC_COMP_INT_LOW_HALWAYS to always generate ADC interrupt when ADC //! output is in the low-band only if ADC output has been in the high-band //! since the last trigger output. //! - \b ADC_COMP_INT_LOW_HONCE to generate ADC interrupt once when ADC output //! transitions into low-band only if ADC output has been in the high-band //! since the last trigger output. //! - \b ADC_COMP_INT_MID_ALWAYS to always generate ADC interrupt when ADC //! output is in the mid-band. //! - \b ADC_COMP_INT_MID_ONCE to generate ADC interrupt once when ADC output //! transitions into the mid-band. //! - \b ADC_COMP_INT_HIGH_ALWAYS to always generate ADC interrupt when ADC //! output is in the high-band. //! - \b ADC_COMP_INT_HIGH_ONCE to generate ADC interrupt once when ADC output //! transitions into the high-band. //! - \b ADC_COMP_INT_HIGH_HALWAYS to always generate ADC interrupt when ADC //! output is in the high-band only if ADC output has been in the low-band //! since the last trigger output. //! - \b ADC_COMP_INT_HIGH_HONCE to generate ADC interrupt once when ADC output //! transitions into high-band only if ADC output has been in the low-band //! since the last trigger output. //! //! \return None. // //***************************************************************************** void ADCComparatorConfigure(uint32_t ui32Base, uint32_t ui32Comp, uint32_t ui32Config) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32Comp < 8); // // Save the new setting. // HWREG(ui32Base + ADC_O_DCCTL0 + (ui32Comp * 4)) = ui32Config; } //***************************************************************************** // //! Defines the ADC digital comparator regions. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32Comp is the index of the comparator to configure. //! \param ui32LowRef is the reference point for the low/mid band threshold. //! \param ui32HighRef is the reference point for the mid/high band threshold. //! //! The ADC digital comparator operation is based on three ADC value regions: //! - \b low-band is defined as any ADC value less than or equal to the //! \e ui32LowRef value. //! - \b mid-band is defined as any ADC value greater than the \e ui32LowRef //! value but less than or equal to the \e ui32HighRef value. //! - \b high-band is defined as any ADC value greater than the \e ui32HighRef //! value. //! //! \return None. // //***************************************************************************** void ADCComparatorRegionSet(uint32_t ui32Base, uint32_t ui32Comp, uint32_t ui32LowRef, uint32_t ui32HighRef) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32Comp < 8); ASSERT((ui32LowRef < 4096) && (ui32LowRef <= ui32HighRef)); ASSERT(ui32HighRef < 4096); // // Save the new region settings. // HWREG(ui32Base + ADC_O_DCCMP0 + (ui32Comp * 4)) = ((ui32HighRef << 16) | ui32LowRef); } //***************************************************************************** // //! Resets the current ADC digital comparator conditions. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32Comp is the index of the comparator. //! \param bTrigger is the flag to indicate reset of Trigger conditions. //! \param bInterrupt is the flag to indicate reset of Interrupt conditions. //! //! Because the digital comparator uses current and previous ADC values, this //! function allows the comparator to be reset to its initial //! value to prevent stale data from being used when a sequence is enabled. //! //! \return None. // //***************************************************************************** void ADCComparatorReset(uint32_t ui32Base, uint32_t ui32Comp, bool bTrigger, bool bInterrupt) { uint32_t ui32Temp; // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32Comp < 8); // // Set the appropriate bits to reset the trigger and/or interrupt // comparator conditions. // ui32Temp = 0; if(bTrigger) { ui32Temp |= (1 << (16 + ui32Comp)); } if(bInterrupt) { ui32Temp |= (1 << ui32Comp); } HWREG(ui32Base + ADC_O_DCRIC) = ui32Temp; } //***************************************************************************** // //! Disables a sample sequence comparator interrupt. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! This function disables the requested sample sequence comparator interrupt. //! //! \return None. // //***************************************************************************** void ADCComparatorIntDisable(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Disable this sample sequence comparator interrupt. // HWREG(ui32Base + ADC_O_IM) &= ~(0x10000 << ui32SequenceNum); } //***************************************************************************** // //! Enables a sample sequence comparator interrupt. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! This function enables the requested sample sequence comparator interrupt. //! //! \return None. // //***************************************************************************** void ADCComparatorIntEnable(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Enable this sample sequence interrupt. // HWREG(ui32Base + ADC_O_IM) |= 0x10000 << ui32SequenceNum; } //***************************************************************************** // //! Gets the current comparator interrupt status. //! //! \param ui32Base is the base address of the ADC module. //! //! This function returns the digital comparator interrupt status bits. This //! status is sequence agnostic. //! //! \return The current comparator interrupt status. // //***************************************************************************** uint32_t ADCComparatorIntStatus(uint32_t ui32Base) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); // // Return the digital comparator interrupt status. // return(HWREG(ui32Base + ADC_O_DCISC)); } //***************************************************************************** // //! Clears sample sequence comparator interrupt source. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32Status is the bit-mapped interrupts status to clear. //! //! The specified interrupt status is cleared. //! //! \return None. // //***************************************************************************** void ADCComparatorIntClear(uint32_t ui32Base, uint32_t ui32Status) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); // // Clear the interrupt. // HWREG(ui32Base + ADC_O_DCISC) = ui32Status; } //***************************************************************************** // //! Disables ADC interrupt sources. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32IntFlags is the bit mask of the interrupt sources to disable. //! //! This function disables the indicated ADC interrupt sources. Only the //! sources that are enabled can be reflected to the processor interrupt; //! disabled sources have no effect on the processor. //! //! The \e ui32IntFlags parameter is the logical OR of any of the following: //! //! - \b ADC_INT_SS0 - interrupt due to ADC sample sequence 0. //! - \b ADC_INT_SS1 - interrupt due to ADC sample sequence 1. //! - \b ADC_INT_SS2 - interrupt due to ADC sample sequence 2. //! - \b ADC_INT_SS3 - interrupt due to ADC sample sequence 3. //! - \b ADC_INT_DMA_SS0 - interrupt due to DMA on ADC sample sequence 0. //! - \b ADC_INT_DMA_SS1 - interrupt due to DMA on ADC sample sequence 1. //! - \b ADC_INT_DMA_SS2 - interrupt due to DMA on ADC sample sequence 2. //! - \b ADC_INT_DMA_SS3 - interrupt due to DMA on ADC sample sequence 3. //! - \b ADC_INT_DCON_SS0 - interrupt due to digital comparator on ADC sample //! sequence 0. //! - \b ADC_INT_DCON_SS1 - interrupt due to digital comparator on ADC sample //! sequence 1. //! - \b ADC_INT_DCON_SS2 - interrupt due to digital comparator on ADC sample //! sequence 2. //! - \b ADC_INT_DCON_SS3 - interrupt due to digital comparator on ADC sample //! sequence 3. //! //! \return None. // //***************************************************************************** void ADCIntDisableEx(uint32_t ui32Base, uint32_t ui32IntFlags) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); // // Disable the requested interrupts. // HWREG(ui32Base + ADC_O_IM) &= ~ui32IntFlags; } //***************************************************************************** // //! Enables ADC interrupt sources. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32IntFlags is the bit mask of the interrupt sources to disable. //! //! This function enables the indicated ADC interrupt sources. Only the //! sources that are enabled can be reflected to the processor interrupt; //! disabled sources have no effect on the processor. //! //! The \e ui32IntFlags parameter is the logical OR of any of the following: //! //! - \b ADC_INT_SS0 - interrupt due to ADC sample sequence 0. //! - \b ADC_INT_SS1 - interrupt due to ADC sample sequence 1. //! - \b ADC_INT_SS2 - interrupt due to ADC sample sequence 2. //! - \b ADC_INT_SS3 - interrupt due to ADC sample sequence 3. //! - \b ADC_INT_DMA_SS0 - interrupt due to DMA on ADC sample sequence 0. //! - \b ADC_INT_DMA_SS1 - interrupt due to DMA on ADC sample sequence 1. //! - \b ADC_INT_DMA_SS2 - interrupt due to DMA on ADC sample sequence 2. //! - \b ADC_INT_DMA_SS3 - interrupt due to DMA on ADC sample sequence 3. //! - \b ADC_INT_DCON_SS0 - interrupt due to digital comparator on ADC sample //! sequence 0. //! - \b ADC_INT_DCON_SS1 - interrupt due to digital comparator on ADC sample //! sequence 1. //! - \b ADC_INT_DCON_SS2 - interrupt due to digital comparator on ADC sample //! sequence 2. //! - \b ADC_INT_DCON_SS3 - interrupt due to digital comparator on ADC sample //! sequence 3. //! //! \return None. // //***************************************************************************** void ADCIntEnableEx(uint32_t ui32Base, uint32_t ui32IntFlags) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); // // Enable the requested interrupts. // HWREG(ui32Base + ADC_O_IM) |= ui32IntFlags; } //***************************************************************************** // //! Gets interrupt status for the specified ADC module. //! //! \param ui32Base is the base address of the ADC module. //! \param bMasked specifies whether masked or raw interrupt status is //! returned. //! //! If \e bMasked is set as \b true, then the masked interrupt status is //! returned; otherwise, the raw interrupt status is returned. //! //! \return Returns the current interrupt status for the specified ADC module. //! The value returned is the logical OR of the \b ADC_INT_* values that are //! currently active. // //***************************************************************************** uint32_t ADCIntStatusEx(uint32_t ui32Base, bool bMasked) { uint32_t ui32Temp; // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); // // Return either the masked interrupt status or the raw interrupt status as // requested. // if(bMasked) { ui32Temp = HWREG(ui32Base + ADC_O_ISC); } else { // // Read the Raw interrupt status to see if a digital comparator // interrupt is active. // ui32Temp = HWREG(ui32Base + ADC_O_RIS); // // Since, the raw interrupt status only indicates that any one of the // digital comparators caused an interrupt, if the raw interrupt status // is set then the return value is modified to indicate that all sample // sequences have a pending digital comparator interrupt. // This is exactly how the hardware works so the return code is // modified to match this behavior. // if(ui32Temp & ADC_RIS_INRDC) { ui32Temp |= (ADC_INT_DCON_SS3 | ADC_INT_DCON_SS2 | ADC_INT_DCON_SS1 | ADC_INT_DCON_SS0); } } return(ui32Temp); } //***************************************************************************** // //! Clears the specified ADC interrupt sources. //! //! \param ui32Base is the base address of the ADC port. //! \param ui32IntFlags is the bit mask of the interrupt sources to disable. //! //! Clears the interrupt for the specified interrupt source(s). //! //! The \e ui32IntFlags parameter is the logical OR of the \b ADC_INT_* values. //! See the ADCIntEnableEx() function for the list of possible \b ADC_INT* //! values. //! //! \note Because there is a write buffer in the Cortex-M processor, it may //! take several clock cycles before the interrupt source is actually cleared. //! Therefore, it is recommended that the interrupt source be cleared early in //! the interrupt handler (as opposed to the very last action) to avoid //! returning from the interrupt handler before the interrupt source is //! actually cleared. Failure to do so may result in the interrupt handler //! being immediately reentered (because the interrupt controller still sees //! the interrupt source asserted). //! //! \return None. // //***************************************************************************** void ADCIntClearEx(uint32_t ui32Base, uint32_t ui32IntFlags) { // // Note: The interrupt bits are "W1C" so we DO NOT use a logical OR // here to clear the requested bits. Doing so would clear all outstanding // interrupts rather than just those which the caller has specified. // HWREG(ui32Base + ADC_O_ISC) = ui32IntFlags; } //***************************************************************************** // //! Selects the ADC reference. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32Ref is the reference to use. //! //! The ADC reference is set as specified by \e ui32Ref. It must be one of //! \b ADC_REF_INT, or \b ADC_REF_EXT_3V for internal or external reference //! If \b ADC_REF_INT is chosen, then an internal 3V reference is used and //! no external reference is needed. If \b ADC_REF_EXT_3V is chosen, then //! a 3V reference must be supplied to the AVREF pin. //! //! \note The ADC reference can only be selected on parts that have an external //! reference. Consult the data sheet for your part to determine if there is //! an external reference. //! //! \return None. // //***************************************************************************** void ADCReferenceSet(uint32_t ui32Base, uint32_t ui32Ref) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT((ui32Ref == ADC_REF_INT) || (ui32Ref == ADC_REF_EXT_3V)); // // Set the reference. // HWREG(ui32Base + ADC_O_CTL) = (HWREG(ui32Base + ADC_O_CTL) & ~ADC_CTL_VREF_M) | ui32Ref; } //***************************************************************************** // //! Returns the current setting of the ADC reference. //! //! \param ui32Base is the base address of the ADC module. //! //! Returns the value of the ADC reference setting. The returned value is one //! of \b ADC_REF_INT, or \b ADC_REF_EXT_3V. //! //! \note The value returned by this function is only meaningful if used on a //! part that is capable of using an external reference. Consult the data //! sheet for your part to determine if it has an external reference input. //! //! \return The current setting of the ADC reference. // //***************************************************************************** uint32_t ADCReferenceGet(uint32_t ui32Base) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); // // Return the value of the reference. // return(HWREG(ui32Base + ADC_O_CTL) & ADC_CTL_VREF_M); } //***************************************************************************** // //! Sets the phase delay between a trigger and the start of a sequence. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32Phase is the phase delay, specified as one of \b ADC_PHASE_0, //! \b ADC_PHASE_22_5, \b ADC_PHASE_45, \b ADC_PHASE_67_5, \b ADC_PHASE_90, //! \b ADC_PHASE_112_5, \b ADC_PHASE_135, \b ADC_PHASE_157_5, \b ADC_PHASE_180, //! \b ADC_PHASE_202_5, \b ADC_PHASE_225, \b ADC_PHASE_247_5, \b ADC_PHASE_270, //! \b ADC_PHASE_292_5, \b ADC_PHASE_315, or \b ADC_PHASE_337_5. //! //! This function sets the phase delay between the detection of an ADC trigger //! event and the start of the sample sequence. By selecting a different phase //! delay for a pair of ADC modules (such as \b ADC_PHASE_0 and //! \b ADC_PHASE_180) and having each ADC module sample the same analog input, //! it is possible to increase the sampling rate of the analog input (with //! samples N, N+2, N+4, and so on, coming from the first ADC and samples N+1, //! N+3, N+5, and so on, coming from the second ADC). The ADC module has a //! single phase delay that is applied to all sample sequences within that //! module. //! //! \note This capability is not available on all parts. //! //! \return None. // //***************************************************************************** void ADCPhaseDelaySet(uint32_t ui32Base, uint32_t ui32Phase) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT((ui32Phase == ADC_PHASE_0) || (ui32Phase == ADC_PHASE_22_5) || (ui32Phase == ADC_PHASE_45) || (ui32Phase == ADC_PHASE_67_5) || (ui32Phase == ADC_PHASE_90) || (ui32Phase == ADC_PHASE_112_5) || (ui32Phase == ADC_PHASE_135) || (ui32Phase == ADC_PHASE_157_5) || (ui32Phase == ADC_PHASE_180) || (ui32Phase == ADC_PHASE_202_5) || (ui32Phase == ADC_PHASE_225) || (ui32Phase == ADC_PHASE_247_5) || (ui32Phase == ADC_PHASE_270) || (ui32Phase == ADC_PHASE_292_5) || (ui32Phase == ADC_PHASE_315) || (ui32Phase == ADC_PHASE_337_5)); // // Set the phase delay. // HWREG(ui32Base + ADC_O_SPC) = ui32Phase; } //***************************************************************************** // //! Gets the phase delay between a trigger and the start of a sequence. //! //! \param ui32Base is the base address of the ADC module. //! //! This function gets the current phase delay between the detection of an ADC //! trigger event and the start of the sample sequence. //! //! \return Returns the phase delay, specified as one of \b ADC_PHASE_0, //! \b ADC_PHASE_22_5, \b ADC_PHASE_45, \b ADC_PHASE_67_5, \b ADC_PHASE_90, //! \b ADC_PHASE_112_5, \b ADC_PHASE_135, \b ADC_PHASE_157_5, \b ADC_PHASE_180, //! \b ADC_PHASE_202_5, \b ADC_PHASE_225, \b ADC_PHASE_247_5, \b ADC_PHASE_270, //! \b ADC_PHASE_292_5, \b ADC_PHASE_315, or \b ADC_PHASE_337_5. // //***************************************************************************** uint32_t ADCPhaseDelayGet(uint32_t ui32Base) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); // // Return the phase delay. // return(HWREG(ui32Base + ADC_O_SPC)); } //***************************************************************************** // //! Enables DMA for sample sequencers. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! Allows DMA requests to be generated based on the FIFO level of the sample //! sequencer. //! //! \return None. // //***************************************************************************** void ADCSequenceDMAEnable(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Enable the DMA on the specified sequencer. // HWREG(ui32Base + ADC_O_ACTSS) |= 0x100 << ui32SequenceNum; } //***************************************************************************** // //! Disables DMA for sample sequencers. //! //! \param ui32Base is the base address of the ADC module. //! \param ui32SequenceNum is the sample sequence number. //! //! Prevents the specified sample sequencer from generating DMA requests. //! //! \return None. // //***************************************************************************** void ADCSequenceDMADisable(uint32_t ui32Base, uint32_t ui32SequenceNum) { // // Check the arguments. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT(ui32SequenceNum < 4); // // Disable the DMA on the specified sequencer. // HWREG(ui32Base + ADC_O_ACTSS) &= ~(0x100 << ui32SequenceNum); } //***************************************************************************** // //! Determines whether the ADC is busy or not. //! //! \param ui32Base is the base address of the ADC. //! //! This function allows the caller to determine whether or not the ADC is //! currently sampling . If \b false is returned, then the ADC is not //! sampling data. //! //! Use this function to detect that the ADC is finished sampling data before //! putting the device into deep sleep. Before using this function, it is //! highly recommended that the event trigger is changed to //! \b ADC_TRIGGER_NEVER on all enabled sequencers to prevent the ADC from //! starting after checking the busy status. //! //! \return Returns \b true if the ADC is sampling or \b false if all //! samples are complete. // //***************************************************************************** bool ADCBusy(uint32_t ui32Base) { // // Check the argument. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); // // Determine if the ADC is busy. // return((HWREG(ui32Base + ADC_O_ACTSS) & ADC_ACTSS_BUSY) ? true : false); } //***************************************************************************** // //! Sets the clock configuration for the ADC. //! //! \param ui32Base is the base address of the ADC to configure, which must //! always be \b ADC0_BASE. //! \param ui32Config is a combination of the \b ADC_CLOCK_SRC_ and //! \b ADC_CLOCK_RATE_* values used to configure the ADC clock input. //! \param ui32ClockDiv is the input clock divider for the clock selected by //! the \b ADC_CLOCK_SRC value. //! //! This function is used to configure the input clock to the ADC modules. The //! clock configuration is shared across ADC units so \e ui32Base must //! always be \b ADC0_BASE. The \e ui32Config value is logical OR of one //! of the \b ADC_CLOCK_RATE_ and one of the \b ADC_CLOCK_SRC_ values defined //! below. The \b ADC_CLOCK_SRC_* values determine the input clock for the ADC. //! Not all values are available on all devices so check the device data sheet //! to determine value configuration options. Regardless of the source, the //! final frequency for TM4C123x devices must be 16 MHz and for TM4C129x parts //! after dividing must be between 16 and 32 MHz. //! //! \note For TM4C123x devices, if the PLL is enabled, the PLL/25 is used as //! the ADC clock unless ADC_CLOCK_SRC_PIOSC is specified. If the PLL is //! disabled, the MOSC is used as the clock source unless ADC_CLOCK_SRC_PIOSC //! is specified. //! //! - \b ADC_CLOCK_SRC_PLL - The main PLL output (TM4x129 class only). //! - \b ADC_CLOCK_SRC_PIOSC - The internal PIOSC at 16 MHz. //! - \b ADC_CLOCK_SRC_ALTCLK - The output of the ALTCLK in the system control //! module (TM4x129 class only). //! - \b ADC_CLOCK_SRC_MOSC - The external MOSC (TM4x129 class only). //! //! \b ADC_CLOCK_RATE values control how often samples are provided back to the //! application. The values are the following: //! //! - \b ADC_CLOCK_RATE_FULL - All samples. //! - \b ADC_CLOCK_RATE_HALF - Every other sample. //! - \b ADC_CLOCK_RATE_QUARTER - Every fourth sample. //! - \b ADC_CLOCK_RATE_EIGHTH - Every either sample. //! //! The \e ui32ClockDiv parameter allows for dividing a higher frequency down //! into the valid range for the ADCs. This parameter is typically only used //! \b ADC_CLOCK_SRC_PLL option because it is the only clock value that can be //! with the in the correct range to use the divider. The actual value ranges //! from 1 to 64. //! //! \b Example: ADC Clock Configurations //! //! \verbatim //! //! // //! // Configure the ADC to use PIOSC divided by one (16 MHz) and sample at //! // half the rate. //! // //! ADCClockConfigSet(ADC0_BASE, ADC_CLOCK_SRC_PIOSC | ADC_CLOCK_RATE_HALF, 1); //! //! ... //! //! // //! // Configure the ADC to use PLL at 480 MHz divided by 24 to get an ADC //! // clock of 20 MHz. //! // //! ADCClockConfigSet(ADC0_BASE, ADC_CLOCK_SRC_PLL | ADC_CLOCK_RATE_FULL, 24); //! \endverbatim //! //! \return None. // //***************************************************************************** void ADCClockConfigSet(uint32_t ui32Base, uint32_t ui32Config, uint32_t ui32ClockDiv) { // // Check the argument. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); ASSERT((ui32ClockDiv - 1) <= (ADC_CC_CLKDIV_M >> ADC_CC_CLKDIV_S)); // // A rate must be supplied. // ASSERT((ui32Config & ADC_CLOCK_RATE_FULL) != 0); // // Write the sample conversion rate. // HWREG(ui32Base + ADC_O_PC) = (ui32Config >> 4) & ADC_PC_SR_M; // // Write the clock select and divider. // HWREG(ui32Base + ADC_O_CC) = (ui32Config & ADC_CC_CS_M) | (((ui32ClockDiv - 1) << ADC_CC_CLKDIV_S)) ; } //***************************************************************************** // //! Returns the clock configuration for the ADC. //! //! \param ui32Base is the base address of the ADC to configure, which must //! always be \b ADC0_BASE. //! \param pui32ClockDiv is a pointer to the input clock divider for the clock //! selected by the \b ADC_CLOCK_SRC in use by the ADCs. //! //! This function returns the ADC clock configuration and the clock divider for //! the ADCs. //! //! \b Example: Read the current ADC clock configuration. //! //! \verbatim //! uint32_t ui32Config, ui32ClockDiv; //! //! // //! // Read the current ADC clock configuration. //! // //! ui32Config = ADCClockConfigGet(ADC0_BASE, &ui32ClockDiv); //! \endverbatim //! //! \return The current clock configuration of the ADC defined as a combination //! of one of \b ADC_CLOCK_SRC_PLL, \b ADC_CLOCK_SRC_PIOSC, //! \b ADC_CLOCK_SRC_MOSC, or \b ADC_CLOCK_SRC_ALTCLK logical ORed with one of //! \b ADC_CLOCK_RATE_FULL, \b ADC_CLOCK_RATE_HALF, \b ADC_CLOCK_RATE_QUARTER, //! or \b ADC_CLOCK_RATE_EIGHTH. See ADCClockConfigSet() for more information //! on these values. // //***************************************************************************** uint32_t ADCClockConfigGet(uint32_t ui32Base, uint32_t *pui32ClockDiv) { uint32_t ui32Config; // // Check the argument. // ASSERT((ui32Base == ADC0_BASE) || (ui32Base == ADC1_BASE)); // // Read the current configuration. // ui32Config = HWREG(ui32Base + ADC_O_CC); // // If the clock divider was requested provide the current value. // if(pui32ClockDiv) { *pui32ClockDiv = ((ui32Config & ADC_CC_CLKDIV_M) >> ADC_CC_CLKDIV_S) + 1; } // // Clear out the divider bits. // ui32Config &= ~ADC_CC_CLKDIV_M; // // Add in the sample interval to the configuration. // ui32Config |= (HWREG(ui32Base + ADC_O_PC) & ADC_PC_SR_M) << 4; return(ui32Config); } //***************************************************************************** // // Close the Doxygen group. //! @} // //*****************************************************************************
{ "content_hash": "b31e7f8b7fdfa82ba9ea25602ccac8c6", "timestamp": "", "source": "github", "line_count": 1946, "max_line_length": 79, "avg_line_length": 35.873586844809864, "alnum_prop": 0.584572410829394, "repo_name": "kpeeyush/dusthawk", "id": "9c361e141a09e74d48deab9d2cd9bbf4e3cf225f", "size": "73332", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tiva/driverlib/adc.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "12122" }, { "name": "Batchfile", "bytes": "5977" }, { "name": "C", "bytes": "16424701" }, { "name": "C++", "bytes": "100365" }, { "name": "HTML", "bytes": "4782" }, { "name": "Makefile", "bytes": "7293" }, { "name": "Objective-C", "bytes": "467769" } ], "symlink_target": "" }
package com.linecorp.armeria.common; import static java.util.Objects.requireNonNull; import com.google.common.base.MoreObjects; import com.linecorp.armeria.common.stream.DefaultStreamMessageDuplicator; import com.linecorp.armeria.common.stream.StreamMessage; import com.linecorp.armeria.common.stream.StreamMessageWrapper; import io.netty.util.concurrent.EventExecutor; final class DefaultHttpRequestDuplicator extends DefaultStreamMessageDuplicator<HttpObject> implements HttpRequestDuplicator { private final RequestHeaders headers; DefaultHttpRequestDuplicator(HttpRequest req, EventExecutor executor, long maxRequestLength) { super(requireNonNull(req, "req"), obj -> { if (obj instanceof HttpData) { return ((HttpData) obj).length(); } return 0; }, executor, maxRequestLength); headers = req.headers(); } @Override public RequestHeaders headers() { return headers; } @Override public HttpRequest duplicate() { return duplicate(headers); } @Override public HttpRequest duplicate(RequestHeaders newHeaders) { requireNonNull(newHeaders, "newHeaders"); return new DuplicatedHttpRequest(super.duplicate(), newHeaders); } private class DuplicatedHttpRequest extends StreamMessageWrapper<HttpObject> implements HttpRequest { private final RequestHeaders headers; DuplicatedHttpRequest(StreamMessage<? extends HttpObject> delegate, RequestHeaders headers) { super(delegate); this.headers = headers; } @Override public RequestHeaders headers() { return headers; } // Override to return HttpRequestDuplicator. @Override public HttpRequestDuplicator toDuplicator() { return toDuplicator(duplicatorExecutor()); } @Override public HttpRequestDuplicator toDuplicator(EventExecutor executor) { return HttpRequest.super.toDuplicator(executor); } @Override public EventExecutor defaultSubscriberExecutor() { return duplicatorExecutor(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("headers", headers) .toString(); } } }
{ "content_hash": "ba2652540d07e2c776c3cdb3e97e5d98", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 101, "avg_line_length": 28.8, "alnum_prop": 0.6535947712418301, "repo_name": "minwoox/armeria", "id": "24f70374c6769cce9c0956f7c56d94e96ba7cb34", "size": "3081", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/com/linecorp/armeria/common/DefaultHttpRequestDuplicator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7197" }, { "name": "HTML", "bytes": "1222" }, { "name": "Java", "bytes": "16194263" }, { "name": "JavaScript", "bytes": "26702" }, { "name": "Kotlin", "bytes": "90127" }, { "name": "Less", "bytes": "34341" }, { "name": "Scala", "bytes": "209950" }, { "name": "Shell", "bytes": "2062" }, { "name": "Thrift", "bytes": "192676" }, { "name": "TypeScript", "bytes": "243099" } ], "symlink_target": "" }
#include "vehicle_info_plugin/commands/mobile/get_dtcs_request.h" #include "application_manager/application_impl.h" #include "application_manager/message_helper.h" #include "interfaces/HMI_API.h" namespace vehicle_info_plugin { using namespace application_manager; namespace commands { SDL_CREATE_LOG_VARIABLE("Commands") GetDTCsRequest::GetDTCsRequest( const application_manager::commands::MessageSharedPtr& message, const VehicleInfoCommandParams& params) : RequestFromMobileImpl(message, params.application_manager_, params.rpc_service_, params.hmi_capabilities_, params.policy_handler_) {} GetDTCsRequest::~GetDTCsRequest() {} void GetDTCsRequest::Run() { SDL_LOG_AUTO_TRACE(); ApplicationSharedPtr app = application_manager_.application( (*message_)[strings::params][strings::connection_key].asUInt()); if (!app) { SDL_LOG_ERROR("NULL pointer"); SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED); return; } smart_objects::SmartObject msg_params = smart_objects::SmartObject(smart_objects::SmartType_Map); msg_params[strings::ecu_name] = (*message_)[strings::msg_params][strings::ecu_name]; if ((*message_)[strings::msg_params].keyExists(strings::dtc_mask)) { msg_params[strings::dtc_mask] = (*message_)[strings::msg_params][strings::dtc_mask]; } msg_params[strings::app_id] = app->app_id(); StartAwaitForInterface(HmiInterfaces::HMI_INTERFACE_VehicleInfo); SendHMIRequest(hmi_apis::FunctionID::VehicleInfo_GetDTCs, &msg_params, true); } void GetDTCsRequest::on_event(const event_engine::Event& event) { SDL_LOG_AUTO_TRACE(); const smart_objects::SmartObject& message = event.smart_object(); switch (event.id()) { case hmi_apis::FunctionID::VehicleInfo_GetDTCs: { EndAwaitForInterface(HmiInterfaces::HMI_INTERFACE_VehicleInfo); hmi_apis::Common_Result::eType result_code = static_cast<hmi_apis::Common_Result::eType>( message[strings::params][hmi_response::code].asInt()); const bool result = PrepareResultForMobileResponse( result_code, HmiInterfaces::HMI_INTERFACE_VehicleInfo); std::string response_info; GetInfo(message, response_info); SendResponse(result, MessageHelper::HMIToMobileResult(result_code), response_info.empty() ? NULL : response_info.c_str(), &(message[strings::msg_params])); break; } default: { SDL_LOG_ERROR("Received unknown event " << event.id()); return; } } } } // namespace commands } // namespace vehicle_info_plugin
{ "content_hash": "709721eeeb9fa7c186edbdf7fc242727", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 79, "avg_line_length": 31.60919540229885, "alnum_prop": 0.6621818181818182, "repo_name": "smartdevicelink/sdl_core", "id": "9044e0a1aab077beb9b2b853166f4f2d235d7ea2", "size": "4263", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/application_manager/rpc_plugins/vehicle_info_plugin/src/commands/mobile/get_dtcs_request.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "27115" }, { "name": "C++", "bytes": "22338348" }, { "name": "CMake", "bytes": "435397" }, { "name": "M4", "bytes": "25347" }, { "name": "Makefile", "bytes": "139997" }, { "name": "Python", "bytes": "566738" }, { "name": "Shell", "bytes": "696186" } ], "symlink_target": "" }
package be.wegenenverkeer.designtests; import be.wegenenverkeer.UsingWireMockRxJava; import be.wegenenverkeer.rxhttpclient.ClientRequest; import be.wegenenverkeer.rxhttpclient.HttpClientError; import be.wegenenverkeer.rxhttpclient.ServerResponse; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.subscribers.TestSubscriber; import org.junit.Test; import java.util.concurrent.TimeUnit; import static com.github.tomakehurst.wiremock.client.WireMock.*; /** * Test for POST requests. * <p> * Created by Karel Maesen, Geovise BVBA on 19/12/14. */ public class RxHttpClientPostTests extends UsingWireMockRxJava { //this is a post that creates a contact entity, and then //retrieves it back from the server. @Test public void POSTHappyPath() { //set up stub String expectBody = "{ 'name': 'John Doe }"; stubFor(post(urlPathEqualTo("/contacts/new")) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse().withFixedDelay(DEFAULT_REQUEST_TIME_OUT / 3) .withStatus(201) .withHeader("Content-Type", "application/json") .withHeader("Location", "/contacts/123")) ); stubFor(get(urlPathEqualTo("/contacts/123")) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse().withFixedDelay(DEFAULT_REQUEST_TIME_OUT / 3) .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(expectBody)) ); //set up use case String path = "/contacts/new"; ClientRequest request = client.requestBuilder() .setMethod("POST") .setUrlRelativetoBase(path) .build(); Flowable<String> flowable = client.executeToCompletion(request, resp -> resp.getHeader("Location").get()) .flatMap(url -> client.executeToCompletion( client.requestBuilder().setMethod("GET").setUrlRelativetoBase(url).build(), ServerResponse::getResponseBody ) ); TestSubscriber<String> sub = flowable.test(); sub.awaitDone(getTimeOut(), TimeUnit.MILLISECONDS); sub.assertNoErrors(); sub.assertValues(expectBody); } @Test public void POSTFailure() { //set up stub String expectFailedBody = "{ \"message\": \"unauthorized\" }"; stubFor(post(urlPathEqualTo("/contacts/new")) .withHeader("Accept", equalTo("application/json")) .willReturn(aResponse().withFixedDelay(DEFAULT_REQUEST_TIME_OUT / 3) .withStatus(403) .withHeader("Content-Type", "application/json") .withBody(expectFailedBody)) ); //set up use case String path = "/contacts/new"; ClientRequest request = client.requestBuilder() .setMethod("POST") .setUrlRelativetoBase(path) .build(); Flowable<String> flowable = client.executeToCompletion(request, ServerResponse::getResponseBody); TestSubscriber<String> sub = flowable.test(); sub.awaitDone(getTimeOut(), TimeUnit.MILLISECONDS); sub.assertError(t -> { if (t instanceof HttpClientError) { HttpClientError hte = (HttpClientError) t; ServerResponse sr = hte.getResponse().get(); return hte.getStatusCode() == 403 && sr.getResponseBody().equals(expectFailedBody) && sr.getContentType().get().equals("application/json"); } else return false; }); } }
{ "content_hash": "c30122aa5ff255730490b6f4f0bb28cc", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 115, "avg_line_length": 38.549019607843135, "alnum_prop": 0.5803662258392676, "repo_name": "WegenenVerkeer/RxHttpClient", "id": "835fb0324656daa8b9c5a8f812f060a7f6a6e5ed", "size": "3932", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "modules/java/src/test/java/be/wegenenverkeer/designtests/RxHttpClientPostTests.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "192794" }, { "name": "Scala", "bytes": "12441" } ], "symlink_target": "" }
using System; using NUnit.Framework; using System.Linq; using SilverNeedle; using SilverNeedle.Characters; using SilverNeedle.Yaml; namespace Characters { [TestFixture] public class SkillYamlGatewayTests { Skill Acrobatics; Skill Bluff; Skill DisableDevice; [SetUp] public void LoadYamlRepository() { var repo = new SkillYamlGateway (SkillsYamlFile.ParseYaml()); var skills = repo.All(); Acrobatics = skills.First (x => x.Name == "Acrobatics"); Bluff = skills.First (x => x.Name == "Bluff"); DisableDevice = skills.First (x => x.Name == "Disable Device"); } [Test] public void LoadSkillsYamlFile() { Assert.IsNotNull (Acrobatics); Assert.IsNotNull (Bluff); Assert.IsNotNull (DisableDevice); } [Test] public void SkillsHaveAnAbilityToBaseScoresFrom() { Assert.AreEqual (AbilityScoreTypes.Dexterity, Acrobatics.Ability); Assert.AreEqual (AbilityScoreTypes.Charisma, Bluff.Ability); Assert.AreEqual (AbilityScoreTypes.Dexterity, DisableDevice.Ability); } [Test] public void SomeSkillsRequireTraining() { Assert.IsFalse (Acrobatics.TrainingRequired); Assert.IsTrue (DisableDevice.TrainingRequired); } [Test] public void SkillsCanHaveALongDescription() { Assert.AreEqual ("A really long description.\n", Acrobatics.Description); } private const string SkillsYamlFile = @"--- - skill: name: Acrobatics ability: dexterity trained: no description: > A really long description. - skill: name: Bluff ability: charisma trained: no description: > A really long description. - skill: name: Disable Device ability: dexterity trained: yes description: > A really long description. ..."; } }
{ "content_hash": "9f5e2f5a8fd3a09845177ef75079ebda", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 76, "avg_line_length": 22.57894736842105, "alnum_prop": 0.7127039627039627, "repo_name": "shortlegstudio/silverneedle", "id": "11aff3887bfad4a57e6d14189bd96753f809235b", "size": "1718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/SilverNeedle/Tests/Editor/Characters/Gateways/SkillYamlGatewayTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1139075" } ], "symlink_target": "" }
package com.lactozily.addict; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.util.Log; import com.evernote.android.job.Job; /** * Created by lactozily on 2/27/2016 AD. */ public class AddictServiceChecker extends Job { public static final String TAG = "addict-service-checker"; @Override @NonNull protected Result onRunJob(Params params) { Log.i(TAG, "Check Service"); // run your job Context mContext = this.getContext(); if (!AddictUtility.isMyServiceRunning(mContext, AddictMonitorService.class)) { Log.e(TAG, "Service is not running"); Intent intent = new Intent(mContext, AddictMonitorService.class); this.getContext().startService(intent); } Log.i(TAG, "Service is running"); return Result.SUCCESS; } }
{ "content_hash": "7ff9f79af088576804ba99bb0f30deee", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 86, "avg_line_length": 29.096774193548388, "alnum_prop": 0.6751662971175166, "repo_name": "lactozily/addict", "id": "879bbbc03a06bb861b1c8be7884d2ef6f464fde6", "size": "902", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/lactozily/addict/AddictServiceChecker.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "60701" } ], "symlink_target": "" }
:- module(rdf_describe, [ rdf_bounded_description/4, % :Expand, +Type, +URI, -Graph rdf_bounded_description/5, % :Expand, +Type, +Pattern, +URI, -Graph resource_CBD/3, % :Expand, +URI, -Graph graph_CBD/3, % :Expand, +Graph0, -Graph rdf_include_reifications/3, % :Expand, +Graph0, -Graph rdf_include_labels/3, % :Expand, +Graph0, -Graph lcbd_label/3 % +Subject, -Pred, -Label ]). :- use_module(library(semweb/rdf_db)). :- use_module(library(assoc)). :- use_module(library(lists)). /** <module> RDF Bounded descriptions The predicates in this module deal with `RDF bounded descriptions'. A bounded description is a subgraph that describes a single resource (URI). Unfortunately, such an isolated description is not possible without the possibility of loosing semantics. We provide some meaningful approximations described in the literature. Scanning the definitions given in the link below, we distinguish two ortogonal expansions: one expanding the graph and another adding either reifications or labels. Expansion is implemented by rdf_bounded_description/4, while the returned graph can be further expanded using rdf_include_reifications/3 and/or rdf_include_labels/3. @tbd Also implement the variations on CBD @see http://n2.talis.com/wiki/Bounded_Descriptions_in_RDF */ :- meta_predicate rdf_bounded_description(3, +, +, -), resource_CBD(3, +, -), graph_CBD(3, +, -), rdf_include_reifications(3, +, -). /******************************* * RESOURCE OPERATIONS * *******************************/ %% rdf_bounded_description(:Expand, +Type, +URI, -Graph) is det. %% rdf_bounded_description(:Expand, +Type, +Filter, +URI, -Graph) is det. % % Graph is a Bounded Description of URI. The literature defines % various types of bounding descriptions. Currently supported % types are: % % * cbd % Concise Bounded Description of URI. This notion is also % known as "the bnode-closure of a resource" % * scbd % Symmetric Concise Bounded Description is similar to % =cbd=, but includes triples with both URI as subject and % object. rdf_bounded_description(Expand, Type, S, Graph) :- rdf_bounded_description(Expand, Type, [], S, Graph). rdf_bounded_description(Expand, Type, Filter, S, Graph) :- empty_assoc(Map0), compile_pattern(Filter, Triple, Expand, Filter1), expansion(Type, Expand, S, Triple, Filter1, Graph, BNG), phrase(new_bnodes(Graph, Map0), BN), phrase(r_bnodes(BN, Type, Expand, Map0, _Map), BNG). compile_pattern([], _, _, true). compile_pattern([rdf(S,P,O)], rdf(S,P,O), Expand, call(Expand, S,P,O)) :- !. compile_pattern([rdf(S,P,O)|T], rdf(S,P,O), Expand, ( call(Expand, S,P,O) ; More )) :- compile_pattern(T, rdf(S,P,O), Expand, More). :- meta_predicate expansion(+, 3, +, +, +, -, ?), r_bnodes(+, +, 3, +, -, ?, ?). expansion(cbd, Expand, S, rdf(S,P,O), Filter, RDF, Tail) :- findall(rdf(S,P,O), (call(Expand, S,P,O),Filter), RDF, Tail). expansion(scbd, Expand, S, rdf(S,P,O), Filter, RDF, Tail) :- findall(rdf(S,P,O), (call(Expand, S,P,O),Filter), RDF, T0), findall(rdf(O,P,S), (call(Expand, O,P,S),Filter), T0, Tail). r_bnodes([], _, _, Map, Map) --> []. r_bnodes([H|T], Type, Expand, Map0, Map, Graph, Tail) :- rdf_is_bnode(H), !, put_assoc(H, Map0, true, Map1), expansion(Type, Expand, H, _, true, Graph, Tail0), phrase(new_bnodes(Graph, Map1), BN, T), r_bnodes(BN, Type, Expand, Map1, Map, Tail0, Tail). r_bnodes([_|T], Type, Expand, Map0, Map) --> r_bnodes(T, Type, Expand, Map0, Map). new_bnodes(Var, _) --> { var(Var) }, !. new_bnodes([rdf(S,_,O)|RDF], Map) --> new_bnode(S, Map), new_bnode(O, Map), new_bnodes(RDF, Map). new_bnode(S, Map) --> { rdf_is_bnode(S), \+ get_assoc(S, Map, _) }, !, [S]. new_bnode(_, _) --> []. %% resource_CBD(:Expand, +URI, -Graph) is det. % % Graph is the Concise Bounded Description of URI. This notion is % also known as "the bnode-closure of a resource". Note that, % according to the definition on the Talis wiki, the CBD includes % reified statements. This predicate does not do this. Use % rdf_include_reifications/3 to add reifications to the graph. % % @param Expand is called to enumerate the PO pairs for a subject. % This will often be =rdf= to use rdf/3. % @see http://n2.talis.com/wiki/Bounded_Descriptions_in_RDF resource_CBD(Expand, S, Graph) :- rdf_bounded_description(Expand, cbd, S, Graph). /******************************* * GRAPH OPERATIONS * *******************************/ %% graph_CBD(:Expand, +Graph0, -Graph) is det. % % Add concise bounded descriptions for bnodes in a graph, creating % an expanded graph. graph_CBD(Expand, Graph0, Graph) :- empty_assoc(Map0), must_be(list, Graph0), phrase(gr_cbd(Graph0, Expand, Map0, _Map), Graph). :- meta_predicate gr_cbd(+, 3, +, -, ?, ?). gr_cbd([], _, Map, Map) --> []. gr_cbd([rdf(S,P,O)|T], Expand, Map0, Map) --> { rdf_is_bnode(S) ; rdf_is_bnode(O) }, !, [ rdf(S,P,O) ], r_bnodes([S,O], cbd, Expand, Map0, Map1), gr_cbd(T, Expand, Map1, Map). gr_cbd([Triple|T], Expand, Map0, Map) --> [Triple], gr_cbd(T, Expand, Map0, Map). %% rdf_include_reifications(:Expand, +Graph0, -Graph) is det. % % Include the reification of any reified statements in Graph0. rdf_include_reifications(Expand, Graph0, Graph) :- phrase(reified_triples(Graph0, Expand), Statements), ( Statements == [] -> Graph = Graph0 ; graph_CBD(Expand, Statements, Statements1), rdf_include_reifications(Expand, Statements1, Graph1), append(Graph0, Graph1, Graph) ). :- meta_predicate reified_triples(+, 3, ?, ?), reification(?,?,?,3,-). reified_triples([], _) --> []. reified_triples([rdf(S,P,O)|T], Expand) --> findall(T, reification(S,P,O,Expand,T)), reified_triples(T, Expand). reification(S,P,O, Expand, Triple) :- rdf_equal(SP, rdf:subject), rdf_equal(PP, rdf:predicate), rdf_equal(OP, rdf:object), call(Expand, Stmt, SP, S), call(Expand, Stmt, OP, O), call(Expand, Stmt, PP, P), ( Triple = rdf(Stmt, SP, S) ; Triple = rdf(Stmt, PP, P) ; Triple = rdf(Stmt, OP, O) ). %% rdf_include_labels(:Expand, +Graph0, -Graph) is det. % % Include missing `label' statements in Graph0. Expand must % provide label triples on % % call(Expand, S, P, O) % % The predicate lcbd_label/3 does this for the standard % definition, considering the properties rdfs:label, rdfs:comment % and rdfs:seeAlso. rdf_include_labels(Expand, Graph0, Graph) :- phrase(label_triples(Graph0, Expand), LabelRDF), ( LabelRDF == [] -> Graph = Graph0 ; append(Graph0, LabelRDF, Graph) ). :- meta_predicate label_triples(+, 3, ?, ?), label_triple(+, 3, -). label_triples([], _) --> []. label_triples([rdf(_,_,O)|T], Expand) --> findall(T, label_triple(O,Expand,T)), label_triples(T, Expand). label_triple(O, Expand, Triple) :- call(Expand, O, LP, Label), Triple = rdf(O, LP, Label). :- rdf_meta lcbd_property(r). %% lcbd_label(+S, -P, -Label) is nondet. % % Standard conforming `Expand' for rdf_include_labels/3. lcbd_label(S, P, Label) :- lcbd_property(P), rdf_has(S, P, Label). lcbd_property(rdfs:label). lcbd_property(rdfs:comment). lcbd_property(rdfs:seeAlso).
{ "content_hash": "ff9d6dcc345a07048fc071583c1f0d0d", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 75, "avg_line_length": 30.544303797468356, "alnum_prop": 0.638071556844868, "repo_name": "TeamSPoon/logicmoo_workspace", "id": "8bb13d6c552899b5dbaa09222acc092e2da2c04c", "size": "8625", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packs_web/ClioPatria/lib/semweb/rdf_describe.pl", "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": "" }
export APP_SECRET="" # any secret key for session management export MONGO_URI="" # mongo db URI, check out compose.io export DB_NAME="" # name of your mongo database export GITHUB_ORG="" # github org id for your class # setup an app on github for your org # https://github.com/organizations/{YOUR_ORG_NAME}/settings/applications export GITHUB_CLIENT_ID="" export GITHUB_CLIENT_SECRET=""
{ "content_hash": "695e1dd863bcf3d7edd02f247ca2c073", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 72, "avg_line_length": 39.1, "alnum_prop": 0.7442455242966752, "repo_name": "ottosipe/github-class-repo-manager", "id": "adb4dde76bcc0906a6e6499858b387e5e9dc62a2", "size": "392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "secret-ex.sh", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "225" }, { "name": "JavaScript", "bytes": "2239" }, { "name": "Python", "bytes": "10358" }, { "name": "Shell", "bytes": "392" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.oodt</groupId> <artifactId>oodt-core</artifactId> <version>0.11-SNAPSHOT</version> <relativePath>../../core/pom.xml</relativePath> </parent> <packaging>jar</packaging> <artifactId>cas-protocol-http</artifactId> <name>CAS Protocol HTTP Implementation</name> <profiles> <profile> <id>create-osgi-bundles-from-dependencies</id> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>2.3.7</version> <configuration> <supportedProjectTypes> <supportedProjectType>jar</supportedProjectType> <supportedProjectType>bundle</supportedProjectType> <supportedProjectType>war</supportedProjectType> </supportedProjectTypes> <instructions> <Bundle-Name>${project.artifactId}</Bundle-Name> <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName> <Bundle-Description>OSGI version of ${project.name}</Bundle-Description> <Export-Package>org.apache.oodt.cas.protocol.http.*</Export-Package> <Embed-Dependency>*;scope=compile|runtime</Embed-Dependency> <Embed-Transitive>true</Embed-Transitive> <Import-Package>*;resolution:=optional</Import-Package> </instructions> </configuration> <extensions>true</extensions> </plugin> </plugins> </build> </profile> <profile> <id>audit</id> <activation> <activeByDefault>false</activeByDefault> </activation> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>rat-maven-plugin</artifactId> <configuration> <excludes> <exclude>**/resources/examples/**/*</exclude> </excludes> </configuration> <executions> <execution> <phase>verify</phase> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>2.3.7</version> <configuration> <supportedProjectTypes> <supportedProjectType>jar</supportedProjectType> <supportedProjectType>bundle</supportedProjectType> <supportedProjectType>war</supportedProjectType> </supportedProjectTypes> <instructions> <Bundle-Name>${project.artifactId}</Bundle-Name> <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName> <Bundle-Description>OSGI version of ${project.name}</Bundle-Description> <Export-Package>org.apache.oodt.cas.protocol.http.*</Export-Package> <Import-Package>*;resolution:=optional</Import-Package> </instructions> </configuration> <extensions>true</extensions> </plugin> </plugins> </build> </profile> </profiles> <build> <resources> <resource> <targetPath>org/apache/oodt/cas/protocol/http</targetPath> <directory>${basedir}/src/main/resources/policy</directory> <includes> <include>http-protocol-config.xml</include> </includes> </resource> </resources> </build> <dependencies> <dependency> <groupId>org.apache.oodt</groupId> <artifactId>cas-protocol-api</artifactId> <version>${project.parent.version}</version> </dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.0</version> </dependency> <dependency> <groupId>nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.6.2</version> </dependency> <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-parsers</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.2</version> <scope>test</scope> </dependency> </dependencies> </project>
{ "content_hash": "459e585c56d50a4de33c64438514aae6", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 201, "avg_line_length": 35.8, "alnum_prop": 0.6845570630486831, "repo_name": "OSBI/oodt", "id": "4fb3d0380015148fbfc560ae436a27c69b3cb6b2", "size": "5012", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "protocol/http/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "2030" }, { "name": "C++", "bytes": "22622" }, { "name": "CSS", "bytes": "168572" }, { "name": "HTML", "bytes": "128991" }, { "name": "Java", "bytes": "7508539" }, { "name": "JavaScript", "bytes": "219131" }, { "name": "Makefile", "bytes": "1135" }, { "name": "PHP", "bytes": "432599" }, { "name": "PLSQL", "bytes": "3736" }, { "name": "Perl", "bytes": "4459" }, { "name": "Python", "bytes": "131018" }, { "name": "Ruby", "bytes": "4884" }, { "name": "Scala", "bytes": "1015" }, { "name": "Shell", "bytes": "108730" }, { "name": "TeX", "bytes": "862979" }, { "name": "XSLT", "bytes": "28584" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ChangeListManager"> <list default="true" id="331ea93a-d8a9-4043-b291-fbba0a0db131" name="Default" comment="vlidate"> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/css/test.css" afterPath="$PROJECT_DIR$/css/test.css" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/.idea/workspace.xml" afterPath="$PROJECT_DIR$/.idea/workspace.xml" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/../WebPageDemo/.idea/workspace.xml" afterPath="$PROJECT_DIR$/../WebPageDemo/.idea/workspace.xml" /> </list> <ignored path="JavascriptExercise.iws" /> <ignored path=".idea/workspace.xml" /> <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" /> <option name="TRACKING_ENABLED" value="true" /> <option name="SHOW_DIALOG" value="false" /> <option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="LAST_RESOLUTION" value="IGNORE" /> </component> <component name="ChangesViewManager" flattened_view="true" show_ignored="false" /> <component name="CreatePatchCommitExecutor"> <option name="PATCH_PATH" value="" /> </component> <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" /> <component name="FavoritesManager"> <favorites_list name="JavascriptExercise" /> </component> <component name="FileEditorManager"> <leaf> <file leaf-file-name="Test.js" pinned="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/js/Test.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="550" column="24" selection-start-line="550" selection-start-column="24" selection-end-line="550" selection-end-column="24" /> <folding /> </state> </provider> </entry> </file> <file leaf-file-name="test.css" pinned="false" current-in-tab="true"> <entry file="file://$PROJECT_DIR$/css/test.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.16536964"> <caret line="5" column="54" selection-start-line="5" selection-start-column="54" selection-end-line="5" selection-end-column="54" /> <folding /> </state> </provider> </entry> </file> <file leaf-file-name="Test.html" pinned="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/html/Test.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-13.076923"> <caret line="20" column="21" selection-start-line="20" selection-start-column="21" selection-end-line="20" selection-end-column="21" /> <folding /> </state> </provider> </entry> </file> </leaf> </component> <component name="FindManager"> <FindUsagesManager> <setting name="OPEN_NEW_TAB" value="true" /> </FindUsagesManager> </component> <component name="Git.Settings"> <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" /> </component> <component name="IdeDocumentHistory"> <option name="CHANGED_PATHS"> <list> <option value="$PROJECT_DIR$/css/test.css" /> </list> </option> </component> <component name="JsBuildToolGruntFileManager" detection-done="true" /> <component name="JsGulpfileManager"> <detection-done>true</detection-done> </component> <component name="NamedScopeManager"> <order /> </component> <component name="ProjectFrameBounds"> <option name="x" value="-8" /> <option name="y" value="-8" /> <option name="width" value="1382" /> <option name="height" value="754" /> </component> <component name="ProjectLevelVcsManager" settingsEditedManually="true"> <OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Checkout" /> <OptionsSetting value="true" id="Update" /> <OptionsSetting value="true" id="Status" /> <OptionsSetting value="true" id="Edit" /> <ConfirmationsSetting value="1" id="Add" /> <ConfirmationsSetting value="0" id="Remove" /> </component> <component name="ProjectReloadState"> <option name="STATE" value="0" /> </component> <component name="ProjectView"> <navigator currentView="ProjectPane" proportions="" version="1"> <flattenPackages /> <showMembers /> <showModules /> <showLibraryContents /> <hideEmptyPackages /> <abbreviatePackageNames /> <autoscrollToSource /> <autoscrollFromSource /> <sortByType /> </navigator> <panes> <pane id="ProjectPane"> <subPane> <PATH> <PATH_ELEMENT> <option name="myItemId" value="JavascriptExercise" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="JavascriptExercise" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="JS_Exercise" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="JavascriptExercise" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="JS_Exercise" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="js" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="JavascriptExercise" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="JS_Exercise" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="html" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="JavascriptExercise" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="JS_Exercise" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="css" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="JavascriptExercise" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="JS_Exercise" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="bower_components" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> </subPane> </pane> <pane id="Scratches" /> <pane id="Scope" /> </panes> </component> <component name="PropertiesComponent"> <property name="options.lastSelected" value="settings.github" /> <property name="options.splitter.main.proportions" value="0.3" /> <property name="options.splitter.details.proportions" value="0.2" /> <property name="options.searchVisible" value="true" /> <property name="WebServerToolWindowFactoryState" value="false" /> <property name="DefaultHtmlFileTemplate" value="Html5" /> <property name="FullScreen" value="false" /> <property name="last_opened_file_path" value="$PROJECT_DIR$" /> <property name="ignore_missing_gitignore" value="true" /> <property name="HbShouldOpenHtmlAsHb" value="" /> </component> <component name="RecentsManager"> <key name="CopyFile.RECENT_KEYS"> <recent name="$PROJECT_DIR$/html" /> <recent name="$PROJECT_DIR$/css" /> <recent name="$PROJECT_DIR$/img" /> <recent name="$PROJECT_DIR$" /> </key> <key name="MoveFile.RECENT_KEYS"> <recent name="$PROJECT_DIR$/html" /> </key> </component> <component name="RunManager"> <configuration default="true" type="DartCommandLineRunConfigurationType" factoryName="Dart Command Line Application"> <method /> </configuration> <configuration default="true" type="DartUnitRunConfigurationType" factoryName="DartUnit"> <method /> </configuration> <configuration default="true" type="JavaScriptTestRunnerKarma" factoryName="Karma" config-file=""> <envs /> <method /> </configuration> <configuration default="true" type="JavascriptDebugType" factoryName="JavaScript Debug"> <method /> </configuration> <configuration default="true" type="JsTestDriver-test-runner" factoryName="JsTestDriver"> <setting name="configLocationType" value="CONFIG_FILE" /> <setting name="settingsFile" value="" /> <setting name="serverType" value="INTERNAL" /> <setting name="preferredDebugBrowser" value="Chrome" /> <method /> </configuration> <configuration default="true" type="NodeJSConfigurationType" factoryName="Node.js" working-dir=""> <method /> </configuration> <configuration default="true" type="cucumber.js" factoryName="Cucumber.js"> <option name="cucumberJsArguments" /> <option name="executablePath" /> <option name="filePath" /> <method /> </configuration> <configuration default="true" type="js.build_tools.gulp" factoryName="Gulp.js"> <method /> </configuration> </component> <component name="ShelveChangesManager" show_recycled="false" /> <component name="SvnConfiguration"> <configuration /> </component> <component name="TaskManager"> <task active="true" id="Default" summary="Default task"> <changelist id="331ea93a-d8a9-4043-b291-fbba0a0db131" name="Default" comment="" /> <created>1441517490253</created> <option name="number" value="Default" /> <updated>1441517490253</updated> </task> <task id="LOCAL-00001" summary="from mac"> <created>1442479774028</created> <option name="number" value="00001" /> <option name="project" value="LOCAL" /> <updated>1442479774028</updated> </task> <task id="LOCAL-00002" summary="左移右移"> <created>1442556222343</created> <option name="number" value="00002" /> <option name="project" value="LOCAL" /> <updated>1442556222343</updated> </task> <task id="LOCAL-00003" summary="左移右移"> <created>1442556350992</created> <option name="number" value="00003" /> <option name="project" value="LOCAL" /> <updated>1442556350992</updated> </task> <task id="LOCAL-00004" summary="左移右移"> <created>1442556359308</created> <option name="number" value="00004" /> <option name="project" value="LOCAL" /> <updated>1442556359308</updated> </task> <task id="LOCAL-00005" summary="update"> <created>1444445502060</created> <option name="number" value="00005" /> <option name="project" value="LOCAL" /> <updated>1444445502060</updated> </task> <option name="localTasksCounter" value="6" /> <servers /> </component> <component name="ToolWindowManager"> <frame x="-8" y="-8" width="1382" height="754" extended-state="6" /> <editor active="true" /> <layout> <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.16145833" sideWeight="0.4992722" order="0" side_tool="false" content_ui="combo" /> <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32718122" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" /> <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.32896653" sideWeight="0.5003524" order="7" side_tool="true" content_ui="tabs" /> <window_info id="Application Servers" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" /> <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.27181208" sideWeight="0.49964765" order="7" side_tool="false" content_ui="tabs" /> <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" /> <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.088926174" sideWeight="0.49964765" order="7" side_tool="false" content_ui="tabs" /> <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.16208598" sideWeight="0.5007278" order="2" side_tool="true" content_ui="tabs" /> <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.19005848" sideWeight="0.49964765" order="7" side_tool="false" content_ui="tabs" /> <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" /> <window_info id="Messages" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" /> <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Documentation" active="true" anchor="right" auto_hide="false" internal_type="DOCKED" type="FLOATING" visible="true" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" x="100" y="123" width="1240" height="605" /> <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" /> <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" /> <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> </layout> </component> <component name="Vcs.Log.UiProperties"> <option name="RECENTLY_FILTERED_USER_GROUPS"> <collection /> </option> <option name="RECENTLY_FILTERED_BRANCH_GROUPS"> <collection /> </option> </component> <component name="VcsContentAnnotationSettings"> <option name="myLimit" value="2678400000" /> </component> <component name="VcsManagerConfiguration"> <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="false" /> <MESSAGE value="from mac" /> <MESSAGE value="左移右移" /> <MESSAGE value="update" /> <option name="LAST_COMMIT_MESSAGE" value="update" /> </component> <component name="XDebuggerManager"> <breakpoint-manager> <option name="time" value="4" /> </breakpoint-manager> <watches-manager /> </component> <component name="editorHistoryManager"> <entry file="file://$PROJECT_DIR$/html/panner.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="16" column="36" selection-start-line="16" selection-start-column="36" selection-end-line="16" selection-end-column="36" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/css/default.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="13" column="30" selection-start-line="13" selection-start-column="30" selection-end-line="13" selection-end-column="30" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/Test.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="11" column="81" selection-start-line="11" selection-start-column="81" selection-end-line="11" selection-end-column="81" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/Test.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="401" column="4" selection-start-line="401" selection-start-column="4" selection-end-line="401" selection-end-column="4" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/Test.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="11" column="81" selection-start-line="11" selection-start-column="81" selection-end-line="11" selection-end-column="81" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/Test.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="423" column="0" selection-start-line="423" selection-start-column="0" selection-end-line="423" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/Test.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="8" column="63" selection-start-line="8" selection-start-column="63" selection-end-line="8" selection-end-column="63" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/Test.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="422" column="18" selection-start-line="422" selection-start-column="18" selection-end-line="422" selection-end-column="18" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/Test.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="8" column="63" selection-start-line="8" selection-start-column="63" selection-end-line="8" selection-end-column="63" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/Test.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="360" column="0" selection-start-line="360" selection-start-column="0" selection-end-line="360" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/Test.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="5" column="4" selection-start-line="5" selection-start-column="4" selection-end-line="5" selection-end-column="4" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/Test.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="334" column="10" selection-start-line="334" selection-start-column="10" selection-end-line="334" selection-end-column="10" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/Test.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="5" column="4" selection-start-line="5" selection-start-column="4" selection-end-line="5" selection-end-column="4" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/Test.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="131" column="13" selection-start-line="131" selection-start-column="13" selection-end-line="131" selection-end-column="13" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/bower_components/jquery/src/ajax.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-1.1630219"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/bower_components/jquery/dist/jquery.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.33673468"> <caret line="11" column="26" selection-start-line="11" selection-start-column="26" selection-end-line="11" selection-end-column="26" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/img/01.jpg"> <provider selected="true" editor-type-id="images"> <state /> </provider> </entry> <entry file="file://$PROJECT_DIR$/img/b5df2063502528.t1.jpg"> <provider selected="true" editor-type-id="images"> <state /> </provider> </entry> <entry file="file://$PROJECT_DIR$/img/btn_cartoon.gif"> <provider selected="true" editor-type-id="images"> <state /> </provider> </entry> <entry file="file://$PROJECT_DIR$/img/down.gif"> <provider selected="true" editor-type-id="images"> <state /> </provider> </entry> <entry file="file://$PROJECT_DIR$/img/up.gif"> <provider selected="true" editor-type-id="images"> <state /> </provider> </entry> <entry file="file://$PROJECT_DIR$/css/style.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.40789473"> <caret line="19" column="22" selection-start-line="19" selection-start-column="22" selection-end-line="19" selection-end-column="22" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/css/style1.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.33211008"> <caret line="120" column="20" selection-start-line="120" selection-start-column="20" selection-end-line="120" selection-end-column="20" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/自定义图片提示.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.18134715"> <caret line="7" column="4" selection-start-line="7" selection-start-column="4" selection-end-line="7" selection-end-column="96" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/文本框高度变化.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.16666667"> <caret line="58" column="11" selection-start-line="58" selection-start-column="11" selection-end-line="58" selection-end-column="11" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/LICENSE"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/README.md"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.047468353"> <caret line="2" column="0" selection-start-line="2" selection-start-column="0" selection-end-line="2" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/文本框内容滚动.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.13461539"> <caret line="42" column="0" selection-start-line="42" selection-start-column="0" selection-end-line="42" selection-end-column="96" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/左移右移.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.42638624"> <caret line="80" column="0" selection-start-line="80" selection-start-column="0" selection-end-line="80" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/css/style2.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.45155394"> <caret line="33" column="30" selection-start-line="33" selection-start-column="30" selection-end-line="33" selection-end-column="30" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/panner.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.2294455"> <caret line="8" column="0" selection-start-line="8" selection-start-column="0" selection-end-line="8" selection-end-column="96" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/data.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.34416825"> <caret line="12" column="6" selection-start-line="12" selection-start-column="6" selection-end-line="12" selection-end-column="6" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/get1.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="32" column="9" selection-start-line="32" selection-start-column="9" selection-end-line="32" selection-end-column="9" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/demo6.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.8852773"> <caret line="44" column="22" selection-start-line="44" selection-start-column="22" selection-end-line="46" selection-end-column="16" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/expand.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.21830986"> <caret line="7" column="3" selection-start-line="7" selection-start-column="3" selection-end-line="7" selection-end-column="96" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/bower_components/jquery/src/jquery.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-0.39308855"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/demo4.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="24" column="4" selection-start-line="24" selection-start-column="4" selection-end-line="24" selection-end-column="96" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/jquery.color.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.5183585"> <caret line="16" column="70" selection-start-line="16" selection-start-column="70" selection-end-line="16" selection-end-column="70" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/.idea/workspace.xml"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-4.6835938"> <caret line="79" column="57" selection-start-line="79" selection-start-column="57" selection-end-line="79" selection-end-column="57" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/../WebPageDemo/.idea/workspace.xml"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/自定义文字提示.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.6164383"> <caret line="57" column="27" selection-start-line="57" selection-start-column="27" selection-end-line="57" selection-end-column="27" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/ltrim和rtrim插件.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.60402685"> <caret line="20" column="19" selection-start-line="20" selection-start-column="19" selection-end-line="20" selection-end-column="19" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/css/default.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-0.6568915"> <caret line="13" column="30" selection-start-line="13" selection-start-column="30" selection-end-line="13" selection-end-column="30" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/ajax_aimation.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="1.70347"> <caret line="57" column="13" selection-start-line="57" selection-start-column="13" selection-end-line="57" selection-end-column="13" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/between插件.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.5205047"> <caret line="11" column="23" selection-start-line="11" selection-start-column="23" selection-end-line="11" selection-end-column="23" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/color_js.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="0" column="0" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/Ajax_load.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.51419556"> <caret line="35" column="3" selection-start-line="35" selection-start-column="3" selection-end-line="35" selection-end-column="96" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/视屏左右滑动视窗.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.28391168"> <caret line="6" column="3" selection-start-line="6" selection-start-column="3" selection-end-line="6" selection-end-column="69" /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/js/Test.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0"> <caret line="550" column="24" selection-start-line="550" selection-start-column="24" selection-end-line="550" selection-end-column="24" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/html/Test.html"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-13.076923"> <caret line="20" column="21" selection-start-line="20" selection-start-column="21" selection-end-line="20" selection-end-column="21" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/css/test.css"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.16536964"> <caret line="5" column="54" selection-start-line="5" selection-start-column="54" selection-end-line="5" selection-end-column="54" /> <folding /> </state> </provider> </entry> </component> </project>
{ "content_hash": "6151fd4e354bc04fc3802311c530373f", "timestamp": "", "source": "github", "line_count": 697, "max_line_length": 260, "avg_line_length": 51.605451936872306, "alnum_prop": 0.6332675359337206, "repo_name": "Linzai1994/JS_Exercise", "id": "f41399b9ea3c98c5d1e9c4a37bfc26b9be191e5e", "size": "36091", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/workspace.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8049" }, { "name": "HTML", "bytes": "46913" }, { "name": "JavaScript", "bytes": "28462" } ], "symlink_target": "" }
// Code generated by client-gen. DO NOT EDIT. package fake import ( "context" v1alpha1 "github.com/tektoncd/triggers/pkg/apis/triggers/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" ) // FakeClusterTriggerBindings implements ClusterTriggerBindingInterface type FakeClusterTriggerBindings struct { Fake *FakeTriggersV1alpha1 } var clustertriggerbindingsResource = schema.GroupVersionResource{Group: "triggers.tekton.dev", Version: "v1alpha1", Resource: "clustertriggerbindings"} var clustertriggerbindingsKind = schema.GroupVersionKind{Group: "triggers.tekton.dev", Version: "v1alpha1", Kind: "ClusterTriggerBinding"} // Get takes name of the clusterTriggerBinding, and returns the corresponding clusterTriggerBinding object, and an error if there is any. func (c *FakeClusterTriggerBindings) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.ClusterTriggerBinding, err error) { obj, err := c.Fake. Invokes(testing.NewRootGetAction(clustertriggerbindingsResource, name), &v1alpha1.ClusterTriggerBinding{}) if obj == nil { return nil, err } return obj.(*v1alpha1.ClusterTriggerBinding), err } // List takes label and field selectors, and returns the list of ClusterTriggerBindings that match those selectors. func (c *FakeClusterTriggerBindings) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.ClusterTriggerBindingList, err error) { obj, err := c.Fake. Invokes(testing.NewRootListAction(clustertriggerbindingsResource, clustertriggerbindingsKind, opts), &v1alpha1.ClusterTriggerBindingList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &v1alpha1.ClusterTriggerBindingList{ListMeta: obj.(*v1alpha1.ClusterTriggerBindingList).ListMeta} for _, item := range obj.(*v1alpha1.ClusterTriggerBindingList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } // Watch returns a watch.Interface that watches the requested clusterTriggerBindings. func (c *FakeClusterTriggerBindings) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewRootWatchAction(clustertriggerbindingsResource, opts)) } // Create takes the representation of a clusterTriggerBinding and creates it. Returns the server's representation of the clusterTriggerBinding, and an error, if there is any. func (c *FakeClusterTriggerBindings) Create(ctx context.Context, clusterTriggerBinding *v1alpha1.ClusterTriggerBinding, opts v1.CreateOptions) (result *v1alpha1.ClusterTriggerBinding, err error) { obj, err := c.Fake. Invokes(testing.NewRootCreateAction(clustertriggerbindingsResource, clusterTriggerBinding), &v1alpha1.ClusterTriggerBinding{}) if obj == nil { return nil, err } return obj.(*v1alpha1.ClusterTriggerBinding), err } // Update takes the representation of a clusterTriggerBinding and updates it. Returns the server's representation of the clusterTriggerBinding, and an error, if there is any. func (c *FakeClusterTriggerBindings) Update(ctx context.Context, clusterTriggerBinding *v1alpha1.ClusterTriggerBinding, opts v1.UpdateOptions) (result *v1alpha1.ClusterTriggerBinding, err error) { obj, err := c.Fake. Invokes(testing.NewRootUpdateAction(clustertriggerbindingsResource, clusterTriggerBinding), &v1alpha1.ClusterTriggerBinding{}) if obj == nil { return nil, err } return obj.(*v1alpha1.ClusterTriggerBinding), err } // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). func (c *FakeClusterTriggerBindings) UpdateStatus(ctx context.Context, clusterTriggerBinding *v1alpha1.ClusterTriggerBinding, opts v1.UpdateOptions) (*v1alpha1.ClusterTriggerBinding, error) { obj, err := c.Fake. Invokes(testing.NewRootUpdateSubresourceAction(clustertriggerbindingsResource, "status", clusterTriggerBinding), &v1alpha1.ClusterTriggerBinding{}) if obj == nil { return nil, err } return obj.(*v1alpha1.ClusterTriggerBinding), err } // Delete takes name of the clusterTriggerBinding and deletes it. Returns an error if one occurs. func (c *FakeClusterTriggerBindings) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewRootDeleteActionWithOptions(clustertriggerbindingsResource, name, opts), &v1alpha1.ClusterTriggerBinding{}) return err } // DeleteCollection deletes a collection of objects. func (c *FakeClusterTriggerBindings) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { action := testing.NewRootDeleteCollectionAction(clustertriggerbindingsResource, listOpts) _, err := c.Fake.Invokes(action, &v1alpha1.ClusterTriggerBindingList{}) return err } // Patch applies the patch and returns the patched clusterTriggerBinding. func (c *FakeClusterTriggerBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.ClusterTriggerBinding, err error) { obj, err := c.Fake. Invokes(testing.NewRootPatchSubresourceAction(clustertriggerbindingsResource, name, pt, data, subresources...), &v1alpha1.ClusterTriggerBinding{}) if obj == nil { return nil, err } return obj.(*v1alpha1.ClusterTriggerBinding), err }
{ "content_hash": "6d07d0d8938862df2f72bcf83b7d8629", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 209, "avg_line_length": 47.32773109243698, "alnum_prop": 0.7911931818181818, "repo_name": "tektoncd/triggers", "id": "59be88c8aa566e63187b0311279bf7734dbaacef", "size": "6196", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pkg/client/clientset/versioned/typed/triggers/v1alpha1/fake/fake_clustertriggerbinding.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "1081483" }, { "name": "Makefile", "bytes": "5967" }, { "name": "Shell", "bytes": "42793" }, { "name": "Smarty", "bytes": "3940" } ], "symlink_target": "" }
package org.apache.lucene.util; import org.apache.lucene.analysis.Token; import org.apache.lucene.analysis.tokenattributes.*; import java.util.HashMap; import java.util.Iterator; @SuppressWarnings("deprecation") public class TestAttributeSource extends LuceneTestCase { public void testCaptureState() { // init a first instance AttributeSource src = new AttributeSource(); CharTermAttribute termAtt = src.addAttribute(CharTermAttribute.class); TypeAttribute typeAtt = src.addAttribute(TypeAttribute.class); termAtt.append("TestTerm"); typeAtt.setType("TestType"); final int hashCode = src.hashCode(); AttributeSource.State state = src.captureState(); // modify the attributes termAtt.setEmpty().append("AnotherTestTerm"); typeAtt.setType("AnotherTestType"); assertTrue("Hash code should be different", hashCode != src.hashCode()); src.restoreState(state); assertEquals("TestTerm", termAtt.toString()); assertEquals("TestType", typeAtt.type()); assertEquals("Hash code should be equal after restore", hashCode, src.hashCode()); // restore into an exact configured copy AttributeSource copy = new AttributeSource(); copy.addAttribute(CharTermAttribute.class); copy.addAttribute(TypeAttribute.class); copy.restoreState(state); assertEquals("Both AttributeSources should have same hashCode after restore", src.hashCode(), copy.hashCode()); assertEquals("Both AttributeSources should be equal after restore", src, copy); // init a second instance (with attributes in different order and one additional attribute) AttributeSource src2 = new AttributeSource(); typeAtt = src2.addAttribute(TypeAttribute.class); FlagsAttribute flagsAtt = src2.addAttribute(FlagsAttribute.class); termAtt = src2.addAttribute(CharTermAttribute.class); flagsAtt.setFlags(12345); src2.restoreState(state); assertEquals("TestTerm", termAtt.toString()); assertEquals("TestType", typeAtt.type()); assertEquals("FlagsAttribute should not be touched", 12345, flagsAtt.getFlags()); // init a third instance missing one Attribute AttributeSource src3 = new AttributeSource(); termAtt = src3.addAttribute(CharTermAttribute.class); try { src3.restoreState(state); fail("The third instance is missing the TypeAttribute, so restoreState() should throw IllegalArgumentException"); } catch (IllegalArgumentException iae) { // pass } } public void testCloneAttributes() { final AttributeSource src = new AttributeSource(); final FlagsAttribute flagsAtt = src.addAttribute(FlagsAttribute.class); final TypeAttribute typeAtt = src.addAttribute(TypeAttribute.class); flagsAtt.setFlags(1234); typeAtt.setType("TestType"); final AttributeSource clone = src.cloneAttributes(); final Iterator<Class<? extends Attribute>> it = clone.getAttributeClassesIterator(); assertEquals("FlagsAttribute must be the first attribute", FlagsAttribute.class, it.next()); assertEquals("TypeAttribute must be the second attribute", TypeAttribute.class, it.next()); assertFalse("No more attributes", it.hasNext()); final FlagsAttribute flagsAtt2 = clone.getAttribute(FlagsAttribute.class); assertNotNull(flagsAtt2); final TypeAttribute typeAtt2 = clone.getAttribute(TypeAttribute.class); assertNotNull(typeAtt2); assertNotSame("FlagsAttribute of original and clone must be different instances", flagsAtt2, flagsAtt); assertNotSame("TypeAttribute of original and clone must be different instances", typeAtt2, typeAtt); assertEquals("FlagsAttribute of original and clone must be equal", flagsAtt2, flagsAtt); assertEquals("TypeAttribute of original and clone must be equal", typeAtt2, typeAtt); // test copy back flagsAtt2.setFlags(4711); typeAtt2.setType("OtherType"); clone.copyTo(src); assertEquals("FlagsAttribute of original must now contain updated term", 4711, flagsAtt.getFlags()); assertEquals("TypeAttribute of original must now contain updated type", "OtherType", typeAtt.type()); // verify again: assertNotSame("FlagsAttribute of original and clone must be different instances", flagsAtt2, flagsAtt); assertNotSame("TypeAttribute of original and clone must be different instances", typeAtt2, typeAtt); assertEquals("FlagsAttribute of original and clone must be equal", flagsAtt2, flagsAtt); assertEquals("TypeAttribute of original and clone must be equal", typeAtt2, typeAtt); } public void testDefaultAttributeFactory() throws Exception { AttributeSource src = new AttributeSource(); assertTrue("CharTermAttribute is not implemented by CharTermAttributeImpl", src.addAttribute(CharTermAttribute.class) instanceof CharTermAttributeImpl); assertTrue("OffsetAttribute is not implemented by OffsetAttributeImpl", src.addAttribute(OffsetAttribute.class) instanceof OffsetAttributeImpl); assertTrue("FlagsAttribute is not implemented by FlagsAttributeImpl", src.addAttribute(FlagsAttribute.class) instanceof FlagsAttributeImpl); assertTrue("PayloadAttribute is not implemented by PayloadAttributeImpl", src.addAttribute(PayloadAttribute.class) instanceof PayloadAttributeImpl); assertTrue("PositionIncrementAttribute is not implemented by PositionIncrementAttributeImpl", src.addAttribute(PositionIncrementAttribute.class) instanceof PositionIncrementAttributeImpl); assertTrue("TypeAttribute is not implemented by TypeAttributeImpl", src.addAttribute(TypeAttribute.class) instanceof TypeAttributeImpl); } @SuppressWarnings({"rawtypes","unchecked"}) public void testInvalidArguments() throws Exception { try { AttributeSource src = new AttributeSource(); src.addAttribute(Token.class); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException iae) {} try { AttributeSource src = new AttributeSource(Token.TOKEN_ATTRIBUTE_FACTORY); src.addAttribute(Token.class); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException iae) {} try { AttributeSource src = new AttributeSource(); // break this by unsafe cast src.addAttribute((Class) Iterator.class); fail("Should throw IllegalArgumentException"); } catch (IllegalArgumentException iae) {} } public void testLUCENE_3042() throws Exception { final AttributeSource src1 = new AttributeSource(); src1.addAttribute(CharTermAttribute.class).append("foo"); int hash1 = src1.hashCode(); // this triggers a cached state final AttributeSource src2 = new AttributeSource(src1); src2.addAttribute(TypeAttribute.class).setType("bar"); assertTrue("The hashCode is identical, so the captured state was preserved.", hash1 != src1.hashCode()); assertEquals(src2.hashCode(), src1.hashCode()); } public void testClonePayloadAttribute() throws Exception { // LUCENE-6055: verify that PayloadAttribute.clone() does deep cloning. PayloadAttributeImpl src = new PayloadAttributeImpl(new BytesRef(new byte[] { 1, 2, 3 })); // test clone() PayloadAttributeImpl clone = src.clone(); clone.getPayload().bytes[0] = 10; // modify one byte, srcBytes shouldn't change assertEquals("clone() wasn't deep", 1, src.getPayload().bytes[0]); // test copyTo() clone = new PayloadAttributeImpl(); src.copyTo(clone); clone.getPayload().bytes[0] = 10; // modify one byte, srcBytes shouldn't change assertEquals("clone() wasn't deep", 1, src.getPayload().bytes[0]); } @SuppressWarnings("unused") static final class OnlyReflectAttributeImpl extends AttributeImpl implements TypeAttribute { private String field1 = "foo"; private int field2 = 4711; private static int x = 0; public String field3 = "public"; @Override public String type() { return field1; } @Override public void setType(String type) { this.field1 = type; } @Override public void clear() {} @Override public void copyTo(AttributeImpl target) {} } public void testBackwardsCompatibilityReflector() throws Exception { TestUtil.assertAttributeReflection(new OnlyReflectAttributeImpl(), new HashMap<String, Object>() {{ put(TypeAttribute.class.getName() + "#field1", "foo"); put(TypeAttribute.class.getName() + "#field2", 4711); put(TypeAttribute.class.getName() + "#field3", "public"); }}); } }
{ "content_hash": "9d24faffc83ac974e4caea0dc600f6f3", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 119, "avg_line_length": 43.38383838383838, "alnum_prop": 0.7291036088474971, "repo_name": "yida-lxw/solr-5.3.1", "id": "05815915f34bd6d5eda1cf6998a6214becc134b1", "size": "9391", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lucene/core/src/test/org/apache/lucene/util/TestAttributeSource.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "291" }, { "name": "Batchfile", "bytes": "46111" }, { "name": "C++", "bytes": "26754" }, { "name": "CSS", "bytes": "231385" }, { "name": "GAP", "bytes": "22114" }, { "name": "Gnuplot", "bytes": "4888" }, { "name": "HTML", "bytes": "1793884" }, { "name": "Java", "bytes": "48093061" }, { "name": "JavaScript", "bytes": "1196315" }, { "name": "Lex", "bytes": "216688" }, { "name": "Perl", "bytes": "95225" }, { "name": "Python", "bytes": "310589" }, { "name": "Shell", "bytes": "157610" }, { "name": "XSLT", "bytes": "192968" } ], "symlink_target": "" }
from sympy import (S, sympify, trigsimp, expand, sqrt, Add, zeros, ImmutableMatrix as Matrix) from sympy.core.compatibility import u from sympy.utilities.misc import filldedent __all__ = ['Vector'] class Vector(object): """The class used to define vectors. It along with ReferenceFrame are the building blocks of describing a classical mechanics system in PyDy and sympy.physics.vector. Attributes ========== simp : Boolean Let certain methods use trigsimp on their outputs """ simp = False def __init__(self, inlist): """This is the constructor for the Vector class. You shouldn't be calling this, it should only be used by other functions. You should be treating Vectors like you would with if you were doing the math by hand, and getting the first 3 from the standard basis vectors from a ReferenceFrame. The only exception is to create a zero vector: zv = Vector(0) """ self.args = [] if inlist == 0: inlist = [] while len(inlist) != 0: added = 0 for i, v in enumerate(self.args): if inlist[0][1] == self.args[i][1]: self.args[i] = (self.args[i][0] + inlist[0][0], inlist[0][1]) inlist.remove(inlist[0]) added = 1 break if added != 1: self.args.append(inlist[0]) inlist.remove(inlist[0]) i = 0 # This code is to remove empty frames from the list while i < len(self.args): if self.args[i][0] == Matrix([0, 0, 0]): self.args.remove(self.args[i]) i -= 1 i += 1 def __hash__(self): return hash(tuple(self.args)) def __add__(self, other): """The add operator for Vector. """ other = _check_vector(other) return Vector(self.args + other.args) def __and__(self, other): """Dot product of two vectors. Returns a scalar, the dot product of the two Vectors Parameters ========== other : Vector The Vector which we are dotting with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, dot >>> from sympy import symbols >>> q1 = symbols('q1') >>> N = ReferenceFrame('N') >>> dot(N.x, N.x) 1 >>> dot(N.x, N.y) 0 >>> A = N.orientnew('A', 'Axis', [q1, N.x]) >>> dot(N.y, A.y) cos(q1) """ from sympy.physics.vector.dyadic import Dyadic if isinstance(other, Dyadic): return NotImplemented other = _check_vector(other) out = S(0) for i, v1 in enumerate(self.args): for j, v2 in enumerate(other.args): out += ((v2[0].T) * (v2[1].dcm(v1[1])) * (v1[0]))[0] if Vector.simp: return trigsimp(sympify(out), recursive=True) else: return sympify(out) def __div__(self, other): """This uses mul and inputs self and 1 divided by other. """ return self.__mul__(sympify(1) / other) __truediv__ = __div__ def __eq__(self, other): """Tests for equality. It is very import to note that this is only as good as the SymPy equality test; False does not always mean they are not equivalent Vectors. If other is 0, and self is empty, returns True. If other is 0 and self is not empty, returns False. If none of the above, only accepts other as a Vector. """ if other == 0: other = Vector(0) other = _check_vector(other) if (self.args == []) and (other.args == []): return True elif (self.args == []) or (other.args == []): return False frame = self.args[0][1] for v in frame: if expand((self - other) & v) != 0: return False return True def __mul__(self, other): """Multiplies the Vector by a sympifyable expression. Parameters ========== other : Sympifyable The scalar to multiply this Vector with Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy import Symbol >>> N = ReferenceFrame('N') >>> b = Symbol('b') >>> V = 10 * b * N.x >>> print(V) 10*b*N.x """ newlist = [v for v in self.args] for i, v in enumerate(newlist): newlist[i] = (sympify(other) * newlist[i][0], newlist[i][1]) return Vector(newlist) def __ne__(self, other): return not self.__eq__(other) def __neg__(self): return self * -1 def __or__(self, other): """Outer product between two Vectors. A rank increasing operation, which returns a Dyadic from two Vectors Parameters ========== other : Vector The Vector to take the outer product with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer >>> N = ReferenceFrame('N') >>> outer(N.x, N.x) (N.x|N.x) """ from sympy.physics.vector.dyadic import Dyadic other = _check_vector(other) ol = Dyadic(0) for i, v in enumerate(self.args): for i2, v2 in enumerate(other.args): # it looks this way because if we are in the same frame and # use the enumerate function on the same frame in a nested # fashion, then bad things happen ol += Dyadic([(v[0][0] * v2[0][0], v[1].x, v2[1].x)]) ol += Dyadic([(v[0][0] * v2[0][1], v[1].x, v2[1].y)]) ol += Dyadic([(v[0][0] * v2[0][2], v[1].x, v2[1].z)]) ol += Dyadic([(v[0][1] * v2[0][0], v[1].y, v2[1].x)]) ol += Dyadic([(v[0][1] * v2[0][1], v[1].y, v2[1].y)]) ol += Dyadic([(v[0][1] * v2[0][2], v[1].y, v2[1].z)]) ol += Dyadic([(v[0][2] * v2[0][0], v[1].z, v2[1].x)]) ol += Dyadic([(v[0][2] * v2[0][1], v[1].z, v2[1].y)]) ol += Dyadic([(v[0][2] * v2[0][2], v[1].z, v2[1].z)]) return ol def _latex(self, printer=None): """Latex Printing method. """ from sympy.physics.vector.printing import VectorLatexPrinter ar = self.args # just to shorten things if len(ar) == 0: return str(0) ol = [] # output list, to be concatenated to a string for i, v in enumerate(ar): for j in 0, 1, 2: # if the coef of the basis vector is 1, we skip the 1 if ar[i][0][j] == 1: ol.append(' + ' + ar[i][1].latex_vecs[j]) # if the coef of the basis vector is -1, we skip the 1 elif ar[i][0][j] == -1: ol.append(' - ' + ar[i][1].latex_vecs[j]) elif ar[i][0][j] != 0: # If the coefficient of the basis vector is not 1 or -1; # also, we might wrap it in parentheses, for readability. arg_str = VectorLatexPrinter().doprint(ar[i][0][j]) if isinstance(ar[i][0][j], Add): arg_str = "(%s)" % arg_str if arg_str[0] == '-': arg_str = arg_str[1:] str_start = ' - ' else: str_start = ' + ' ol.append(str_start + arg_str + ar[i][1].latex_vecs[j]) outstr = ''.join(ol) if outstr.startswith(' + '): outstr = outstr[3:] elif outstr.startswith(' '): outstr = outstr[1:] return outstr def _pretty(self, printer=None): """Pretty Printing method. """ from sympy.physics.vector.printing import VectorPrettyPrinter e = self class Fake(object): baseline = 0 def render(self, *args, **kwargs): self = e ar = self.args # just to shorten things if len(ar) == 0: return unicode(0) ol = [] # output list, to be concatenated to a string for i, v in enumerate(ar): for j in 0, 1, 2: # if the coef of the basis vector is 1, we skip the 1 if ar[i][0][j] == 1: ol.append(u(" + ") + ar[i][1].pretty_vecs[j]) # if the coef of the basis vector is -1, we skip the 1 elif ar[i][0][j] == -1: ol.append(u(" - ") + ar[i][1].pretty_vecs[j]) elif ar[i][0][j] != 0: # If the basis vector coeff is not 1 or -1, # we might wrap it in parentheses, for readability. if isinstance(ar[i][0][j], Add): arg_str = VectorPrettyPrinter()._print( ar[i][0][j]).parens()[0] else: arg_str = (VectorPrettyPrinter().doprint( ar[i][0][j])) if arg_str[0] == u("-"): arg_str = arg_str[1:] str_start = u(" - ") else: str_start = u(" + ") ol.append(str_start + arg_str + ' ' + ar[i][1].pretty_vecs[j]) outstr = u("").join(ol) if outstr.startswith(u(" + ")): outstr = outstr[3:] elif outstr.startswith(" "): outstr = outstr[1:] return outstr return Fake() def __ror__(self, other): """Outer product between two Vectors. A rank increasing operation, which returns a Dyadic from two Vectors Parameters ========== other : Vector The Vector to take the outer product with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, outer >>> N = ReferenceFrame('N') >>> outer(N.x, N.x) (N.x|N.x) """ from sympy.physics.vector.dyadic import Dyadic other = _check_vector(other) ol = Dyadic(0) for i, v in enumerate(other.args): for i2, v2 in enumerate(self.args): # it looks this way because if we are in the same frame and # use the enumerate function on the same frame in a nested # fashion, then bad things happen ol += Dyadic([(v[0][0] * v2[0][0], v[1].x, v2[1].x)]) ol += Dyadic([(v[0][0] * v2[0][1], v[1].x, v2[1].y)]) ol += Dyadic([(v[0][0] * v2[0][2], v[1].x, v2[1].z)]) ol += Dyadic([(v[0][1] * v2[0][0], v[1].y, v2[1].x)]) ol += Dyadic([(v[0][1] * v2[0][1], v[1].y, v2[1].y)]) ol += Dyadic([(v[0][1] * v2[0][2], v[1].y, v2[1].z)]) ol += Dyadic([(v[0][2] * v2[0][0], v[1].z, v2[1].x)]) ol += Dyadic([(v[0][2] * v2[0][1], v[1].z, v2[1].y)]) ol += Dyadic([(v[0][2] * v2[0][2], v[1].z, v2[1].z)]) return ol def __rsub__(self, other): return (-1 * self) + other def __str__(self, printer=None): """Printing method. """ from sympy.physics.vector.printing import VectorStrPrinter ar = self.args # just to shorten things if len(ar) == 0: return str(0) ol = [] # output list, to be concatenated to a string for i, v in enumerate(ar): for j in 0, 1, 2: # if the coef of the basis vector is 1, we skip the 1 if ar[i][0][j] == 1: ol.append(' + ' + ar[i][1].str_vecs[j]) # if the coef of the basis vector is -1, we skip the 1 elif ar[i][0][j] == -1: ol.append(' - ' + ar[i][1].str_vecs[j]) elif ar[i][0][j] != 0: # If the coefficient of the basis vector is not 1 or -1; # also, we might wrap it in parentheses, for readability. arg_str = VectorStrPrinter().doprint(ar[i][0][j]) if isinstance(ar[i][0][j], Add): arg_str = "(%s)" % arg_str if arg_str[0] == '-': arg_str = arg_str[1:] str_start = ' - ' else: str_start = ' + ' ol.append(str_start + arg_str + '*' + ar[i][1].str_vecs[j]) outstr = ''.join(ol) if outstr.startswith(' + '): outstr = outstr[3:] elif outstr.startswith(' '): outstr = outstr[1:] return outstr def __sub__(self, other): """The subraction operator. """ return self.__add__(other * -1) def __xor__(self, other): """The cross product operator for two Vectors. Returns a Vector, expressed in the same ReferenceFrames as self. Parameters ========== other : Vector The Vector which we are crossing with Examples ======== >>> from sympy.physics.vector import ReferenceFrame, Vector >>> from sympy import symbols >>> q1 = symbols('q1') >>> N = ReferenceFrame('N') >>> N.x ^ N.y N.z >>> A = N.orientnew('A', 'Axis', [q1, N.x]) >>> A.x ^ N.y N.z >>> N.y ^ A.x - sin(q1)*A.y - cos(q1)*A.z """ from sympy.physics.vector.dyadic import Dyadic if isinstance(other, Dyadic): return NotImplemented other = _check_vector(other) if other.args == []: return Vector(0) def _det(mat): """This is needed as a little method for to find the determinant of a list in python; needs to work for a 3x3 list. SymPy's Matrix won't take in Vector, so need a custom function. You shouldn't be calling this. """ return (mat[0][0] * (mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1]) + mat[0][1] * (mat[1][2] * mat[2][0] - mat[1][0] * mat[2][2]) + mat[0][2] * (mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0])) outvec = Vector(0) ar = other.args # For brevity for i, v in enumerate(ar): tempx = v[1].x tempy = v[1].y tempz = v[1].z tempm = ([[tempx, tempy, tempz], [self & tempx, self & tempy, self & tempz], [Vector([ar[i]]) & tempx, Vector([ar[i]]) & tempy, Vector([ar[i]]) & tempz]]) outvec += _det(tempm) return outvec _sympystr = __str__ _sympyrepr = _sympystr __repr__ = __str__ __radd__ = __add__ __rand__ = __and__ __rmul__ = __mul__ def separate(self): """ The constituents of this vector in different reference frames, as per its definition. Returns a dict mapping each ReferenceFrame to the corresponding constituent Vector. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> R1 = ReferenceFrame('R1') >>> R2 = ReferenceFrame('R2') >>> v = R1.x + R2.x >>> v.separate() == {R1: R1.x, R2: R2.x} True """ components = {} for x in self.args: components[x[1]] = Vector([x]) return components def dot(self, other): return self & other dot.__doc__ = __and__.__doc__ def cross(self, other): return self ^ other cross.__doc__ = __xor__.__doc__ def outer(self, other): return self | other outer.__doc__ = __or__.__doc__ def diff(self, wrt, otherframe): """Takes the partial derivative, with respect to a value, in a frame. Returns a Vector. Parameters ========== wrt : Symbol What the partial derivative is taken with respect to. otherframe : ReferenceFrame The ReferenceFrame that the partial derivative is taken in. Examples ======== >>> from sympy.physics.vector import ReferenceFrame, Vector, dynamicsymbols >>> from sympy import Symbol >>> Vector.simp = True >>> t = Symbol('t') >>> q1 = dynamicsymbols('q1') >>> N = ReferenceFrame('N') >>> A = N.orientnew('A', 'Axis', [q1, N.y]) >>> A.x.diff(t, N) - q1'*A.z """ from sympy.physics.vector.frame import _check_frame wrt = sympify(wrt) _check_frame(otherframe) outvec = Vector(0) for i, v in enumerate(self.args): if v[1] == otherframe: outvec += Vector([(v[0].diff(wrt), otherframe)]) else: if otherframe.dcm(v[1]).diff(wrt) == zeros(3, 3): d = v[0].diff(wrt) outvec += Vector([(d, v[1])]) else: d = (Vector([v]).express(otherframe)).args[0][0].diff(wrt) outvec += Vector([(d, otherframe)]).express(v[1]) return outvec def express(self, otherframe, variables=False): """ Returns a Vector equivalent to this one, expressed in otherframe. Uses the global express method. Parameters ========== otherframe : ReferenceFrame The frame for this Vector to be described in variables : boolean If True, the coordinate symbols(if present) in this Vector are re-expressed in terms otherframe Examples ======== >>> from sympy.physics.vector import ReferenceFrame, Vector, dynamicsymbols >>> q1 = dynamicsymbols('q1') >>> N = ReferenceFrame('N') >>> A = N.orientnew('A', 'Axis', [q1, N.y]) >>> A.x.express(N) cos(q1)*N.x - sin(q1)*N.z """ from sympy.physics.vector import express return express(self, otherframe, variables=variables) def to_matrix(self, reference_frame): """Returns the matrix form of the vector with respect to the given frame. Parameters ---------- reference_frame : ReferenceFrame The reference frame that the rows of the matrix correspond to. Returns ------- matrix : ImmutableMatrix, shape(3,1) The matrix that gives the 1D vector. Examples -------- >>> from sympy import symbols >>> from sympy.physics.vector import ReferenceFrame >>> from sympy.physics.mechanics.functions import inertia >>> a, b, c = symbols('a, b, c') >>> N = ReferenceFrame('N') >>> vector = a * N.x + b * N.y + c * N.z >>> vector.to_matrix(N) Matrix([ [a], [b], [c]]) >>> beta = symbols('beta') >>> A = N.orientnew('A', 'Axis', (beta, N.x)) >>> vector.to_matrix(A) Matrix([ [ a], [ b*cos(beta) + c*sin(beta)], [-b*sin(beta) + c*cos(beta)]]) """ return Matrix([self.dot(unit_vec) for unit_vec in reference_frame]).reshape(3, 1) def doit(self, **hints): """Calls .doit() on each term in the Vector""" ov = Vector(0) for i, v in enumerate(self.args): ov += Vector([(v[0].applyfunc(lambda x: x.doit(**hints)), v[1])]) return ov def dt(self, otherframe): """ Returns a Vector which is the time derivative of the self Vector, taken in frame otherframe. Calls the global time_derivative method Parameters ========== otherframe : ReferenceFrame The frame to calculate the time derivative in """ from sympy.physics.vector import time_derivative return time_derivative(self, otherframe) def simplify(self): """Returns a simplified Vector.""" outvec = Vector(0) for i in self.args: outvec += Vector([(i[0].simplify(), i[1])]) return outvec def subs(self, *args, **kwargs): """Substituion on the Vector. Examples ======== >>> from sympy.physics.vector import ReferenceFrame >>> from sympy import Symbol >>> N = ReferenceFrame('N') >>> s = Symbol('s') >>> a = N.x * s >>> a.subs({s: 2}) 2*N.x """ ov = Vector(0) for i, v in enumerate(self.args): ov += Vector([(v[0].subs(*args, **kwargs), v[1])]) return ov def magnitude(self): """Returns the magnitude (Euclidean norm) of self.""" return sqrt(self & self) def normalize(self): """Returns a Vector of magnitude 1, codirectional with self.""" return Vector(self.args + []) / self.magnitude() class VectorTypeError(TypeError): def __init__(self, other, want): msg = filldedent("Expected an instance of %s, but received object " "'%s' of %s." % (type(want), other, type(other))) super(VectorTypeError, self).__init__(msg) def _check_vector(other): if not isinstance(other, Vector): raise TypeError('A Vector must be supplied') return other
{ "content_hash": "7f2e541a62c67762b12690fedb3c3cb3", "timestamp": "", "source": "github", "line_count": 670, "max_line_length": 83, "avg_line_length": 32.88059701492537, "alnum_prop": 0.47385383567862005, "repo_name": "dqnykamp/sympy", "id": "25d51717e01f7b13c33fd75a5e1a569907416c32", "size": "22030", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "sympy/physics/vector/vector.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "15195033" }, { "name": "Ruby", "bytes": "304" }, { "name": "Scheme", "bytes": "125" }, { "name": "Shell", "bytes": "4018" }, { "name": "TeX", "bytes": "32356" }, { "name": "XSLT", "bytes": "366202" } ], "symlink_target": "" }
--- title: Promise category: Web, JavaScript, ES6 --- ## Legacy: Utiliser des callbacks Si on veut créer une fonction asynchrone, avec ES5, on utiliserait `setTimeout`. Si cette fonction doit retourner une valeur, ou effectuer une action lorsqu'elle est terminée, alors il est nécessaire de passer un callback en paramètre. Et si on a beaucoup de fonctions asynchrones dans le code, alors le code devient très vite illisible (*callback hell*). Par exemple, pour exécuter B une fois qu'A a fini, C une fois que B a fini, etc: ``` js function doA(callback) { console.log("A does something"); callback && callback(); } function doB(callback) { console.log("B does something"); callback && callback(); } function doC(callback) { console.log("C does something"); callback && callback(); } function doD(callback) { console.log("D does something"); callback && callback(); } doA(doB.bind(null, doC.bind(null, doD))); ``` ## Utiliser des promesses Pour régler ce problème, ES6 introduit les promesses (*promise* en anglais). Une promesse permet de créer une fonction asynchrone, et d'utiliser le chaînage pour exécuter des callbacks plutôt que de les prendre en paramètre. ``` js function doA() { return new Promise((resolve) => { console.log("A does something", Date.now()); resolve(); }); } function doB() { return new Promise((resolve) => { console.log("B does something", Date.now()); resolve(); }); } function doC() { return new Promise((resolve) => { console.log("C does something", Date.now()); resolve(); }); } function doD() { return new Promise((resolve) => { console.log("D does something", Date.now()); resolve(); }); } console.log("Start", Date.now()); doA().then(() => doB()) .then(() => doC()) .then(() => doD()) .then(() => { console.log("All promises ended", Date.now()); }); /* Start 1558015603802 A does something 1558015603803 B does something 1558015603804 C does something 1558015603804 D does something 1558015603804 All promises ended 1558015603805 */ ``` <ins>Exemple</ins>: ``` js function logFetch(url) { return fetch(url) .then(response => response.text()) .then(text => { console.log(text); }).catch(err => { console.error('fetch failed', err); }); } ``` ``` js async function loadScript(url){ return new Promise((resolve, reject) => { var script = document.createElement("script"); script.type = "text/javascript"; if(script.readyState){ //IE script.onreadystatechange = function(){ if (script.readyState == "loaded" || script.readyState == "complete"){ script.onreadystatechange = null; resolve(); } }; } else { // Others script.onload = resolve; } script.src = url; document.getElementsByTagName("head")[0].appendChild(script); }); }; loadScript("react-chartjs.js") .then(() => { console.log(window['react-chartjs']); }); ``` --- ## Concurrence Une promesse est exécutée dès qu'elle est instanciée, on peut s'en servir pour exécuter plusieurs processus en concurrence. ``` js var doA = new Promise((resolve) => { console.log("A does something", Date.now()); resolve(); }); var doB = new Promise((resolve) => { console.log("B does something", Date.now()); resolve(); }); var doC = new Promise((resolve) => { console.log("C does something", Date.now()); resolve(); }); var doD = new Promise((resolve) => { console.log("D does something", Date.now()); resolve(); }); console.log("Start", Date.now()); doA.then(() => doB) .then(() => doC) .then(() => doD) .then(() => { console.log("All promises ended", Date.now()) }); /* A does something 1558015640463 B does something 1558015640463 C does something 1558015640463 D does something 1558015640463 Start 1558015640464 All promises ended 1558015640466 */ ``` --- ## Gérer les erreurs: catch Chaque promesse reçoit deux fonctions en argument: * la première, a appeler pour retourner un résultat — par convention, on l'appelle `resolve` * la deuxième, a appeler pour retourner une erreur — par convention, on l'appelle `reject` ``` js var doA = new Promise((resolve, reject) => { var result = Math.random(); if(result > 0.5) { resolve(result); } else { reject('Your score is too damn low'); } }); ```` Lorsque l'une ou l'autre est appelée, le moteur JavaScript s'occupe de transmettre le résultat à la fonction qui attend la résolution de la promesse. * On peut soit utiliser `.then(result, error)` ``` js doA.then(result => { console.log('Result is: ' + result); }, error => { console.log('Error: ' + error); }); ``` * Soit `.then(result).catch(error)` ``` js doA.then(result => { console.log('Result is: ' + result); }).catch(error => { console.log('Error: ' + error); }); ``` --- ## Type d'une variable Pour savoir si une variable est une promesse, on peut utiliser le test suivant: ``` js const isPromise = obj => Boolean(obj) && typeof obj.then === 'function'; ``` --- ## async `async` permet de déclarer une fonction asyncrhone [ES8]. Ces fonctions ne bloquent pas le processus et retournent automatiquement une promesse. Une fois que la fonction arrive au `return`, la promesse est réalisée — comme si on appelait `resolve`. ``` async function doA() { console.log("A does something", Date.now()); } async function doB() { console.log("B does something", Date.now()); } async function doC() { console.log("C does something", Date.now()); } async function doD() { console.log("D does something", Date.now()); } console.log("Start", Date.now()); doA().then(() => doB()) .then(() => doC()) .then(() => doD()) .then(() => { console.log("All promises ended", Date.now()); }); /* Start 1558015694403 A does something 1558015694404 B does something 1558015694404 C does something 1558015694405 D does something 1558015694405 All promises ended 1558015694406 */ ``` --- ## await `await` permet d’attendre la résolution d’une promesse [ES8]. Ce mot-clé n’est valide qu'à l’intérieur d’une fonction `async`. ``` js let obj = { async method() { let value = await fetch('/'); } }; ``` ``` js class MyClass { async myMethod() { let value = await fetch('/'); } } ``` ### Concurrence Pour exécuter la promesse A après la promesse B: ``` js (async function(){ var a = await doA(), b = await doB(); console.log('Results: ', a, b); })(); ``` Pour exécuter les promesses en même tempos: ``` js (async function(){ var promiseA = doA(), promiseB = doB(); var a = await promiseA, b = await promiseB; console.log('Results: ', a, b); })(); ``` ### Catch Avec un `await`, les erreurs levées par une promesse peuvent être récupérées avec * un bloc `try... catch` ``` js try { let x = await myAsyncFunction(); } catch(e) { console.error(e); } ``` * ou avec `catch()` ``` js let x = await myAsyncFunction().catch(e => console.error(e)); ``` --- ## ES8 ### Promise.all() `Promise.all` permet d'executer plusieurs promesses en parallèle (de manière concurrente) et de n'executer le callback qu'une fois toutes les promesses réalisées. ``` js async function getAB(a, b) { [a, b] = await Promise.all([getA(a), getB(b)]); return a + b; } ``` ### Promise.race() `Promise.race` permet d'executer plusieurs promesses en parallèle (de manière concurrente) et d'executer le callback une fois qu'une des promesses est réalisée, avec le résultat de la première promesse résolue. ``` js const first = new Promise((resolve, reject) => { setTimeout(resolve, 500, 'first'); }) const second = new Promise((resolve, reject) => { setTimeout(resolve, 100, 'second'); }) Promise.race([first, second]).then((result) => { console.log(result); // second }); ``` --- ## ES9 ### finally Sur le même principe que le `finally` d'un bloc `try... catch`, `finally` est executé à la fin — quel que soit le résultat de la requête (erreur ou non) [ES2018] ``` js var myPromise = new Promise(function(resolve, reject){ resolve('all good'); }); myPromise.then(val => { console.log(val); }).catch(val => { console.error(val); }).finally(() => { stopLoader(); }); ``` ### for await... of La boucle `for await` permet de boucler sur une liste de promesses [ES2018]. Chaque itération est appelée une fois que l'itération précédente est terminée. ``` js var promises = [ new Promise(resolve => resolve(1)), new Promise(resolve => resolve(2)), new Promise(resolve => resolve(3)) ]; async function test() { for await(var res of promises) { console.log(res); // 1 2 3 } } test(); ```
{ "content_hash": "e1b56bac218771b377e7dc9528f5ce3c", "timestamp": "", "source": "github", "line_count": 402, "max_line_length": 355, "avg_line_length": 21.776119402985074, "alnum_prop": 0.6399360292437742, "repo_name": "a-mt/dev-roadmap", "id": "4f04a43988dfb50970dc27551c624139ab0c03e5", "size": "8837", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/!js/js-promise.md", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "259" }, { "name": "Ruby", "bytes": "71" } ], "symlink_target": "" }
package com.mood.jenaPlus; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * Fragment for mood events of the people you are following * This fragment will only show the most recent mood from the participants you are following, * provided that they have a mood. * * @author Carlo * @author Carrol * @version 1.0 */ public class FollowingViewActivity extends Fragment implements MPView<MoodPlus>{ protected ListView moodListView; ArrayList<Mood> moodArrayList = new ArrayList<Mood>(); private ArrayAdapter<Mood> adapter; protected MainMPController mpController; Context context; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { context = container.getContext(); return inflater.inflate(R.layout.activity_follower_view,container,false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); moodListView = (ListView) getView().findViewById(R.id.listView); moodListView.setAdapter(adapter); moodListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getActivity(), ViewMoodActivity.class); intent.putExtra("aMood", (Serializable) moodListView.getItemAtPosition(position)); intent.putExtra("pos", position); startActivity(intent); } }); } @Override public void onStart() { super.onStart(); moodArrayList.clear(); ElasticsearchMPController eController = MoodPlusApplication.getElasticsearchMPController(); mpController = MoodPlusApplication.getMainMPController(); Participant participant = mpController.getParticipant(); ArrayList<String> participantListStr = participant.getFollowingList(); for (int i = 0; i<participantListStr.size(); i++) { Participant tempParticipant = eController.getUsingParticipant(participantListStr.get(i)); ArrayList<Mood> partMoods = tempParticipant.getUserMoodList().getUserMoodList(); getUserMoodOrderedList2(partMoods); if(partMoods.size() >0){ moodArrayList.add(partMoods.get(0)); } } adapter = new MoodFollowerListAdapter(getActivity(),moodArrayList); getUserMoodOrderedList(); moodListView.setAdapter(adapter); } public void noMoods() { new AlertDialog.Builder(context) .setTitle("No Moods") .setMessage("All of your followers do not have any available moods.") .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } public ArrayList<Mood> getUserMoodOrderedList() { Collections.sort(moodArrayList, new Comparator<Mood>() { public int compare(Mood o1, Mood o2) { return o2.getDate().compareTo(o1.getDate()); } }); return this.moodArrayList; } @Override public void update(MoodPlus moodPlus) { } public ArrayList<Mood> getUserMoodOrderedList2(ArrayList<Mood> array) { Collections.sort(array, new Comparator<Mood>() { public int compare(Mood o1, Mood o2) { return o2.getDate().compareTo(o1.getDate()); } }); return array; } }
{ "content_hash": "0f96c07d8fc98cfdd0666a7966be533a", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 103, "avg_line_length": 32.443609022556394, "alnum_prop": 0.6665121668597914, "repo_name": "CMPUT301W17T02/JenaPlus", "id": "3846813fcf2a4f9188ae9ec00c12502b30676c02", "size": "4315", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Mood+/app/src/main/java/com/mood/jenaPlus/FollowingViewActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12842" }, { "name": "HTML", "bytes": "6376563" }, { "name": "Java", "bytes": "317316" }, { "name": "JavaScript", "bytes": "827" } ], "symlink_target": "" }
@implementation UIImage (XCYCoreAdditions) + (UIImage*)imageFromMainBundleFile_xcy:(NSString*)aFileName { NSString* bundlePath = [[NSBundle mainBundle] bundlePath]; return [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", bundlePath,aFileName]]; } + (UIImage *)imageFromBundle:(NSString *)aBundle fileName_xcy:(NSString *)aFileName { NSArray *tempArray = [aFileName componentsSeparatedByString:@"."]; //如果文件不包含后缀,返回空 if (tempArray.count != 2) { return nil; } NSString *name = [tempArray objectAtIndex_xcy:0]; NSString *suffix = [tempArray objectAtIndex_xcy:1]; //获取图片时不能直接使用包含@x的图片名称 if ([name hasSuffix:@"@x"]) { return nil; } //当前屏幕倍数 NSInteger currentScale = (NSInteger)[[UIScreen mainScreen] scale]; //获取当前分辨率的图片 UIImage *image = [self p_getImageFromBundle:aBundle name:name suffix:suffix scale_xcy:currentScale]; if (image) { return image; } //如果当前分辨率图片不存在,则查找其它分辨率图片,从高分辨率开始查找 for (NSInteger tempScale = 3;tempScale >= 1;tempScale--) { if (tempScale == currentScale) { continue; } //获取当前分辨率的图片 UIImage *image = [self p_getImageFromBundle:aBundle name:name suffix:suffix scale_xcy:tempScale]; if (image) { return image; } } return nil; } + (UIImage *)imageFromImage:(UIImage *)image inRect_xcy:(CGRect)rect { CGImageRef sourceImageRef = [image CGImage]; CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect); UIImage *newImage = [UIImage imageWithCGImage:newImageRef]; CGImageRelease(newImageRef); return newImage; } #pragma mark - Private Method + (NSString *)p_getFileName:(NSString *)aFile suffix:(NSString *)aSuffix scale_xcy:(NSInteger)aScale { NSString *result = @""; switch (aScale) { case 2: case 3: { result = [NSString stringWithFormat:@"%@@%ldx.%@",aFile,(long)aScale,aSuffix]; break; } default: result = [NSString stringWithFormat:@"%@.%@",aFile,aSuffix]; break; } return result; } + (UIImage *)p_getImageFromBundle:(NSString *)aBundleName imageFullName_xcy:(NSString *)aImageFullName { NSString *mainBundlePath = [[NSBundle mainBundle] bundlePath]; NSString *customBundlePath = [mainBundlePath stringByAppendingPathComponent:aBundleName]; NSString *filePath = [customBundlePath stringByAppendingPathComponent:aImageFullName]; UIImage *image = [UIImage imageWithContentsOfFile:filePath]; return image; } + (UIImage *)p_getImageFromBundle:(NSString *)aBundleName name:(NSString *)aName suffix:(NSString *)aSuffix scale_xcy:(NSInteger)aScale { //获取当前分辨率的图片 NSString *fileFullName = [self p_getFileName:aName suffix:aSuffix scale_xcy:aScale]; UIImage *image = [self p_getImageFromBundle:aBundleName imageFullName_xcy:fileFullName]; return image; } @end
{ "content_hash": "4657ab90fab0dc43e0e336a6d8812411", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 104, "avg_line_length": 30.963636363636365, "alnum_prop": 0.5880798590722255, "repo_name": "huahuali/haha", "id": "a953f3475d315a661289456a91d9578f7369ba56", "size": "3811", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XCYBlueBox/XCYBlueBox/XCYUniversalClass/Models/UIKitAdditions/UIImage+XCYCoreAdditions.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2526" }, { "name": "Objective-C", "bytes": "456335" } ], "symlink_target": "" }
// ./lib/index.js var fs = require("fs"); var jetpack = require("fs-jetpack"); var user_home = require('user-home'); var Composer = require("./composer.js"); var global_path = user_home + "/AppData/Roaming/npm/node_modules/mongoplus" /** * Displays a string in the console * * @param {string_to_say} String string to show in the console */ var config = { bd : { root:".", pathToTemplate: global_path + "/lib/templates/RestApi/bd", inputTemplateFile:"", outputTemplateFile:"", outputFile: global_path + "/lib/templates/RestApi/bd/out", templateExtension:"" }, controllers : { root:".", pathToTemplate: global_path + "/lib/templates/RestApi/controllers", inputTemplateFile:"", outputTemplateFile:"", outputFile: global_path + "/lib/templates/RestApi/controllers/out", templateExtension:"" }, models : { root:".", pathToTemplate: global_path + "/lib/templates/RestApi/models", inputTemplateFile:"", outputTemplateFile:"", outputFile: global_path + "/lib/templates/RestApi/models/out", templateExtension:"" }, routerIndex : { root:".", pathToTemplate: global_path + "/lib/templates/RestApi/router/index", inputTemplateFile:"", outputTemplateFile:"", outputFile: global_path + "/lib/templates/RestApi/router/index/out", templateExtension:"" }, routerRoutes : { root:".", pathToTemplate: global_path + "/lib/templates/RestApi/router/routes", inputTemplateFile:"", outputTemplateFile:"", outputFile: global_path + "/lib/templates/RestApi/router/routes/out", templateExtension:"" }, tests : { root:".", pathToTemplate: global_path + "/lib/templates/RestApi/tests", inputTemplateFile:"", outputTemplateFile:"", outputFile: global_path + "/lib/templates/RestApi/tests/out", templateExtension:"" } }; var RestApiConfig = { project : "newRestApiProject", bd : { pathToTemplate : config.bd.pathToTemplate || ".", inputTemplate : config.bd.inputTemplateFile || "input.tpl", outputTemplate : config.bd.outputTemplateFile || "output.tpl", templateExtension : config.bd.templateExtension || ".tpl", output : config.bd.outputFile || "test.html", pathToGenerated : "/app/config/" }, controllers : { pathToTemplate : config.controllers.pathToTemplate || ".", inputTemplate : config.controllers.inputTemplateFile || "input.tpl", outputTemplate : config.controllers.outputTemplateFile || "output.tpl", templateExtension : config.controllers.templateExtension || ".tpl", output : config.controllers.outputFile || "test.html", pathToGenerated : "/app/controllers/" }, models : { pathToTemplate : config.models.pathToTemplate || ".", inputTemplate : config.models.inputTemplateFile || "input.tpl", outputTemplate : config.models.outputTemplateFile || "output.tpl", templateExtension : config.models.templateExtension || ".tpl", output : config.models.outputFile || "test.html", pathToGenerated : "/app/models/" }, routerIndex : { pathToTemplate : config.routerIndex.pathToTemplate || ".", inputTemplate : config.routerIndex.inputTemplateFile || "input.tpl", outputTemplate : config.routerIndex.outputTemplateFile || "output.tpl", templateExtension : config.routerIndex.templateExtension || ".tpl", output : config.routerIndex.outputFile || "test.html", pathToGenerated : "/app/router/" }, routerRoutes : { pathToTemplate : config.routerRoutes.pathToTemplate || ".", inputTemplate : config.routerRoutes.inputTemplateFile || "input.tpl", outputTemplate : config.routerRoutes.outputTemplateFile || "output.tpl", templateExtension : config.routerRoutes.templateExtension || ".tpl", output : config.routerRoutes.outputFile || "test.html", pathToGenerated : "/app/router/routes/" }, tests : { pathToTemplate : config.tests.pathToTemplate || ".", inputTemplate : config.tests.inputTemplateFile || "input.tpl", outputTemplate : config.tests.outputTemplateFile || "output.tpl", templateExtension : config.tests.templateExtension || ".tpl", output : config.tests.outputFile || "test.html", pathToGenerated : "/tests/" } }; // clone project structure to the current directory function cloneProjectStructure(structure , dest){ console.log(global_path); jetpack.copy(global_path + '/lib/project-structure/RestApi/',"./" + dest,{overwrite : true}); } // copy files to a specific directory function copyFileToProject(src,dest){ console.log("*********** : " + dest); jetpack.copy(src, dest , {overwrite : true}); } /* options = { bd : { host : "localhost", dbName : "MeanTest", models : [ { name : "Bear", path : "../models/BearModel" } ] }, models : [ { name : 'Bear', path : '../models/BearModel', fields : [ { name : 'name', type : 'String' } ] } ] }; */ function build_bd(options){ Composer.setConfig({ pathToTemplate : RestApiConfig.bd.pathToTemplate, outputFile : RestApiConfig.bd.output }); Composer.build( RestApiConfig.bd.pathToTemplate + "/" + RestApiConfig.bd.inputTemplate, RestApiConfig.bd.output + '/' + "db.js",options); var dest = "./" + options.name + RestApiConfig.bd.pathToGenerated ; copyFileToProject(RestApiConfig.bd.output,dest); } function build_models(options){ Composer.setConfig({ pathToTemplate : RestApiConfig.models.pathToTemplate, outputFile : RestApiConfig.models.output }); for(index in options.models){ Composer.build( RestApiConfig.models.pathToTemplate + "/" + RestApiConfig.models.inputTemplate, RestApiConfig.models.output + '/' + options.models[index].name + "Model.js",options.models[index]); var dest = "./" + options.name + RestApiConfig.models.pathToGenerated ; copyFileToProject(RestApiConfig.models.output,dest); } } function build_controllers(options){ Composer.setConfig({ pathToTemplate : RestApiConfig.controllers.pathToTemplate, outputFile : RestApiConfig.controllers.output }); for(index in options.models){ Composer.build( RestApiConfig.controllers.pathToTemplate + "/" + RestApiConfig.controllers.inputTemplate, RestApiConfig.controllers.output + '/' + options.models[index].name + "Controller.js",options.models[index]); var dest = "./" + options.name + RestApiConfig.controllers.pathToGenerated ; copyFileToProject(RestApiConfig.controllers.output,dest); } } function build_routerIndex(options){ Composer.setConfig({ pathToTemplate : RestApiConfig.routerIndex.pathToTemplate, outputFile : RestApiConfig.routerIndex.output }); for(index in options.models){ Composer.build( RestApiConfig.routerIndex.pathToTemplate + "/" + RestApiConfig.routerIndex.inputTemplate, RestApiConfig.routerIndex.output + '/' + "index.js",options.models); var dest = "./" + options.name + RestApiConfig.routerIndex.pathToGenerated ; copyFileToProject(RestApiConfig.routerIndex.output,dest); } } function build_tests(options){ Composer.setConfig({ pathToTemplate : RestApiConfig.tests.pathToTemplate, outputFile : RestApiConfig.tests.output }); for(index in options.models){ Composer.build( RestApiConfig.tests.pathToTemplate + "/" + RestApiConfig.tests.inputTemplate, RestApiConfig.tests.output + '/' + options.models[index].name + ".js",options.models[index]); var dest = "./" + options.name + RestApiConfig.tests.pathToGenerated ; copyFileToProject(RestApiConfig.tests.output,dest); } } function build_routerRoutes(options){ Composer.setConfig({ pathToTemplate : RestApiConfig.routerRoutes.pathToTemplate, outputFile : RestApiConfig.routerRoutes.output }); for(index in options.models){ Composer.build( RestApiConfig.routerRoutes.pathToTemplate + "/" + RestApiConfig.routerRoutes.inputTemplate, RestApiConfig.routerRoutes.output + '/' + options.models[index].name + ".js",options.models[index]); var dest = "./" + options.name + RestApiConfig.routerRoutes.pathToGenerated ; copyFileToProject(RestApiConfig.routerRoutes.output,dest); } } var say = function(string_to_say , options) { cloneProjectStructure('RestApi',options.name); build_bd(options); build_models(options); build_controllers(options); build_routerIndex(options); build_routerRoutes(options); build_tests(options); return console.log(string_to_say); }; // Allows us to call this function from outside of the library file. // Without this, the function would be private to this file. exports.say = say;
{ "content_hash": "b58be9eb75a490ea4299b3e087400b23", "timestamp": "", "source": "github", "line_count": 269, "max_line_length": 115, "avg_line_length": 34.96654275092937, "alnum_prop": 0.6372528173506272, "repo_name": "siu-lim-studio/mongo-", "id": "15193cc0f6189e29cb8868e1c207d82c663040b4", "size": "9406", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "28068" }, { "name": "Smarty", "bytes": "20760" } ], "symlink_target": "" }
package com.bzh.dytt; import android.arch.core.executor.testing.InstantTaskExecutorRule; import android.arch.lifecycle.Lifecycle; import android.arch.lifecycle.LifecycleOwner; import android.arch.lifecycle.LifecycleRegistry; import android.arch.lifecycle.Observer; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class SingleLiveEventTest { // Execute tasks synchronously @Rule public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule(); // The class that has the lifecycle @Mock private LifecycleOwner mOwner; // The observer of the event under test @Mock private Observer<Integer> mEventObserver; // Defines the Android Lifecycle of an object, used to trigger different events private LifecycleRegistry mLifecycle; // Event object under test private SingleLiveEvent<Integer> mSingleLiveEvent = new SingleLiveEvent<>(); @Before public void setUpLifecycles() { MockitoAnnotations.initMocks(this); // Link custom lifecycle owner with the lifecyle register. mLifecycle = new LifecycleRegistry(mOwner); when(mOwner.getLifecycle()).thenReturn(mLifecycle); // Start observing mSingleLiveEvent.observe(mOwner, mEventObserver); // Start in a non-active state mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); } @Test public void valueNotSet_onFirstOnResume() { // On resume mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); // no updateItem should be emitted because no value has been set verify(mEventObserver, never()).onChanged(anyInt()); } @Test public void singleUpdate_onSecondOnResume_updatesOnce() { // After a value is set mSingleLiveEvent.setValue(42); // observers are called once on resume mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); // on second resume, no updateItem should be emitted. mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_STOP); mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); // Check that the observer is called once verify(mEventObserver, times(1)).onChanged(anyInt()); } @Test public void twoUpdates_updatesTwice() { // After a value is set mSingleLiveEvent.setValue(42); // observers are called once on resume mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); // when the value is set again, observers are called again. mSingleLiveEvent.setValue(23); // Check that the observer has been called twice verify(mEventObserver, times(2)).onChanged(anyInt()); } @Test public void twoUpdates_noUpdateUntilActive() { // Set a value mSingleLiveEvent.setValue(42); // which doesn't emit a change verify(mEventObserver, never()).onChanged(42); // and set it again mSingleLiveEvent.setValue(42); // observers are called once on resume. mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); // Check that the observer is called only once verify(mEventObserver, times(1)).onChanged(anyInt()); } }
{ "content_hash": "d3071f483b26e5ae4bca4bbee5773c1d", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 87, "avg_line_length": 31.157894736842106, "alnum_prop": 0.7032657657657657, "repo_name": "DYTT-2017/DYTT", "id": "7c356a30ea34e9ccc2ec8c0e5c8bae32f3cb81cc", "size": "3552", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/test/java/com/bzh/dytt/SingleLiveEventTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "139835" }, { "name": "Java", "bytes": "144535" } ], "symlink_target": "" }
#ifndef MBED_INTERFACE_H #define MBED_INTERFACE_H #include <stdarg.h> #include "platform/mbed_toolchain.h" #include "device.h" /** \addtogroup platform-public-api */ /** @{*/ /** * \defgroup platform_interface Network interface and other utility functions * @{ */ /* Mbed interface mac address * if MBED_MAC_ADD_x are zero, interface uid sets mac address, * otherwise MAC_ADD_x are used. */ #define MBED_MAC_ADDR_INTERFACE 0x00 #define MBED_MAC_ADDR_0 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDR_1 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDR_2 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDR_3 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDR_4 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDR_5 MBED_MAC_ADDR_INTERFACE #define MBED_MAC_ADDRESS_SUM (MBED_MAC_ADDR_0 | MBED_MAC_ADDR_1 | MBED_MAC_ADDR_2 | MBED_MAC_ADDR_3 | MBED_MAC_ADDR_4 | MBED_MAC_ADDR_5) #ifdef __cplusplus extern "C" { #endif #if DEVICE_SEMIHOST /** * \defgroup platform_interface interface functions * @{ */ /** Functions to control the mbed interface * * mbed Microcontrollers have a built-in interface to provide functionality such as * drag-n-drop download, reset, serial-over-usb, and access to the mbed local file * system. These functions provide means to control the interface using semihost * calls it supports. */ /** Determine whether the mbed interface is connected, based on whether debug is enabled * * @returns * 1 if interface is connected, * 0 otherwise */ int mbed_interface_connected(void); /** Instruct the mbed interface to reset, as if the reset button had been pressed * * @returns * 1 if successful, * 0 otherwise (e.g. interface not present) */ int mbed_interface_reset(void); /** This will disconnect the debug aspect of the interface, so semihosting will be disabled. * The interface will still support the USB serial aspect * * @returns * 0 if successful, * -1 otherwise (e.g. interface not present) */ int mbed_interface_disconnect(void); /** This will disconnect the debug aspect of the interface, and if the USB cable is not * connected, also power down the interface. If the USB cable is connected, the interface * will remain powered up and visible to the host * * @returns * 0 if successful, * -1 otherwise (e.g. interface not present) */ int mbed_interface_powerdown(void); /** This returns a string containing the 32-character UID of the mbed interface * This is a weak function that can be overwritten if required * * @param uid A 33-byte array to write the null terminated 32-byte string * * @returns * 0 if successful, * -1 otherwise (e.g. interface not present) */ int mbed_interface_uid(char *uid); #endif /** This returns a unique 6-byte MAC address, based on the interface UID * If the interface is not present, it returns a default fixed MAC address (00:02:F7:F0:00:00) * * This is a weak function that can be overwritten if you want to provide your own mechanism to * provide a MAC address. * * @param mac A 6-byte array to write the MAC address */ void mbed_mac_address(char *mac); /** Cause the mbed to flash the BLOD (Blue LEDs Of Death) sequence */ MBED_NORETURN void mbed_die(void); /** Print out an error message. This is typically called when * handling a crash. * * @note Synchronization level: Interrupt safe, as long as the * FileHandle::write of the stderr device is. See mbed_error_puts * for more information. * @note This uses an internal 128-byte buffer to format the string, * so the output may be truncated. If you need to write a potentially * long string, use mbed_error_puts. * * @param format C string that contains data stream to be printed. * Code snippets below show valid format. * * @code * mbed_error_printf("Failed: %s, file: %s, line %d \n", expr, file, line); * @endcode * */ void mbed_error_printf(const char *format, ...) MBED_PRINTF(1, 2); /** Print out an error message. Similar to mbed_error_printf * but uses a va_list. * * @note Synchronization level: Interrupt safe, as long as the * FileHandle::write of the stderr device is. See mbed_error_puts * for more information. * * @param format C string that contains data stream to be printed. * @param arg Variable arguments list * */ void mbed_error_vprintf(const char *format, va_list arg) MBED_PRINTF(1, 0); /** Print out an error message. This is typically called when * handling a crash. * * Unlike mbed_error_printf, there is no limit to the maximum output * length. Unlike standard puts, but like standard fputs, this does not * append a '\n' character. * * @note Synchronization level: Interrupt safe, as long as the * FileHandle::write of the stderr device is. The default * serial console is safe, either buffered or not. If the * console has not previously been initialized, an attempt * to use this from interrupt may crash during console initialization. * Special handling of `mbed_error` relaxes various system traps * to increase the chance of initialization working. * * @param str C string that contains data stream to be printed. * */ void mbed_error_puts(const char *str); /** @deprecated Renamed to mbed_error_vprintf to match functionality */ MBED_DEPRECATED_SINCE("mbed-os-5.11", "Renamed to mbed_error_vprintf to match functionality.") void mbed_error_vfprintf(const char *format, va_list arg) MBED_PRINTF(1, 0); /** @}*/ #ifdef __cplusplus } #endif #endif /** @}*/
{ "content_hash": "ae883fd6b6e0611022e734785d181cda", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 136, "avg_line_length": 31.34269662921348, "alnum_prop": 0.701917906434845, "repo_name": "andcor02/mbed-os", "id": "cb90c95e3bf4348532b6db834e28f50c8ff363e9", "size": "6250", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "platform/mbed_interface.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "6601399" }, { "name": "Batchfile", "bytes": "22" }, { "name": "C", "bytes": "295194591" }, { "name": "C++", "bytes": "9038670" }, { "name": "CMake", "bytes": "5285" }, { "name": "HTML", "bytes": "2063156" }, { "name": "Makefile", "bytes": "103497" }, { "name": "Objective-C", "bytes": "460244" }, { "name": "Perl", "bytes": "2589" }, { "name": "Python", "bytes": "38809" }, { "name": "Shell", "bytes": "16862" }, { "name": "XSLT", "bytes": "5596" } ], "symlink_target": "" }
import cv2 import argparse def run(im, multi=False): im_disp = im.copy() im_draw = im.copy() window_name = "Select objects to be tracked here." cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) cv2.imshow(window_name, im_draw) # List containing top-left and bottom-right to crop the image. pts_1 = [] pts_2 = [] rects = [] run.mouse_down = False def callback(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDOWN: if multi == False and len(pts_2) == 1: print "WARN: Cannot select another object in SINGLE OBJECT TRACKING MODE." print "Delete the previously selected object using key `d` to mark a new location." return run.mouse_down = True pts_1.append((x, y)) elif event == cv2.EVENT_LBUTTONUP and run.mouse_down == True: run.mouse_down = False pts_2.append((x, y)) print "Object selected at [{}, {}]".format(pts_1[-1], pts_2[-1]) elif event == cv2.EVENT_MOUSEMOVE and run.mouse_down == True: im_draw = im.copy() cv2.rectangle(im_draw, pts_1[-1], (x, y), (255,255,255), 3) cv2.imshow(window_name, im_draw) print "Press and release mouse around the object to be tracked. \n You can also select multiple objects." cv2.setMouseCallback(window_name, callback) print "Press key `p` to continue with the selected points." print "Press key `d` to discard the last object selected." print "Press key `q` to quit the program." while True: # Draw the rectangular boxes on the image window_name_2 = "Objects to be tracked." for pt1, pt2 in zip(pts_1, pts_2): rects.append([pt1[0],pt2[0], pt1[1], pt2[1]]) cv2.rectangle(im_disp, pt1, pt2, (255, 255, 255), 3) # Display the cropped images cv2.namedWindow(window_name_2, cv2.WINDOW_NORMAL) cv2.imshow(window_name_2, im_disp) key = cv2.waitKey(30) if key == ord('p'): # Press key `s` to return the selected points cv2.destroyAllWindows() return [(tl + br) for tl, br in zip(pts_1, pts_2)] elif key == ord('q'): # Press key `q` to quit the program print "Quitting without saving." exit() elif key == ord('d'): # Press ket `d` to delete the last rectangular region if run.mouse_down == False and pts_1: print "Object deleted at [{}, {}]".format(pts_1[-1], pts_2[-1]) pts_1.pop() pts_2.pop() im_disp = im.copy() else: print "No object to delete." cv2.destroyAllWindows() return [(tl + br) for tl, br in zip(pts_1, pts_2)] if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("-i", "--imagepath", required=True, help="Path to image") args = vars(ap.parse_args()) try: im = cv2.imread(args["imagepath"]) except: print "Cannot read image and exiting." exit() points = run(im) print "Rectangular Regions Selected are -> ", points
{ "content_hash": "5d91560c698cf672764fbc699623df6f", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 109, "avg_line_length": 37.48809523809524, "alnum_prop": 0.5722451571927596, "repo_name": "yanweifu/object-tracker", "id": "f6d7b92174963e7a04fe3e53c6c71ef2aa9f58ef", "size": "3179", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "get_points.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "9312" } ], "symlink_target": "" }
\providecommand{\nperfprof}{7}\providecommand{\algAperfprof}{\StrLeft{2-D}{\nperfprof}}\providecommand{\algBperfprof}{\StrLeft{3-D}{\nperfprof}}\providecommand{\algCperfprof}{\StrLeft{5-D}{\nperfprof}}\providecommand{\algDperfprof}{\StrLeft{10-D}{\nperfprof}}\providecommand{\algEperfprof}{\StrLeft{20-D}{\nperfprof}}\providecommand{\algFperfprof}{\StrLeft{40-D}{\nperfprof}}\providecommand{\perfprofsidepanel}{{\mbox{\algFperfprof} \vfill \mbox{\algEperfprof} \vfill \mbox{\algDperfprof} \vfill \mbox{\algCperfprof} \vfill \mbox{\algBperfprof} \vfill \mbox{\algAperfprof}}}
{ "content_hash": "db87dd798bf8bd37f8c8750919d037fa", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 432, "avg_line_length": 95.83333333333333, "alnum_prop": 0.7704347826086957, "repo_name": "PyQuake/earthquakemodels", "id": "95fe671775bef5ebf4482639684e5eaf54ea5d2f", "size": "575", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/cocobbob/coco/defaultExperiment/postProcessedDefaultExperiment/exdata/pprldmany-single-functions/pprldmany_f019.tex", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE HTML> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="//d3js.org/d3.v3.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/> <script type="text/javascript" src="script.js"></script> <script type="text/javascript" src="settings.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="style.css"> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav"> <li><a href="game.html">Game</a></li> <li class="active"><a href="settings.html">Settings</a></li> <li><a href="phrases.html">Catchphrases</a></li> </ul> </div> </div> </nav> <div class="container-fluid text-center" id="mainPage"> <div class="row content" id="mainRows"> <div class="col-sm-2 sidenav"> </div> <div class="col-sm-8 text-left" id="settings"> <h1>Duration Settings</h1> <hr> <form> <p> <label>Range:</label> <input type="text" id="range" readonly style="border:0; color:#f6931f; font-weight:bold;"> </p> <div id="rangeSlider"></div> <br> <label>Distribution:</label> <select name="dist" onchange="distShow(this.value)" id="dist"> <option value="uniform">Uniform</option> <option value="normal">Normal</option> </select> <div id="normal"> <p> <br> <label for="mean">Mean:</label> <input type="text" id="mean" readonly style="border:0; color:#f6931f; font-weight:bold;"> </p> <div id="meanSlider"></div> <p> <label>Standard deviation:</label> <input type="text" id="sd" readonly style="border:0; color:#f6931f; font-weight:bold;"> </p> <div id="sdSlider"></div> <div id="graph"></div> </div> </form> </div> <div class="col-sm-2 sidenav"> </div> </div> </div> <footer class="footer container-fluid text-center"> <p>This project is Open Source.</p> </footer> </body> </html>
{ "content_hash": "6162016025d9982e897d20299fd3a072", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 120, "avg_line_length": 40.4025974025974, "alnum_prop": 0.537769206043073, "repo_name": "ojh31/ojh31.github.io", "id": "ac69837a5cef001872a8af3de69ab531275d243e", "size": "3111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "catchphrase/settings.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21449" }, { "name": "HTML", "bytes": "24628" }, { "name": "JavaScript", "bytes": "50869" } ], "symlink_target": "" }
/** * Sunseeker Telemetry * * Battery Interface * * @author Alec Carpenter <alec.g.carpenter@wmich.edu> */ package Sunseeker.Telemetry.Battery; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; class SerialHandler implements Listener, ActionListener { // Menu option commands private final String ACTION_CONNECT = "connect"; private final String ACTION_DISCONNECT = "disconnect"; // Events public final static String EVENT_CONNECTION = "connection"; // Status messages private final String STATUS_CONNECTED = "Connected to serial port, waiting for data."; private final String STATUS_ERROR = "Could not connect to serial port."; private final String STATUS_DISCONNECTED = "Disconnected from serial port."; private final String STATUS_PAGE_STARTED = "Receiving data..."; private final String STATUS_PAGE_WAIT = "Waiting for more data..."; // Dependencies Serial serial; MainInterface mainIntf; PortInterface portIntf; // Status boolean connected; // Menu options JMenuItem connectItem; JMenuItem disconnectItem; SerialHandler (Serial comms, MainInterface mainI, PortInterface portI) { serial = comms; mainIntf = mainI; portIntf = portI; initializeMenu(); initializeListeners(); } public void actionPerformed (ActionEvent e) { switch (e.getActionCommand()) { case ACTION_CONNECT: String port = portIntf.trigger(serial.getPortNames()); if (port != null) { if (serial.setActivePort(port)) { updateConnectionState(true); mainIntf.updateStatus(STATUS_CONNECTED); } else { mainIntf.updateStatus(STATUS_ERROR); } } break; case ACTION_DISCONNECT: serial.setActivePort(null); updateConnectionState(false); mainIntf.updateStatus(STATUS_DISCONNECTED); break; } } public void triggered (Event e) { switch (e.getEvent()) { case Serial.EVENT_PAGE_START: mainIntf.updateStatus(STATUS_PAGE_STARTED); break; case Serial.EVENT_PAGE_COMPLETE: mainIntf.updateStatus(STATUS_PAGE_WAIT); break; } } private void initializeMenu () { JMenu optionsMenu = new JMenu("Connection"); mainIntf.addMenu(optionsMenu); connectItem = new JMenuItem("Connect"); connectItem.setActionCommand(ACTION_CONNECT); connectItem.addActionListener(this); optionsMenu.add(connectItem); disconnectItem = new JMenuItem("Disconnect"); disconnectItem.setActionCommand(ACTION_DISCONNECT); disconnectItem.addActionListener(this); optionsMenu.add(disconnectItem); updateConnectionState(false); } private void initializeListeners () { Dispatcher.subscribe(Serial.EVENT_PAGE_START, this); Dispatcher.subscribe(Serial.EVENT_PAGE_COMPLETE, this); } private void updateConnectionState (boolean state) { connected = state; Dispatcher.trigger(EVENT_CONNECTION, connected); connectItem.setEnabled(!connected); disconnectItem.setEnabled(connected); } }
{ "content_hash": "000fce4e87dae2cf9d10a2295e6c3885", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 93, "avg_line_length": 30.321739130434782, "alnum_prop": 0.6197304273014053, "repo_name": "SunseekerSolarCarProject/battery-telemetry", "id": "0ca40e18533c91d6832dd9d01db119cc73d4e800", "size": "3487", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Handler/SerialHandler.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "24517" } ], "symlink_target": "" }
do{ \ if (this->debug) printf (P_GREEN); \ if (this->debug) printf ("%s(): ", __func__); \ if (this->debug) printf (x); \ if (this->debug) printf (P_NORMAL); \ }while(0) #define CHECK_NYSA_ERROR(x) \ do{ \ if (retval < 0){ \ if (this->debug) printf (x " %d\n", retval); \ return retval; \ } \ }while(0) class Nysa { private: uint8_t * drt; bool debug; int parse_drt(); //DRT Values int num_devices; uint8_t version; public: Nysa (bool debug = false); ~Nysa(); int open(); int close(); //Low Level interface virtual int write_memory(uint32_t address, uint8_t *buffer, uint32_t size); virtual int read_memory(uint32_t address, uint8_t *buffer, uint32_t size); virtual int write_periph_data(uint32_t dev_addr, uint32_t addr, uint8_t *buffer, uint32_t size); virtual int read_periph_data(uint32_t dev_addr, uint32_t addr, uint8_t *buffer, uint32_t size); virtual int wait_for_interrupts(uint32_t timeout, uint32_t *interrupts); virtual int ping(); virtual int crash_report(uint32_t *buffer); //Helper Functions int write_register(uint32_t dev_addr, uint32_t reg_addr, uint32_t data); int set_register_bit(uint32_t dev_addr, uint32_t reg_addr, uint8_t bit); int clear_register_bit(uint32_t dev_addr, uint32_t reg_addr, uint8_t bit); int read_register(uint32_t dev_addr, uint32_t reg_addr, uint32_t *data); int read_register_bit(uint32_t dev_addr, uint32_t reg_addr, uint8_t bit, bool *value); //DRT int pretty_print_drt(); int read_drt(); int get_drt_version(); int get_drt_device_count(); uint16_t get_drt_device_type(uint32_t index); uint16_t get_drt_device_sub_type(uint32_t index); uint16_t get_drt_device_user_id(uint32_t index); uint32_t get_image_id(); uint32_t get_board_id(); bool is_memory_device(uint32_t index); uint32_t get_drt_device_size(uint32_t index); int get_drt_device_flags(uint32_t index, uint16_t *nysa_flags, uint16_t *dev_flags); uint32_t get_drt_device_addr(uint32_t index); int pretty_print_crash_report(); uint32_t find_device(uint32_t device_type, uint32_t subtype = 0, uint32_t id = 0); }; #endif //__NYSA_H__
{ "content_hash": "c062fb94aaacb9f28dea8ebf0c4b2bbb", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 100, "avg_line_length": 32.973684210526315, "alnum_prop": 0.5754189944134078, "repo_name": "cospan/nysa_cpp", "id": "b9589649c7a2a7542cc46fd07c6d1b41f6c2bf16", "size": "2666", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/nysa.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "151450" }, { "name": "Python", "bytes": "6195" }, { "name": "Shell", "bytes": "36" } ], "symlink_target": "" }
module Parser where import Control.Applicative((<*)) import Text.Parsec import Text.Parsec.String import Text.Parsec.Token import Text.Parsec.Language -- Our language definition and operators. import Lang import Common -- | Generate our Lang definition from emptyDef. langDef = emptyDef { commentLine = "--" , nestedComments = False , identStart = letter <|> char '_' , identLetter = alphaNum <|> oneOf "_'" , opStart = opLetter emptyDef , opLetter = oneOf "+-*|&<>=~" , reservedOpNames= [] , reservedNames = ["fun", "if", "true", "false", "head", "not", "tail", "fst", "snd"] , caseSensitive = True } -- | Get token parsers from langauge definition. TokenParser{ parens = parensP , identifier = identifierP , reserved = reservedP , operator = operatorP , semiSep1 = semiSep1P , whiteSpace = whiteSpaceP , charLiteral = charLiteralP , stringLiteral = stringLiteralP , natural = naturalP , brackets = bracketsP , comma = commaP , commaSep = commaSepP , dot = dotP } = makeTokenParser langDef -- | Main parser for Lang. TODO whitespace at the front and eof and the end. expressionParser :: Parser Exp expressionParser = try funParser <|> try litParser <|> try varParser <|> try appParser <|> try binParser <|> try uniParser <|> try ifParser funParser :: Parser Exp funParser = parensP $ do reservedP "fun" boundVar <- identifierP dotP body <- expressionParser return (Lam boundVar body) appParser :: Parser Exp appParser = parensP $ do fun <- expressionParser arg <- expressionParser return (fun :@ arg) -- TODO forgot "Cons" binParser :: Parser Exp binParser = parensP $ do op <- operatorP case mapBinOp op of Just myOp -> do e1 <- expressionParser e2 <- expressionParser return (Bin myOp e1 e2) Nothing -> unexpected $ "Bin: Unkown operator: '" ++ op ++ "'" mapBinOp :: String -> Maybe BinOp mapBinOp "+" = Just Plus mapBinOp "-" = Just Minus mapBinOp "*" = Just Mult mapBinOp "||" = Just Or mapBinOp "&&" = Just And mapBinOp "<=" = Just Lte mapBinOp ">=" = Just Gte mapBinOp "<" = Just Lt mapBinOp ">" = Just Gt mapBinOp "==" = Just Eq mapBinOp _ = Nothing uniParser :: Parser Exp uniParser = parensP $ (reservedP "not" >> expressionParser >>= return . (Uni Not)) <|> (reservedP "fst" >> expressionParser >>= return . (Uni Fst)) <|> (reservedP "snd" >> expressionParser >>= return . (Uni Snd)) <|> (reservedP "head" >> expressionParser >>= return . (Uni Head)) <|> (reservedP "tail" >> expressionParser >>= return . (Uni Tail)) -- I'm sure there is a better way to write these parsers. I'm just not good enough -- with applicative functors X( litParser :: Parser Exp litParser = (naturalP >>= return . Lit) <|> (reservedP "true" >> return (Lit True)) <|> (reservedP "false" >> return (Lit False)) <|> (charLiteralP >>= return . Lit) <|> (stringLiteralP >>= return . Lit) <|> listParser <|> tupleParser listParser :: Parser Exp listParser = bracketsP (commaSepP expressionParser >>= return . makeList) -- Given a list of expressions representing the parse of a list literal, return -- it as a single list using our List data. makeList :: [Exp] -> Exp makeList [] = Nill makeList (x : xs) = Bin Cons x (makeList xs) tupleParser :: Parser Exp tupleParser = parensP $ do t1 <- expressionParser commaP t2 <- expressionParser return (Bin Tup t1 t2) varParser :: Parser Exp varParser = identifierP >>= return . Var ifParser :: Parser Exp ifParser = parensP $ do reservedP "if" cond <- expressionParser e1 <- expressionParser e2 <- expressionParser return (If cond e1 e2) -- Fix parser to take tryParse :: String -> Exp tryParse input = case parse expressionParser "" input of Left err -> error (show err) Right exp -> exp
{ "content_hash": "6ae97c0491f28ac4f7765bde5c1e736f", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 82, "avg_line_length": 28.08843537414966, "alnum_prop": 0.6137079195931219, "repo_name": "plclub/cis670-16fa", "id": "fe804ead0f9d38999f4c0f8dd18a7bfb28c18844", "size": "4129", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/DynamicLang/src/Parser.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Clojure", "bytes": "8584" }, { "name": "Coq", "bytes": "947088" }, { "name": "HTML", "bytes": "75799" }, { "name": "Haskell", "bytes": "90770" }, { "name": "OCaml", "bytes": "3746" }, { "name": "TeX", "bytes": "22049" } ], "symlink_target": "" }
<?php namespace pub007\dstruct\auth; /** * AuthContainers class */ /** * Collection of AuthContainer objects. *@package dstruct_auth */ class AuthContainers { /** * Collection of AuthContainer objects * @var array */ private static $authcontainers = array(); /** * Load all auth containers into the collection. * @return object */ public function getAll() { if (count(self::$authcontainers) == 0) { $prefs = Prefs::getInstance(); $authcontainers = $prefs->get('authcontainers'); foreach ($authcontainers as $container) { self::$authcontainers[$container] = new $container; } } return self::$authcontainers; } } ?>
{ "content_hash": "032c6ca30d8859bf3322ef79b554de91", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 54, "avg_line_length": 18.852941176470587, "alnum_prop": 0.6817472698907956, "repo_name": "pub007/dstruct", "id": "f0cea10d8704c42b2133d97f9f1a047e54883e9d", "size": "641", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/auth/AuthContainers.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "289552" } ], "symlink_target": "" }
package API::Parameter; # # # 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. # # # use UI::Utils; use UI::Parameter; use Mojo::Base 'Mojolicious::Controller'; use Data::Dumper; use POSIX qw(strftime); use Time::Local; use LWP; use MojoPlugins::Response; use MojoPlugins::Job; use Utils::Helper::ResponseHelper; sub index { my $self = shift; my $rs_data = $self->db->resultset("Parameter")->search(); my @data = (); while ( my $row = $rs_data->next ) { my $value = $row->value; &UI::Parameter::conceal_secure_parameter_value( $self, $row->secure, \$value ); push( @data, { "name" => $row->name, "id" => $row->id, "configFile" => $row->config_file, "value" => $value, "secure" => \$row->secure, "lastUpdated" => $row->last_updated } ); } $self->success( \@data ); } sub show { my $self = shift; my $id = $self->param('id'); my $find = $self->db->resultset('Parameter')->find({ id => $id } ); if ( !defined($find) ) { return $self->not_found("parameter [id:".$id."] does not exist."); } if ( $find->secure != 0 && !&is_admin($self)) { return $self->forbidden("You must be an admin to perform this operation!"); } my @data = (); push( @data, { "id" => $find->id, "name" => $find->name, "configFile" => $find->config_file, "value" => $find->value, "secure" => \$find->secure, "lastUpdated" => $find->last_updated } ); $self->success( \@data ); } sub get_profile_params { my $self = shift; my $profile_id = $self->param('id'); my $profile_name = $self->param('name'); my %criteria; if ( defined $profile_id ) { $criteria{'profile.id'} = $profile_id; } elsif ( defined $profile_name ) { $criteria{'profile.name'} = $profile_name; } else { return $self->alert("Profile ID or Name is required"); } my $rs_data = $self->db->resultset("ProfileParameter")->search( \%criteria, { prefetch => [ 'parameter', 'profile' ] } ); my @data = (); while ( my $row = $rs_data->next ) { my $value = $row->parameter->value; &UI::Parameter::conceal_secure_parameter_value( $self, $row->parameter->secure, \$value ); push( @data, { "name" => $row->parameter->name, "id" => $row->parameter->id, "configFile" => $row->parameter->config_file, "value" => $value, "secure" => \$row->parameter->secure, "lastUpdated" => $row->parameter->last_updated } ); } $self->success( \@data ); } sub get_profile_params_unassigned { my $self = shift; my $profile_id = $self->param('id'); my $profile_name = $self->param('name'); my %criteria; if ( defined $profile_id ) { $criteria{'profile.id'} = $profile_id; } elsif ( defined $profile_name ) { $criteria{'profile.name'} = $profile_name; } else { return $self->alert("Profile ID or Name is required"); } my @assigned_params = $self->db->resultset('ProfileParameter')->search( \%criteria, { prefetch => [ 'parameter', 'profile' ] } )->get_column('parameter')->all(); my $rs_data = $self->db->resultset("Parameter")->search( 'me.id' => { 'not in' => \@assigned_params } ); my @data = (); while ( my $row = $rs_data->next ) { my $value = $row->value; &UI::Parameter::conceal_secure_parameter_value( $self, $row->secure, \$value ); push( @data, { "name" => $row->name, "id" => $row->id, "configFile" => $row->config_file, "value" => $value, "secure" => \$row->secure, "lastUpdated" => $row->last_updated } ); } $self->success( \@data ); } sub get_cachegroup_params { my $self = shift; my $cg_id = $self->param('id'); my %criteria; if ( defined $cg_id ) { $criteria{'cachegroup.id'} = $cg_id; } else { return $self->alert("Cache Group ID is required"); } my $rs_data = $self->db->resultset("CachegroupParameter")->search( \%criteria, { prefetch => [ 'cachegroup', 'parameter' ] } ); my @data = (); while ( my $row = $rs_data->next ) { my $value = $row->parameter->value; &UI::Parameter::conceal_secure_parameter_value( $self, $row->parameter->secure, \$value ); push( @data, { "name" => $row->parameter->name, "id" => $row->parameter->id, "configFile" => $row->parameter->config_file, "value" => $value, "secure" => \$row->parameter->secure, "lastUpdated" => $row->parameter->last_updated } ); } $self->success( \@data ); } sub get_cachegroup_params_unassigned { my $self = shift; my $cg_id = $self->param('id'); my %criteria; if ( defined $cg_id ) { $criteria{'cachegroup.id'} = $cg_id; } else { return $self->alert("Cache Group ID is required"); } my @assigned_params = $self->db->resultset('CachegroupParameter')->search( \%criteria, { prefetch => [ 'parameter', 'cachegroup' ] } )->get_column('parameter')->all(); my $rs_data = $self->db->resultset("Parameter")->search( 'me.id' => { 'not in' => \@assigned_params } ); my @data = (); while ( my $row = $rs_data->next ) { my $value = $row->value; &UI::Parameter::conceal_secure_parameter_value( $self, $row->secure, \$value ); push( @data, { "name" => $row->name, "id" => $row->id, "configFile" => $row->config_file, "value" => $value, "secure" => \$row->secure, "lastUpdated" => $row->last_updated } ); } $self->success( \@data ); } sub create { my $self = shift; my $params = $self->req->json; if ( !defined($params) ) { return $self->alert("parameters must be in JSON format, please check!"); } if ( !&is_oper($self) ) { return $self->forbidden("You must be an admin or oper to perform this operation!"); } if ( ref($params) ne 'ARRAY' ) { #not a array, create single parameter my @temparry; push(@temparry, $params); $params = \@temparry; } if ( scalar($params) == 0 ) { return $self->alert("parameters array length is 0."); } my @new_parameters = (); $self->db->txn_begin(); my $param; foreach $param (@{ $params }) { if ( !defined($param->{name}) ) { $self->db->txn_rollback(); return $self->alert("there is parameter name does not provide , configFile:".$param->{configFile}." , value:".$param->{value}); } if ( !defined($param->{configFile}) ) { $self->db->txn_rollback(); return $self->alert("there is parameter configFile does not provide , name:".$param->{name}." , value:".$param->{value}); } if ( !defined($param->{value}) ) { $self->db->txn_rollback(); return $self->alert("there is parameter value does not provide , name:".$param->{name}." , configFile:".$param->{configFile}); } if ( !defined($param->{secure}) ) { $param->{secure} = 0 } else { if (($param->{secure} ne '0') && ($param->{secure} ne '1')) { $self->db->txn_rollback(); return $self->alert("secure must 0 or 1, parameter [name:".$param->{name}." , configFile:".$param->{configFile}." , value:".$param->{value}." , secure:".$param->{secure}."]"); } $param->{secure} = 0 if ($param->{secure} eq '0' ); $param->{secure} = 1 if ($param->{secure} eq '1' ); if ( $param->{secure} != 0 && !&is_admin($self)) { $self->db->txn_rollback(); return $self->forbidden("Parameter[name:".$param->{name}." , configFile:".$param->{configFile}." , value:".$param->{value}."] secure=1, You must be an admin to perform this operation!"); } } my $find = $self->db->resultset('Parameter')->find( { name => $param->{name}, config_file => $param->{configFile}, value => $param->{value} } ); if ( defined($find)) { $self->db->txn_rollback(); return $self->alert("parameter [name:".$param->{name}." , configFile:".$param->{configFile}." , value:".$param->{value}."] already exists."); } my $insert = $self->db->resultset('Parameter')->create( { name => $param->{name}, config_file => $param->{configFile}, value => $param->{value}, secure => $param->{secure} } ); $insert->insert(); push(@new_parameters, { 'id' => $insert->id, 'name' => $insert->name, 'configFile' => $insert->config_file, 'value' => $insert->value, 'secure' => $insert->secure }) } $self->db->txn_commit(); my $response = \@new_parameters; return $self->success($response, "Create ". scalar(@new_parameters) . " parameters successfully."); } sub update { my $self = shift; my $id = $self->param('id'); my $params = $self->req->json; if ( !defined($params) ) { return $self->alert("parameters must be in JSON format, please check!"); } if ( !&is_oper($self) ) { return $self->forbidden("You must be an admin or oper to perform this operation!"); } my $find = $self->db->resultset('Parameter')->find({ id => $id } ); if ( !defined($find) ) { return $self->not_found("parameter [id:".$id."] does not exist."); } if ( $find->secure != 0 && !&is_admin($self)) { return $self->forbidden("You must be an admin to perform this operation!"); } my $name = $params->{name} || $find->name; my $configFile = $params->{configFile} || $find->config_file; my $value = $params->{value} || $find->value; my $secure = $find->secure; if ( defined($params->{secure}) ) { $secure = $params->{secure}; } $find->update( { name => $name, config_file => $configFile, value => $value, secure => $secure } ); my $response; $response->{id} = $find->id; $response->{name} = $find->name; $response->{configFile} = $find->config_file; $response->{value} = $find->value; $response->{secure} = $find->secure; return $self->success($response, "Parameter was successfully edited."); } sub delete { my $self = shift; my $id = $self->param('id'); my $params = $self->req->json; if ( !&is_oper($self) ) { return $self->forbidden( "You must be an admin or oper to perform this operation!" ); } my $find = $self->db->resultset('Parameter')->find({ id => $id } ); $self->app->log->debug("defined find #-> " . defined($find)); if ( !defined($find) ) { return $self->not_found("parameter [id:".$id."] does not exist."); } if ( $find->secure != 0 && !&is_admin($self)) { return $self->forbidden("You must be an admin to perform this operation!"); } my $find_profile = $self->db->resultset('ProfileParameter')->find( { parameter => $id } ); if ( defined($find_profile) ) { return $self->alert("fail to delete parameter, parameter [id:".$id."] has profile associated."); } $find->delete(); return $self->success_message("Parameter was successfully deleted."); } sub validate { my $self = shift; my $params = $self->req->json; if ( !defined($params) ) { return $self->alert("parameters must be in JSON format, please check!"); } if ( !defined($params->{name}) ) { return $self->alert("Parameter name is required."); } if ( !defined($params->{configFile}) ) { return $self->alert("Parameter configFile is required."); } if ( !defined($params->{value}) ) { return $self->alert("Parameter value is required."); } my $find = $self->db->resultset('Parameter')->find({ name => $params->{name}, config_file => $params->{configFile}, value => $params->{value}, } ) ; if ( !defined($find) ) { return $self->alert("parameter [name:".$params->{name}.", config_file:".$params->{configFile}.", value:".$params->{value}."] does not exist."); } my $response; $response->{id} = $find->id; $response->{name} = $find->name; $response->{configFile} = $find->config_file; $response->{value} = $find->value; $response->{secure} = $find->secure; return $self->success($response, "Parameter exists."); } 1;
{ "content_hash": "e44d8672362085e1137f43b10e024bc6", "timestamp": "", "source": "github", "line_count": 409, "max_line_length": 202, "avg_line_length": 33.28850855745721, "alnum_prop": 0.5224384869629085, "repo_name": "naamashoresh/incubator-trafficcontrol", "id": "dd0217310db013a532c7151b577ba0af34fd56ff", "size": "13615", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "traffic_ops/app/lib/API/Parameter.pm", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "21929" }, { "name": "CSS", "bytes": "195099" }, { "name": "Go", "bytes": "1160352" }, { "name": "HTML", "bytes": "612938" }, { "name": "Java", "bytes": "1231693" }, { "name": "JavaScript", "bytes": "1767993" }, { "name": "Makefile", "bytes": "1047" }, { "name": "PLSQL", "bytes": "3450" }, { "name": "PLpgSQL", "bytes": "70798" }, { "name": "Perl", "bytes": "2614543" }, { "name": "Perl6", "bytes": "631229" }, { "name": "Python", "bytes": "11054" }, { "name": "Roff", "bytes": "4011" }, { "name": "Ruby", "bytes": "4090" }, { "name": "Shell", "bytes": "161675" } ], "symlink_target": "" }
<!DOCTYPE html> <html ng-app="blocTime"> <head lang="en"> <meta charset="UTF-8"> <title>Bloctime</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="/styles/normalize.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" type="text/css" href="/styles/style.css"> </head> <body ng-controller="TimerCtrl"> <ui-view></ui-view> <script src="https://www.gstatic.com/firebasejs/3.7.4/firebase.js"></script> <script> var config = { apiKey: "AIzaSyBobLX0PQiG8OcexEZTQE2KcWV53lWC-30", authDomain: "bloctime-69fb2.firebaseapp.com", databaseURL: "https://bloctime-69fb2.firebaseio.com", storageBucket: "bloctime-69fb2.appspot.com", messagingSenderId: "1042202248217" }; firebase.initializeApp(config); </script> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script> <script src="https://cdn.firebase.com/libs/angularfire/2.0.1/angularfire.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/buzz/1.1.0/buzz.min.js"></script> <script src="/scripts/app.js"></script> <script src="/scripts/controllers/TimerCtrl.js"></script> <script src="/scripts/filters/timecode.js"></script> <script src="/scripts/tasks.js"></script> </body> </html>
{ "content_hash": "405d63837f6e4b085d3ce1a4f2247af5", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 209, "avg_line_length": 42.65, "alnum_prop": 0.7063305978898007, "repo_name": "membrq/bloctime", "id": "037a8c1be9afe77b8de45bf7e6ee46420a61a629", "size": "1706", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dist/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "415" }, { "name": "HTML", "bytes": "3123" }, { "name": "JavaScript", "bytes": "7041" } ], "symlink_target": "" }
package org.apache.catalina.realm; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.security.cert.X509Certificate; import java.util.ArrayList; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.HttpRequest; import org.apache.catalina.HttpResponse; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleListener; import org.apache.catalina.Logger; import org.apache.catalina.Realm; import org.apache.catalina.core.ContainerBase; import org.apache.catalina.deploy.LoginConfig; import org.apache.catalina.deploy.SecurityConstraint; import org.apache.catalina.deploy.SecurityCollection; import org.apache.catalina.util.HexUtils; import org.apache.catalina.util.LifecycleSupport; import org.apache.catalina.util.MD5Encoder; import org.apache.catalina.util.StringManager; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.modeler.Registry; /** * Simple implementation of <b>Realm</b> that reads an XML file to configure * the valid users, passwords, and roles. The file format (and default file * location) are identical to those currently supported by Tomcat 3.X. * * @author Craig R. McClanahan * @version $Revision: 1.25 $ $Date: 2004/01/11 09:23:42 $ */ public abstract class RealmBase implements Lifecycle, Realm, MBeanRegistration { private static Log log = LogFactory.getLog(RealmBase.class); // ----------------------------------------------------- Instance Variables /** * The Container with which this Realm is associated. */ protected Container container = null; /** * The debugging detail level for this component. */ protected int debug = 0; /** * Digest algorithm used in storing passwords in a non-plaintext format. * Valid values are those accepted for the algorithm name by the * MessageDigest class, or <code>null</code> if no digesting should * be performed. */ protected String digest = null; /** * Descriptive information about this Realm implementation. */ protected static final String info = "org.apache.catalina.realm.RealmBase/1.0"; /** * The lifecycle event support for this component. */ protected LifecycleSupport lifecycle = new LifecycleSupport(this); /** * The MessageDigest object for digesting user credentials (passwords). */ protected MessageDigest md = null; /** * The MD5 helper object for this class. */ protected static final MD5Encoder md5Encoder = new MD5Encoder(); /** * MD5 message digest provider. */ protected static MessageDigest md5Helper; /** * The string manager for this package. */ protected static StringManager sm = StringManager.getManager(Constants.Package); /** * Has this component been started? */ protected boolean started = false; /** * The property change support for this component. */ protected PropertyChangeSupport support = new PropertyChangeSupport(this); /** * Should we validate client certificate chains when they are presented? */ protected boolean validate = true; // ------------------------------------------------------------- Properties /** * Return the Container with which this Realm has been associated. */ public Container getContainer() { return (container); } /** * Set the Container with which this Realm has been associated. * * @param container The associated Container */ public void setContainer(Container container) { Container oldContainer = this.container; this.container = container; support.firePropertyChange("container", oldContainer, this.container); } /** * Return the debugging detail level for this component. */ public int getDebug() { return (this.debug); } /** * Set the debugging detail level for this component. * * @param debug The new debugging detail level */ public void setDebug(int debug) { this.debug = debug; } /** * Return the digest algorithm used for storing credentials. */ public String getDigest() { return digest; } /** * Set the digest algorithm used for storing credentials. * * @param digest The new digest algorithm */ public void setDigest(String digest) { this.digest = digest; } /** * Return descriptive information about this Realm implementation and * the corresponding version number, in the format * <code>&lt;description&gt;/&lt;version&gt;</code>. */ public String getInfo() { return info; } /** * Return the "validate certificate chains" flag. */ public boolean getValidate() { return (this.validate); } /** * Set the "validate certificate chains" flag. * * @param validate The new validate certificate chains flag */ public void setValidate(boolean validate) { this.validate = validate; } // --------------------------------------------------------- Public Methods /** * Add a property change listener to this component. * * @param listener The listener to add */ public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } /** * Return the Principal associated with the specified username and * credentials, if there is one; otherwise return <code>null</code>. * * @param username Username of the Principal to look up * @param credentials Password or other credentials to use in * authenticating this username */ public Principal authenticate(String username, String credentials) { String serverCredentials = getPassword(username); if ( (serverCredentials == null) || (!serverCredentials.equals(credentials)) ) return null; return getPrincipal(username); } /** * Return the Principal associated with the specified username and * credentials, if there is one; otherwise return <code>null</code>. * * @param username Username of the Principal to look up * @param credentials Password or other credentials to use in * authenticating this username */ public Principal authenticate(String username, byte[] credentials) { return (authenticate(username, credentials.toString())); } /** * Return the Principal associated with the specified username, which * matches the digest calculated using the given parameters using the * method described in RFC 2069; otherwise return <code>null</code>. * * @param username Username of the Principal to look up * @param clientDigest Digest which has been submitted by the client * @param nOnce Unique (or supposedly unique) token which has been used * for this request * @param realm Realm name * @param md5a2 Second MD5 digest used to calculate the digest : * MD5(Method + ":" + uri) */ public Principal authenticate(String username, String clientDigest, String nOnce, String nc, String cnonce, String qop, String realm, String md5a2) { /* System.out.println("Digest : " + clientDigest); System.out.println("************ Digest info"); System.out.println("Username:" + username); System.out.println("ClientSigest:" + clientDigest); System.out.println("nOnce:" + nOnce); System.out.println("nc:" + nc); System.out.println("cnonce:" + cnonce); System.out.println("qop:" + qop); System.out.println("realm:" + realm); System.out.println("md5a2:" + md5a2); */ String md5a1 = getDigest(username, realm); if (md5a1 == null) return null; String serverDigestValue = md5a1 + ":" + nOnce + ":" + nc + ":" + cnonce + ":" + qop + ":" + md5a2; String serverDigest = md5Encoder.encode(md5Helper.digest(serverDigestValue.getBytes())); //System.out.println("Server digest : " + serverDigest); if (serverDigest.equals(clientDigest)) return getPrincipal(username); else return null; } /** * Return the Principal associated with the specified chain of X509 * client certificates. If there is none, return <code>null</code>. * * @param certs Array of client certificates, with the first one in * the array being the certificate of the client itself. */ public Principal authenticate(X509Certificate certs[]) { if ((certs == null) || (certs.length < 1)) return (null); // Check the validity of each certificate in the chain if (log.isDebugEnabled()) log.debug("Authenticating client certificate chain"); if (validate) { for (int i = 0; i < certs.length; i++) { if (log.isDebugEnabled()) log.debug(" Checking validity for '" + certs[i].getSubjectDN().getName() + "'"); try { certs[i].checkValidity(); } catch (Exception e) { if (log.isDebugEnabled()) log.debug(" Validity exception", e); return (null); } } } // Check the existence of the client Principal in our database return (getPrincipal(certs[0].getSubjectDN().getName())); } /** * Return the SecurityConstraints configured to guard the request URI for * this request, or <code>null</code> if there is no such constraint. * * @param request Request we are processing * @param context Context the Request is mapped to */ public SecurityConstraint [] findSecurityConstraints(HttpRequest request, Context context) { ArrayList results = null; // Are there any defined security constraints? SecurityConstraint constraints[] = context.findConstraints(); if ((constraints == null) || (constraints.length == 0)) { if (log.isDebugEnabled()) log.debug(" No applicable constraints defined"); return (null); } // Check each defined security constraint HttpServletRequest hreq = (HttpServletRequest) request.getRequest(); String uri = request.getRequestPathMB().toString(); String method = hreq.getMethod(); int i; boolean found = false; for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); if (log.isDebugEnabled()) log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); for(int k=0; k < patterns.length; k++) { if(uri.equals(patterns[k])) { found = true; if(collection[j].findMethod(method)) { if(results == null) { results = new ArrayList(); } results.add(constraints[i]); } } } } } if(found) { return resultsToArray(results); } int longest = -1; for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); if (log.isDebugEnabled()) log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); boolean matched = false; int length = -1; for(int k=0; k < patterns.length; k++) { String pattern = patterns[k]; if(pattern.startsWith("/") && pattern.endsWith("/*") && pattern.length() >= longest) { if(pattern.length() == 2) { matched = true; length = pattern.length(); } else if(pattern.regionMatches(0,uri,0, pattern.length()-2)) { matched = true; length = pattern.length(); } } } if(matched) { found = true; if(length > longest) { if(results != null) { results.clear(); } longest = length; } if(collection[j].findMethod(method)) { if(results == null) { results = new ArrayList(); } results.add(constraints[i]); } } } } if(found) { return resultsToArray(results); } for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); if (log.isDebugEnabled()) log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); boolean matched = false; int pos = -1; for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); for(int k=0; k < patterns.length && !matched; k++) { String pattern = patterns[k]; if(pattern.startsWith("*.")){ int slash = uri.lastIndexOf("/"); int dot = uri.lastIndexOf("."); if(slash >= 0 && dot > slash && dot != uri.length()-1 && uri.length()-dot == pattern.length()-1) { if(pattern.regionMatches(1,uri,dot,uri.length()-dot)) { matched = true; pos = j; } } } } } if(matched) { found = true; if(collection[pos].findMethod(method)) { if(results == null) { results = new ArrayList(); } results.add(constraints[i]); } } } if(found) { return resultsToArray(results); } for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); if (log.isDebugEnabled()) log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); boolean matched = false; for(int k=0; k < patterns.length && !matched; k++) { String pattern = patterns[k]; if(pattern.equals("/")){ matched = true; } } if(matched) { if(results == null) { results = new ArrayList(); } results.add(constraints[i]); } } } if(results == null) { // No applicable security constraint was found if (log.isDebugEnabled()) log.debug(" No applicable constraint located"); } return resultsToArray(results); } /** * Convert an ArrayList to a SecurityContraint []. */ private SecurityConstraint [] resultsToArray(ArrayList results) { if(results == null) { return null; } SecurityConstraint [] array = new SecurityConstraint[results.size()]; results.toArray(array); return array; } /** * Perform access control based on the specified authorization constraint. * Return <code>true</code> if this constraint is satisfied and processing * should continue, or <code>false</code> otherwise. * * @param request Request we are processing * @param response Response we are creating * @param constraint Security constraint we are enforcing * @param The Context to which client of this class is attached. * * @exception IOException if an input/output error occurs */ public boolean hasResourcePermission(HttpRequest request, HttpResponse response, SecurityConstraint []constraints, Context context) throws IOException { if (constraints == null || constraints.length == 0) return (true); // Specifically allow access to the form login and form error pages // and the "j_security_check" action LoginConfig config = context.getLoginConfig(); if ((config != null) && (Constants.FORM_METHOD.equals(config.getAuthMethod()))) { String requestURI = request.getDecodedRequestURI(); String loginPage = context.getPath() + config.getLoginPage(); if (loginPage.equals(requestURI)) { if (log.isDebugEnabled()) log.debug(" Allow access to login page " + loginPage); return (true); } String errorPage = context.getPath() + config.getErrorPage(); if (errorPage.equals(requestURI)) { if (log.isDebugEnabled()) log.debug(" Allow access to error page " + errorPage); return (true); } if (requestURI.endsWith(Constants.FORM_ACTION)) { if (log.isDebugEnabled()) log.debug(" Allow access to username/password submission"); return (true); } } // Which user principal have we already authenticated? Principal principal = ((HttpServletRequest) request.getRequest()).getUserPrincipal(); for(int i=0; i < constraints.length; i++) { SecurityConstraint constraint = constraints[i]; String roles[] = constraint.findAuthRoles(); if (roles == null) roles = new String[0]; if (constraint.getAllRoles()) return (true); if (log.isDebugEnabled()) log.debug(" Checking roles " + principal); if (roles.length == 0) { if(constraint.getAuthConstraint()) { ((HttpServletResponse) response.getResponse()).sendError (HttpServletResponse.SC_FORBIDDEN, sm.getString("realmBase.forbidden")); if( log.isDebugEnabled() ) log.debug("No roles "); return (false); // No listed roles means no access at all } else { log.debug("Passing all access"); return (true); } } else if (principal == null) { if (log.isDebugEnabled()) log.debug(" No user authenticated, cannot grant access"); ((HttpServletResponse) response.getResponse()).sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("realmBase.notAuthenticated")); return (false); } for (int j = 0; j < roles.length; j++) { if (hasRole(principal, roles[j])) return (true); if( log.isDebugEnabled() ) log.debug( "No role found: " + roles[j]); } } // Return a "Forbidden" message denying access to this resource ((HttpServletResponse) response.getResponse()).sendError (HttpServletResponse.SC_FORBIDDEN, sm.getString("realmBase.forbidden")); return (false); } /** * Return <code>true</code> if the specified Principal has the specified * security role, within the context of this Realm; otherwise return * <code>false</code>. This method can be overridden by Realm * implementations, but the default is adequate when an instance of * <code>GenericPrincipal</code> is used to represent authenticated * Principals from this Realm. * * @param principal Principal for whom the role is to be checked * @param role Security role to be checked */ public boolean hasRole(Principal principal, String role) { // Should be overriten in JAASRealm - to avoid pretty inefficient conversions if ((principal == null) || (role == null) || !(principal instanceof GenericPrincipal)) return (false); GenericPrincipal gp = (GenericPrincipal) principal; if (!(gp.getRealm() == this)) { log.debug("Different realm " + this + " " + gp.getRealm());// return (false); } boolean result = gp.hasRole(role); if (log.isDebugEnabled()) { String name = principal.getName(); if (result) log.debug(sm.getString("realmBase.hasRoleSuccess", name, role)); else log.debug(sm.getString("realmBase.hasRoleFailure", name, role)); } return (result); } /** * Enforce any user data constraint required by the security constraint * guarding this request URI. Return <code>true</code> if this constraint * was not violated and processing should continue, or <code>false</code> * if we have created a response already. * * @param request Request we are processing * @param response Response we are creating * @param constraint Security constraint being checked * * @exception IOException if an input/output error occurs */ public boolean hasUserDataPermission(HttpRequest request, HttpResponse response, SecurityConstraint []constraints) throws IOException { // Is there a relevant user data constraint? if (constraints == null || constraints.length == 0) { if (log.isDebugEnabled()) log.debug(" No applicable security constraint defined"); return (true); } for(int i=0; i < constraints.length; i++) { SecurityConstraint constraint = constraints[i]; String userConstraint = constraint.getUserConstraint(); if (userConstraint == null) { if (log.isDebugEnabled()) log.debug(" No applicable user data constraint defined"); return (true); } if (userConstraint.equals(Constants.NONE_TRANSPORT)) { if (log.isDebugEnabled()) log.debug(" User data constraint has no restrictions"); return (true); } } // Validate the request against the user data constraint if (request.getRequest().isSecure()) { if (log.isDebugEnabled()) log.debug(" User data constraint already satisfied"); return (true); } // Initialize variables we need to determine the appropriate action HttpServletRequest hrequest = (HttpServletRequest) request.getRequest(); HttpServletResponse hresponse = (HttpServletResponse) response.getResponse(); int redirectPort = request.getConnector().getRedirectPort(); // Is redirecting disabled? if (redirectPort <= 0) { if (log.isDebugEnabled()) log.debug(" SSL redirect is disabled"); hresponse.sendError (HttpServletResponse.SC_FORBIDDEN, hrequest.getRequestURI()); return (false); } // Redirect to the corresponding SSL port StringBuffer file = new StringBuffer(); String protocol = "https"; String host = hrequest.getServerName(); // Protocol file.append(protocol).append("://"); // Host with port file.append(host).append(":").append(redirectPort); // URI file.append(hrequest.getRequestURI()); String requestedSessionId = hrequest.getRequestedSessionId(); if ((requestedSessionId != null) && hrequest.isRequestedSessionIdFromURL()) { file.append(";jsessionid="); file.append(requestedSessionId); } String queryString = hrequest.getQueryString(); if (queryString != null) { file.append('?'); file.append(queryString); } if (log.isDebugEnabled()) log.debug(" Redirecting to " + file.toString()); hresponse.sendRedirect(file.toString()); return (false); } /** * Remove a property change listener from this component. * * @param listener The listener to remove */ public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } // ------------------------------------------------------ Lifecycle Methods /** * Add a lifecycle event listener to this component. * * @param listener The listener to add */ public void addLifecycleListener(LifecycleListener listener) { lifecycle.addLifecycleListener(listener); } /** * Get the lifecycle listeners associated with this lifecycle. If this * Lifecycle has no listeners registered, a zero-length array is returned. */ public LifecycleListener[] findLifecycleListeners() { return lifecycle.findLifecycleListeners(); } /** * Remove a lifecycle event listener from this component. * * @param listener The listener to remove */ public void removeLifecycleListener(LifecycleListener listener) { lifecycle.removeLifecycleListener(listener); } /** * Prepare for the beginning of active use of the public methods of this * component. This method should be called before any of the public * methods of this component are utilized. It should also send a * LifecycleEvent of type START_EVENT to any registered listeners. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ public void start() throws LifecycleException { // Validate and update our current component state if (started) { log.info(sm.getString("realmBase.alreadyStarted")); return; } if( !initialized ) { init(); } lifecycle.fireLifecycleEvent(START_EVENT, null); started = true; // Create a MessageDigest instance for credentials, if desired if (digest != null) { try { md = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); } } } /** * Gracefully terminate the active use of the public methods of this * component. This method should be the last one called on a given * instance of this component. It should also send a LifecycleEvent * of type STOP_EVENT to any registered listeners. * * @exception LifecycleException if this component detects a fatal error * that needs to be reported */ public void stop() throws LifecycleException { // Validate and update our current component state if (!started) { log.info(sm.getString("realmBase.notStarted")); return; } lifecycle.fireLifecycleEvent(STOP_EVENT, null); started = false; // Clean up allocated resources md = null; destroy(); } public void destroy() { // unregister this realm if ( oname!=null ) { try { Registry.getRegistry().unregisterComponent(oname); log.debug( "unregistering realm " + oname ); } catch( Exception ex ) { log.error( "Can't unregister realm " + oname, ex); } } } // ------------------------------------------------------ Protected Methods /** * Digest the password using the specified algorithm and * convert the result to a corresponding hexadecimal string. * If exception, the plain credentials string is returned. * * <strong>IMPLEMENTATION NOTE</strong> - This implementation is * synchronized because it reuses the MessageDigest instance. * This should be faster than cloning the instance on every request. * * @param credentials Password or other credentials to use in * authenticating this username */ protected String digest(String credentials) { // If no MessageDigest instance is specified, return unchanged if (hasMessageDigest() == false) return (credentials); // Digest the user credentials and return as hexadecimal synchronized (this) { try { md.reset(); md.update(credentials.getBytes()); return (HexUtils.convert(md.digest())); } catch (Exception e) { log.error(sm.getString("realmBase.digest"), e); return (credentials); } } } protected boolean hasMessageDigest() { return !(md == null); } /** * Return the digest associated with given principal's user name. */ protected String getDigest(String username, String realmName) { if (md5Helper == null) { try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); } } String digestValue = username + ":" + realmName + ":" + getPassword(username); byte[] digest = md5Helper.digest(digestValue.getBytes()); return md5Encoder.encode(digest); } /** * Return a short name for this Realm implementation, for use in * log messages. */ protected abstract String getName(); /** * Return the password associated with the given principal's user name. */ protected abstract String getPassword(String username); /** * Return the Principal associated with the given user name. */ protected abstract Principal getPrincipal(String username); /** * Log a message on the Logger associated with our Container (if any) * * @param message Message to be logged */ protected void log(String message) { Logger logger = null; String name = null; if (container != null) { logger = container.getLogger(); name = container.getName(); } if (logger != null) { logger.log(getName()+"[" + name + "]: " + message); } else { System.out.println(getName()+"[" + name + "]: " + message); } } /** * Log a message on the Logger associated with our Container (if any) * * @param message Message to be logged * @param throwable Associated exception */ protected void log(String message, Throwable throwable) { Logger logger = null; String name = null; if (container != null) { logger = container.getLogger(); name = container.getName(); } if (logger != null) { logger.log(getName()+"[" + name + "]: " + message, throwable); } else { System.out.println(getName()+"[" + name + "]: " + message); throwable.printStackTrace(System.out); } } // --------------------------------------------------------- Static Methods /** * Digest password using the algorithm especificied and * convert the result to a corresponding hex string. * If exception, the plain credentials string is returned * * @param credentials Password or other credentials to use in * authenticating this username * @param algorithm Algorithm used to do th digest */ public final static String Digest(String credentials, String algorithm) { try { // Obtain a new message digest with "digest" encryption MessageDigest md = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); // encode the credentials md.update(credentials.getBytes()); // Digest the credentials and return as hexadecimal return (HexUtils.convert(md.digest())); } catch(Exception ex) { ex.printStackTrace(); return credentials; } } /** * Digest password using the algorithm especificied and * convert the result to a corresponding hex string. * If exception, the plain credentials string is returned */ public static void main(String args[]) { if(args.length > 2 && args[0].equalsIgnoreCase("-a")) { for(int i=2; i < args.length ; i++){ System.out.print(args[i]+":"); System.out.println(Digest(args[i], args[1])); } } else { System.out.println ("Usage: RealmBase -a <algorithm> <credentials>"); } } // -------------------- JMX and Registration -------------------- protected String type; protected String domain; protected String host; protected String path; protected ObjectName oname; protected ObjectName controller; protected MBeanServer mserver; public ObjectName getController() { return controller; } public void setController(ObjectName controller) { this.controller = controller; } public ObjectName getObjectName() { return oname; } public String getDomain() { return domain; } public String getType() { return type; } public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { oname=name; mserver=server; domain=name.getDomain(); type=name.getKeyProperty("type"); host=name.getKeyProperty("host"); path=name.getKeyProperty("path"); return name; } public void postRegister(Boolean registrationDone) { } public void preDeregister() throws Exception { } public void postDeregister() { } protected boolean initialized=false; public void init() { if( initialized && container != null ) return; initialized=true; if( container== null ) { ObjectName parent=null; // Register with the parent try { if( host == null ) { // global parent=new ObjectName(domain +":type=Engine"); } else if( path==null ) { parent=new ObjectName(domain + ":type=Host,host=" + host); } else { parent=new ObjectName(domain +":j2eeType=WebModule,name=//" + host + path); } if( mserver.isRegistered(parent )) { log.debug("Register with " + parent); mserver.invoke(parent, "setRealm", new Object[] {this}, new String[] {"org.apache.catalina.Realm"}); } } catch (Exception e) { log.info("Parent not available yet: " + parent); } } if( oname==null ) { // register try { ContainerBase cb=(ContainerBase)container; oname=new ObjectName(cb.getDomain()+":type=Realm" + cb.getContainerSuffix()); Registry.getRegistry().registerComponent(this, oname, null ); log.debug("Register Realm "+oname); } catch (Throwable e) { log.error( "Can't register " + oname, e); } } } }
{ "content_hash": "64ae68698f8f27f291baaa11776b049e", "timestamp": "", "source": "github", "line_count": 1187, "max_line_length": 93, "avg_line_length": 32.6301600673968, "alnum_prop": 0.5500103273778788, "repo_name": "devjin24/howtomcatworks", "id": "5168d9f4906ba2be4ecd17510003994abd2ecbfc", "size": "41652", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bookrefer/jakarta-tomcat-5.0.18-src/jakarta-tomcat-catalina/catalina/src/share/org/apache/catalina/realm/RealmBase.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "52224" }, { "name": "C", "bytes": "2123859" }, { "name": "C++", "bytes": "5454" }, { "name": "CSS", "bytes": "4762" }, { "name": "HTML", "bytes": "232523" }, { "name": "Java", "bytes": "25349050" }, { "name": "Makefile", "bytes": "2331" }, { "name": "NSIS", "bytes": "25933" }, { "name": "Perl", "bytes": "100975" }, { "name": "Shell", "bytes": "49871" }, { "name": "Visual Basic", "bytes": "9998" }, { "name": "XSLT", "bytes": "27566" } ], "symlink_target": "" }
@interface TWTMenuViewController : UIViewController @end
{ "content_hash": "62aa4694dd82eabd2360581fd7501949", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 51, "avg_line_length": 19.333333333333332, "alnum_prop": 0.8448275862068966, "repo_name": "wangwei1237/TWTSideMenuViewController", "id": "eac6260a85f4853c937e9517b883c307088d0012", "size": "256", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "TWTSideMenuViewController-Sample/TWTMenuViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "30789" }, { "name": "Ruby", "bytes": "1694" } ], "symlink_target": "" }
define([], function() { var spec = { id: "Table", name: "databound.Table", requireName: "databoundtable", fullComponentName: "org.scn.community.databound.Table", fullComponentPackage: "org.scn.community.databound/res/Table", script: "org.scn.community.databound/res/Table/Table", scriptSpec: "org.scn.community.databound/res/Table/TableSpec", min: false }; spec.spec = { "column1": { "opts": { "apsControl": "text", "cat": "DataBinding", "desc": "Column 1", "noAps": false, "noZtl": false, "tooltip": "Column 1", "ztlFunction": "", "ztlType": "ResultCellList" }, "template": "default", "type": "ResultCellList", "value": "", "visible": true }, "column2": { "opts": { "apsControl": "text", "cat": "DataBinding", "desc": "Column 2", "noAps": false, "noZtl": false, "tooltip": "Column 2", "ztlFunction": "", "ztlType": "ResultCellList" }, "template": "default", "type": "ResultCellList", "value": "", "visible": true }, "column3": { "opts": { "apsControl": "text", "cat": "DataBinding", "desc": "Column 3", "noAps": false, "noZtl": false, "tooltip": "Column 3", "ztlFunction": "", "ztlType": "ResultCellList" }, "template": "default", "type": "ResultCellList", "value": "", "visible": true }, "data": { "opts": { "apsControl": "text", "cat": "DataBinding", "desc": "Column 1", "noAps": true, "noZtl": true, "tooltip": "Column 1", "ztlFunction": "", "ztlType": "ResultCellList" }, "template": "default", "type": "ResultCellList", "value": "", "visible": false } }; spec.specInclude = {}; spec.specAbout = { "description": "Data Table", "icon": "Table.png", "title": "Data Table 2.0", "topics": [ { "content": "Data Table", "title": "Data Table" }, { "content": "This component is a visualization component. It requires specific space in the application canvas.", "title": "Visualization" } ] }; spec.specComp = { "databound": true, "extension": "Component", "group": "ScnCommunityVisualizations", "handlerType": "div", "height": "400", "id": "Table", "package": "databound", "parentControl": "sap.zen.commons.layout.AbsoluteLayout", "require": [{ "id": "common_basics", "space": "known" }], "title": "Data Table 2.0", "tooltip": "Data Table", "width": "400" }; return spec; });// End of closure
{ "content_hash": "c182f3bd0667f890b3d49f993844685b", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 118, "avg_line_length": 21.072580645161292, "alnum_prop": 0.5411404515882128, "repo_name": "org-scn-design-studio-community/sdkpackage", "id": "a976d84539c552a7aed3c89f7548c8c1d4ecc971", "size": "3338", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/org.scn.community.databound/res/Table/TableSpec.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "26655" }, { "name": "CSS", "bytes": "2531803" }, { "name": "HTML", "bytes": "152298" }, { "name": "JavaScript", "bytes": "13255138" }, { "name": "XSLT", "bytes": "552" } ], "symlink_target": "" }
import {Upload} from '../../../contracts/entities'; import {ActionType} from '../../../contracts/enums'; const actions = { update: ActionType.UPLOAD_UPDATE_SUCCESS, remove: ActionType.UPLOAD_DELETE_SUCCESS, list: ActionType.UPLOAD_LIST_SUCCESS, }; import Dispatcher from './dispatcher'; import IndexedStore from '../indexed_store'; export default class UploadeStore extends Dispatcher { constructor() { super(actions); this.indexed = new IndexedStore(); } reset() { return this.indexed.reset('Uploads'); } close() { return this.indexed.close('Uploads'); } create(value) { return this.indexed.create('Uploads', value) .then(data => new Upload(data)); } subscribe(dispatch) { const unsubscribe = super.subscribe(dispatch); this.list(); // initial data load return unsubscribe; } update(value) { return this.indexed.update('Uploads', value) .then(data => new Upload(data)); } remove(value) { return this.indexed.remove('Uploads', value.id); } get(id) { return this.indexed.get('Uploads', id) .then(data => data && new Upload(data)); } list() { return this.indexed.list('Uploads') .then(data => data.map(item => new Upload(item))); } find(criterion) { const [key] = Object.keys(criterion); const [value] = Object.values(criterion); return this.indexed.getMany('Uploads', key, value) .then(data => data.map(item => new Upload(item))); } findOne(criterion) { const [key] = Object.keys(criterion); const [value] = Object.values(criterion); return this.indexed.findBy('Uploads', key, value) .then(data => data && new Upload(data)); } }
{ "content_hash": "0a160b75931e0b8fbf1fb741972d9d05", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 56, "avg_line_length": 23.625, "alnum_prop": 0.6390358612580834, "repo_name": "o-evin/glacier-console", "id": "ac2338a41c2ac9e0263b9e057c60451b6aee45f7", "size": "1701", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/main/storage/typed/upload_store.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8352" }, { "name": "HTML", "bytes": "235" }, { "name": "JavaScript", "bytes": "231326" }, { "name": "Shell", "bytes": "939" } ], "symlink_target": "" }
package org.piraso.api.entry; import java.io.PrintStream; /** * Defines an exception entry. */ public class ThrowableEntry extends Entry { private String message; private String actualToString; private ThrowableEntry cause; private StackTraceElementEntry[] stackTrace; public ThrowableEntry() {} public ThrowableEntry(Throwable e) { actualToString = e.toString(); message = e.getMessage(); StackTraceElement[] elements = e.getStackTrace(); stackTrace = new StackTraceElementEntry[elements.length]; for(int i = 0; i < elements.length; i++) { stackTrace[i] = new StackTraceElementEntry(elements[i]); } if(e.getCause() != null) { cause = new ThrowableEntry(e.getCause()); } } public StackTraceElementEntry[] getStackTrace() { return stackTrace; } public void setStackTrace(StackTraceElementEntry[] stackTrace) { this.stackTrace = stackTrace; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public ThrowableEntry getCause() { return cause; } public void setCause(ThrowableEntry cause) { this.cause = cause; } public String getActualToString() { return actualToString; } public void setActualToString(String actualToString) { this.actualToString = actualToString; } /** * Prints this throwable and its backtrace to the specified print stream. * * @param s <code>PrintStream</code> to use for output */ public void printStackTrace(PrintStream s) { synchronized (s) { s.println(actualToString); StackTraceElementEntry[] trace = getStackTrace(); for (StackTraceElementEntry aTrace : trace) { s.println("\tat " + aTrace); } ThrowableEntry ourCause = getCause(); if (ourCause != null) ourCause.printStackTraceAsCause(s, trace); } } /** * Print our stack trace as a cause for the specified stack trace. * * @param s the print stream * @param causedTrace the base stack trace */ private void printStackTraceAsCause(PrintStream s, StackTraceElementEntry[] causedTrace) { StackTraceElementEntry[] trace = getStackTrace(); int m = trace.length - 1, n = causedTrace.length - 1; while (m >= 0 && n >= 0 && trace[m].equals(causedTrace[n])) { m--; n--; } int framesInCommon = trace.length - 1 - m; s.println("Caused by: " + actualToString); for (int i = 0; i <= m; i++) { s.println("\tat " + trace[i]); } if (framesInCommon != 0) { s.println("\t... " + framesInCommon + " more"); } ThrowableEntry ourCause = getCause(); if (ourCause != null) { ourCause.printStackTraceAsCause(s, trace); } } @Override public String toString() { String s = getClass().getName(); String message = getMessage(); return (message != null) ? (s + ": " + message) : s; } }
{ "content_hash": "228b6be0ab719e721fca8dfbafbdf9e7", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 79, "avg_line_length": 25.8828125, "alnum_prop": 0.5731964986417145, "repo_name": "piraso/piraso", "id": "112e2b7098618cab9a44264ceee75edbb51efd97", "size": "4087", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "context-logger/api/src/main/java/org/piraso/api/entry/ThrowableEntry.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "72264" }, { "name": "Java", "bytes": "703739" }, { "name": "JavaScript", "bytes": "3956" } ], "symlink_target": "" }
"use strict"; 'use stricts'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Attachment = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _fs = require("fs"); var _fs2 = _interopRequireDefault(_fs); var _nodeNativeZip = require("node-native-zip"); var _nodeNativeZip2 = _interopRequireDefault(_nodeNativeZip); var _lodash = require("lodash"); var _lodash2 = _interopRequireDefault(_lodash); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Attachment = exports.Attachment = function () { function Attachment() { _classCallCheck(this, Attachment); } _createClass(Attachment, [{ key: "buildText", /** * Convert string to base64 * @param {*} data */ value: function buildText(data) { return new Buffer(data, 'utf8').toString('base64'); } /** * Convert list string to zip stream * @param {*} failures an array with fields: name, and message */ }, { key: "buildZip", value: function buildZip(failures) { var archive = new _nodeNativeZip2.default(); _lodash2.default.each(failures, function (item) { archive.add(item.name + ".txt", new Buffer(item.message, "utf8")); }); return archive.toBuffer().toString('base64'); } }]); return Attachment; }();
{ "content_hash": "72e9d425ff7c36802f06d4e2b129ce37", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 564, "avg_line_length": 34.49152542372882, "alnum_prop": 0.6776412776412777, "repo_name": "gunivan/log2qtest", "id": "8cf412e0cc56b44f93b3aaf1aa0c5bf117c3b3da", "size": "2035", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bin/attachment.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "53322" } ], "symlink_target": "" }
<?php namespace Magento\SalesRule\Model\ResourceModel\Coupon; use Magento\Backend\Block\Widget\Grid\Column; use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; use Magento\SalesRule\Model\Rule; /** * SalesRule Model Resource Coupon_Collection * * @author Magento Core Team <core@magentocommerce.com> */ class Collection extends AbstractCollection { /** * Constructor * * @return void */ protected function _construct() { parent::_construct(); $this->_init('Magento\SalesRule\Model\Coupon', 'Magento\SalesRule\Model\ResourceModel\Coupon'); } /** * Add rule to filter * * @param Rule|int $rule * @return $this */ public function addRuleToFilter($rule) { if ($rule instanceof Rule) { $ruleId = $rule->getId(); } else { $ruleId = (int)$rule; } $this->addFieldToFilter('rule_id', $ruleId); return $this; } /** * Add rule IDs to filter * * @param array $ruleIds * @return $this */ public function addRuleIdsToFilter(array $ruleIds) { $this->addFieldToFilter('rule_id', ['in' => $ruleIds]); return $this; } /** * Filter collection to be filled with auto-generated coupons only * * @return $this */ public function addGeneratedCouponsFilter() { $this->addFieldToFilter('is_primary', ['null' => 1])->addFieldToFilter('type', '1'); return $this; } /** * Callback function that filters collection by field "Used" from grid * * @param AbstractCollection $collection * @param Column $column * @return void */ public function addIsUsedFilterCallback($collection, $column) { $filterValue = $column->getFilter()->getCondition(); $expression = $this->getConnection()->getCheckSql('main_table.times_used > 0', 1, 0); $conditionSql = $this->_getConditionSql($expression, $filterValue); $collection->getSelect()->where($conditionSql); } }
{ "content_hash": "8726e34569cdbd0ac4bd567286f59d9f", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 103, "avg_line_length": 25.071428571428573, "alnum_prop": 0.6016144349477682, "repo_name": "enettolima/magento-training", "id": "5610ae773e93bd123886b2028b3786c75acd98a5", "size": "2204", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "magento2ce/app/code/Magento/SalesRule/Model/ResourceModel/Coupon/Collection.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "22648" }, { "name": "CSS", "bytes": "3382928" }, { "name": "HTML", "bytes": "8749335" }, { "name": "JavaScript", "bytes": "7355635" }, { "name": "PHP", "bytes": "58607662" }, { "name": "Perl", "bytes": "10258" }, { "name": "Shell", "bytes": "41887" }, { "name": "XSLT", "bytes": "19889" } ], "symlink_target": "" }
<?php namespace Drupal\sw\Plugin\Filter; use Drupal\Component\Utility\Html; use Drupal\Component\Utility\Unicode; use Drupal\Component\Utility\Xss; use Drupal\filter\FilterProcessResult; use Drupal\filter\Plugin\FilterBase; use Drupal\filter\Render\FilteredMarkup; /** * Provides a filter to caption elements. * * When used in combination with the filter_align filter, this must run last. * * This code is copied from the core FilterCaption plugin, but has logic to * handle a special case where the caption is set to "default". In that case, * we find the entity_id of the thing being embedded, and call a helper * function to get the appropriate caption to use. * * @Filter( * id = "sw_filter_caption", * title = @Translation("Caption SW images"), * description = @Translation("Uses a <code>data-caption</code> attribute on <code>&lt;img&gt;</code> tags to caption images."), * type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE * ) */ class SWFilterCaption extends FilterBase { /** * {@inheritdoc} */ public function process($text, $langcode) { $result = new FilterProcessResult($text); if (stristr($text, 'data-caption') !== FALSE) { $dom = Html::load($text); $xpath = new \DOMXPath($dom); foreach ($xpath->query('//*[@data-caption]') as $node) { // Read the data-caption attribute's value, then delete it. $caption = $node->getAttribute('data-caption'); $node->removeAttribute('data-caption'); // If the caption is set to "default", pull the caption from the entity. if ($caption === 'default') { $entity_id = $node->getAttribute('data-entity-id'); $caption = sw_get_media_caption($entity_id); $node->removeAttribute('data-entity-id'); } $caption = Html::escape($caption); // Sanitize caption: decode HTML encoding, limit allowed HTML tags; only // allow inline tags that are allowed by default, plus <br>. $caption = Html::decodeEntities($caption); $caption = FilteredMarkup::create(Xss::filter($caption, ['a', 'em', 'strong', 'cite', 'code', 'br'])); // The caption must be non-empty. if (Unicode::strlen($caption) === 0) { continue; } // Given the updated node and caption: re-render it with a caption, but // bubble up the value of the class attribute of the captioned element, // this allows it to collaborate with e.g. the filter_align filter. $tag = $node->tagName; $classes = $node->getAttribute('class'); $node->removeAttribute('class'); $node = ($node->parentNode->tagName === 'a') ? $node->parentNode : $node; $filter_caption = [ '#theme' => 'filter_caption', // We pass the unsanitized string because this is a text format // filter, and after filtering, we always assume the output is safe. // @see \Drupal\filter\Element\ProcessedText::preRenderText() '#node' => FilteredMarkup::create($node->C14N()), '#tag' => $tag, '#caption' => $caption, '#classes' => $classes, ]; $altered_html = \Drupal::service('renderer')->render($filter_caption); // Load the altered HTML into a new DOMDocument and retrieve the element. $updated_nodes = Html::load($altered_html)->getElementsByTagName('body') ->item(0) ->childNodes; foreach ($updated_nodes as $updated_node) { // Import the updated node from the new DOMDocument into the original // one, importing also the child nodes of the updated node. $updated_node = $dom->importNode($updated_node, TRUE); $node->parentNode->insertBefore($updated_node, $node); } // Finally, remove the original data-caption node. $node->parentNode->removeChild($node); } $result->setProcessedText(Html::serialize($dom)) ->addAttachments([ 'library' => [ 'filter/caption', ], ]); } return $result; } /** * {@inheritdoc} */ public function tips($long = FALSE) { if ($long) { return $this->t(' <p>You can caption images, videos, blockquotes, and so on. Examples:</p> <ul> <li><code>&lt;img src="" data-caption="This is an img caption" /&gt;</code></li> <li><code>&lt;video src="" data-caption="This is a video caption" /&gt;</code></li> <li><code>&lt;blockquote data-caption="Alan Maass"&gt;SocialistWorker.org is so great!&lt;/blockquote&gt;</code></li> <li><code>&lt;drupal-entity data-entity-id="1234" data-caption="Something custom for this entity"&gt;&lt;/drupal-entity&gt;</code></li> <li><code>&lt;drupal-entity data-entity-id="2345" data-caption="default"&gt;&lt;/drupal-entity&gt;</code> (looks up the caption from the referenced entity</li> </ul>'); } else { return $this->t('You can caption images (<code>data-caption="Text"</code>), but also videos, blockquotes, and so on.'); } } }
{ "content_hash": "a50782868b88c624fff4f2a42986faf8", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 171, "avg_line_length": 39.83720930232558, "alnum_prop": 0.6143218525004864, "repo_name": "ISO-tech/sw-d8", "id": "7fd156a541e5edf70c832b4d18c5b59a23669a38", "size": "5139", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/modules/custom/sw/src/Plugin/Filter/SWFilterCaption.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "30677" }, { "name": "Gherkin", "bytes": "3374" }, { "name": "HTML", "bytes": "269460" }, { "name": "Hack", "bytes": "35936" }, { "name": "JavaScript", "bytes": "104527" }, { "name": "PHP", "bytes": "53430607" }, { "name": "SCSS", "bytes": "50217" }, { "name": "Shell", "bytes": "8234" }, { "name": "Twig", "bytes": "57403" } ], "symlink_target": "" }
package com.coolweather.android.gson; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by wanlongping on 2017/10/16. */ public class Weather { public String status; public Basic basic; public AQI aqi; public Now now; public Suggestion suggestion; @SerializedName("daily_forecast") public List<Forecast> forecasts; }
{ "content_hash": "23caf35399e64b4bc1becdb2f9267759", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 50, "avg_line_length": 15.384615384615385, "alnum_prop": 0.7, "repo_name": "wanlongping/coolweather1", "id": "35ea8d11aeb1a7911e8f7ecf8533c2305f2363b6", "size": "400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/coolweather/android/gson/Weather.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "33619" } ], "symlink_target": "" }
// This file contains the image codec operations for PNG files. #include <fstream> #include "core/cross/bitmap.h" #include "core/cross/error.h" #include "core/cross/types.h" #include "utils/cross/file_path_utils.h" #include "base/file_path.h" #include "base/file_util.h" #include "import/cross/memory_buffer.h" #include "import/cross/memory_stream.h" #include "png.h" #include "utils/cross/dataurl.h" using file_util::OpenFile; using file_util::CloseFile; namespace o3d { namespace { // Helper function for LoadFromPNGFile that converts a stream into the // necessary abstract byte reading function. void StreamReadData(png_structp png_ptr, png_bytep data, png_size_t length) { MemoryReadStream *stream = static_cast<MemoryReadStream*>(png_get_io_ptr(png_ptr)); stream->Read(data, length); } // Helper function for ToDataURL that converts a stream into the necessary // abstract byte writing function. void StreamWriteData(png_structp png_ptr, png_bytep data, png_size_t length) { std::vector<uint8>* stream = static_cast<std::vector<uint8>*>(png_get_io_ptr(png_ptr)); stream->insert(stream->end(), static_cast<uint8*>(data), static_cast<uint8*>(data) + length); } // Because libpng requires a flush function according to the docs. void StreamFlush(png_structp png_ptr) { } } // anonymous namespace // Loads the raw RGB data from a compressed PNG file. bool Bitmap::LoadFromPNGStream(ServiceLocator* service_locator, MemoryReadStream *stream, const String &filename, BitmapRefArray* bitmaps) { DCHECK(bitmaps); // Read the magic header. char magic[4]; size_t bytes_read = stream->Read(magic, sizeof(magic)); if (bytes_read != sizeof(magic)) { DLOG(ERROR) << "PNG file magic header not loaded \"" << filename << "\""; return false; } // Match the magic header to check that this is a PNG file. if (png_sig_cmp(reinterpret_cast<png_bytep>(magic), 0, sizeof(magic)) != 0) { DLOG(ERROR) << "File is not a PNG file \"" << filename << "\""; return false; } // Load the rest of the PNG file ---------------- png_structp png_ptr = NULL; png_infop info_ptr = NULL; // create the PNG structure (not providing user error functions). png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, // user_error_ptr NULL, // user_error_fn NULL); // user_warning_fn if (png_ptr == NULL) return 0; // Allocate memory for image information info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { png_destroy_read_struct(&png_ptr, png_infopp_NULL, png_infopp_NULL); DLOG(ERROR) << "Cannot allocate working memory for PNG load."; return false; } // NOTE: The following smart pointer needs to be declared before the // setjmp so that it is properly destroyed if we jump back. scoped_array<uint8> image_data; png_bytepp row_pointers = NULL; // Set error handling if you are using the setjmp/longjmp method. If any // error happens in the following code, we will return here to handle the // error. if (setjmp(png_jmpbuf(png_ptr))) { // If we reach here, a fatal error occurred so free memory and exit. DLOG(ERROR) << "Fatal error reading PNG file \"" << filename << "\""; if (row_pointers) png_free(png_ptr, row_pointers); png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL); return false; } // Set up our STL stream input control png_set_read_fn(png_ptr, stream, &StreamReadData); // We have already read some of the signature, advance the pointer. png_set_sig_bytes(png_ptr, sizeof(magic)); // Read the PNG header information. png_uint_32 png_width = 0; png_uint_32 png_height = 0; int png_color_type = 0; int png_interlace_type = 0; int png_bits_per_channel = 0; png_read_info(png_ptr, info_ptr); png_get_IHDR(png_ptr, info_ptr, &png_width, &png_height, &png_bits_per_channel, &png_color_type, &png_interlace_type, NULL, NULL); if (!image::CheckImageDimensions(png_width, png_height)) { DLOG(ERROR) << "Failed to load " << filename << ": dimensions are too large (" << png_width << ", " << png_height << ")."; // Use the png error system to clean up and exit. png_error(png_ptr, "PNG image too large"); } // Extract multiple pixels with bit depths of 1, 2, and 4 from a single // byte into separate bytes (useful for paletted and grayscale images) // // png_set_packing(png_ptr); // Change the order of packed pixels to least significant bit first // (not useful if you are using png_set_packing) // // png_set_packswap(png_ptr); // Number of components in destination data (going to image_data). unsigned int dst_components = 0; Texture::Format format = Texture::UNKNOWN_FORMAT; // Palette vs non-palette. if (png_color_type == PNG_COLOR_TYPE_PALETTE) { // Expand paletted colors into RGB{A} triplets png_set_palette_to_rgb(png_ptr); // Gray vs RGB. } else if ((png_color_type & PNG_COLOR_MASK_COLOR) == PNG_COLOR_TYPE_RGB) { if (png_bits_per_channel != 8) { png_error(png_ptr, "PNG image type not recognized"); } } else { if (png_bits_per_channel <= 1 || png_bits_per_channel >= 8 ) { png_error(png_ptr, "PNG image type not recognized"); } // Expand grayscale images to the full 8 bits from 2, or 4 bits/pixel // TODO(o3d): Do we want to expose L/A/LA texture formats ? png_set_gray_1_2_4_to_8(png_ptr); png_set_gray_to_rgb(png_ptr); } // Expand paletted or RGB images with transparency to full alpha channels // so the data will be available as RGBA quartets. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(png_ptr); png_color_type |= PNG_COLOR_MASK_ALPHA; } // 24-bit RGB image or 32-bit RGBA image. if (png_color_type & PNG_COLOR_MASK_ALPHA) { format = Texture::ARGB8; } else { format = Texture::XRGB8; // Add alpha byte after each RGB triplet png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER); } png_set_bgr(png_ptr); dst_components = 4; // Turn on interlace handling. REQURIED if you are not using // png_read_image(). To see how to handle interlacing passes, // see the png_read_row() method below: png_set_interlace_handling(png_ptr); // Execute any setup steps for each Transform, i.e. to gamma correct and // add the background to the palette and update info structure. REQUIRED // if you are expecting libpng to update the palette for you (ie you // selected such a transform above). png_read_update_info(png_ptr, info_ptr); // Allocate storage for the pixels. Bitmap requires we allocate enough // memory for all mips even if we don't use them. size_t png_image_size = Bitmap::ComputeMaxSize(png_width, png_height, format); image_data.reset(new uint8[png_image_size]); if (image_data.get() == NULL) { DLOG(ERROR) << "PNG image memory allocation error \"" << filename << "\""; png_error(png_ptr, "Cannot allocate memory for bitmap"); } // Create an array of pointers to the beginning of each row. For some // hideous reason the PNG library requires this. At least we don't malloc // memory for each row as the examples do. row_pointers = static_cast<png_bytep *>( png_malloc(png_ptr, png_height * sizeof(png_bytep))); // NOLINT if (row_pointers == NULL) { DLOG(ERROR) << "PNG row memory allocation error \"" << filename << "\""; png_error(png_ptr, "Cannot allocate memory for row pointers"); } // Fill the row pointer array. DCHECK_LE(png_get_rowbytes(png_ptr, info_ptr), png_width * dst_components); png_bytep row_ptr = reinterpret_cast<png_bytep>(image_data.get()); for (unsigned int i = 0; i < png_height; ++i) { row_pointers[i] = row_ptr; row_ptr += png_width * dst_components; } // Read the image, applying format transforms and de-interlacing as we go. png_read_image(png_ptr, row_pointers); // Do not reading any additional chunks using png_read_end() // Clean up after the read, and free any memory allocated - REQUIRED png_free(png_ptr, row_pointers); png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL); // Success. Bitmap::Ref bitmap(new Bitmap(service_locator)); bitmap->SetContents(format, 1, png_width, png_height, IMAGE, &image_data); bitmaps->push_back(bitmap); return true; } namespace { bool CreatePNGInUInt8Vector(const Bitmap& bitmap, std::vector<uint8>* buffer) { DCHECK(bitmap.format() == Texture::ARGB8); DCHECK(bitmap.num_mipmaps() == 1); png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { DLOG(ERROR) << "Could not create PNG structure."; return false; } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { DLOG(ERROR) << "Could not create PNG info structure."; png_destroy_write_struct(&png_ptr, png_infopp_NULL); return false; } unsigned width = bitmap.width(); unsigned height = bitmap.height(); scoped_array<png_bytep> row_pointers(new png_bytep[height]); for (unsigned int i = 0; i < height; ++i) { row_pointers[height - 1 - i] = bitmap.GetMipData(0) + i * width * 4; } if (setjmp(png_jmpbuf(png_ptr))) { // If we get here, we had a problem reading the file. DLOG(ERROR) << "Error while getting dataURL."; png_destroy_write_struct(&png_ptr, &info_ptr); return false; } // Set up our STL stream output. png_set_write_fn(png_ptr, buffer, &StreamWriteData, &StreamFlush); png_set_IHDR(png_ptr, info_ptr, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_set_bgr(png_ptr); png_set_rows(png_ptr, info_ptr, row_pointers.get()); png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, png_voidp_NULL); png_destroy_write_struct(&png_ptr, &info_ptr); return true; } } // anonymous namespace String Bitmap::ToDataURL() { if (format_ != Texture::ARGB8) { O3D_ERROR(service_locator()) << "Can only get data URL from ARGB8 images."; return dataurl::kEmptyDataURL; } if (num_mipmaps_ != 1) { O3D_ERROR(service_locator()) << "Can only get data URL from 2d images with no mips."; return dataurl::kEmptyDataURL; } std::vector<uint8> stream; if (!CreatePNGInUInt8Vector(*this, &stream)) { return dataurl::kEmptyDataURL; } return dataurl::ToDataURL("image/png", &stream[0], stream.size()); } } // namespace o3d
{ "content_hash": "721eecbb11572a172740c06712b01176", "timestamp": "", "source": "github", "line_count": 309, "max_line_length": 80, "avg_line_length": 35.23948220064725, "alnum_prop": 0.6470750298466342, "repo_name": "rwatson/chromium-capsicum", "id": "6b73b9482291c675202f7b689919f58ba4492109", "size": "12451", "binary": false, "copies": "1", "ref": "refs/heads/chromium-capsicum", "path": "o3d/core/cross/bitmap_png.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
Reports use of a default export as a locally named import. Rationale: the syntax exists to import default exports expressively, let's use it. ## Rule Details Given: ```js // foo.js export default 'foo'; export const bar = 'baz'; ``` ...these would be valid: ```js import foo from './foo.js'; import foo, { bar } from './foo.js'; ``` ...and these would be reported: ```js // message: Using exported name 'bar' as identifier for default export. import { default as foo } from './foo.js'; import { default as foo, bar } from './foo.js'; ```
{ "content_hash": "71e314849af62e6e4070846cf05cdf2e", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 82, "avg_line_length": 21.72, "alnum_prop": 0.6721915285451197, "repo_name": "Khan/khan-linter", "id": "86fb41d6150e122e2395917eb87221bdfe53ae63", "size": "570", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "node_modules/eslint-plugin-import/docs/rules/no-named-default.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "473" }, { "name": "JavaScript", "bytes": "9867" }, { "name": "Makefile", "bytes": "1397" }, { "name": "Python", "bytes": "409986" }, { "name": "Shell", "bytes": "5543" } ], "symlink_target": "" }
$.fn.feedbackForm = function () { this.on('submit', function (e) { e.preventDefault(); submitForm($(this)); return false; }); resetForm(this); function resetForm($el) { $el.removeClass('fb-form_success fb-form_error'); $el.find('.fb-input_error').removeClass('fb-input_error'); $el.find('.fb-label, .fb-status') .removeClass('fb-status_success fb-status_error') .html('') .hide(); } function startProcessing($el) { resetForm($el) $el.addClass('fb-form_loading'); $el.find('.fb-disabled').prop('disabled', true); } function finishProcessing($el, text, status) { $el.removeClass('fb-form_loading'); $el.addClass(status ? 'fb-form_success' : 'fb-form_error'); $el.find('.fb-disabled').prop('disabled', false); if (text) { $el.find('.fb-status') .addClass(status ? 'fb-status_success' : 'fb-status_error') .html(text) .show(); } } function setFormErrors($el, errors) { $.each(errors, function (name, error) { $el.find('.fb-input[name~=' + name + ']').addClass('fb-input_error'); $el.find('.fb-label[rel~=' + name + ']').html(error).show(); }); } function submitForm($el) { var data = $el.serialize() , name = $el.attr('name'); startProcessing($el); $.ajax({ type: 'POST', url: 'mail.php', cache: false, dataType: 'json', data: 'act=' + name + '&' + data, success: function (data) { finishProcessing($el, data.text, data.status); if (data.errors) { setFormErrors($el, data.errors); } }, error: function () { finishProcessing($el, undefined, false); } }); } } $(document).ready(function () { $('.fb-form').feedbackForm(); });
{ "content_hash": "289baa28f637e8ffcd683812a949cfad", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 72, "avg_line_length": 22.21518987341772, "alnum_prop": 0.5669515669515669, "repo_name": "nazarov-mi/mail-feedback", "id": "7b1e29cabae7019acc694d831220fb8318759542", "size": "1755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mail.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1755" }, { "name": "PHP", "bytes": "6181" } ], "symlink_target": "" }
package com.amazonaws.services.codepipeline.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum FailureType { JobFailed("JobFailed"), ConfigurationError("ConfigurationError"), PermissionError("PermissionError"), RevisionOutOfSync("RevisionOutOfSync"), RevisionUnavailable("RevisionUnavailable"), SystemUnavailable("SystemUnavailable"); private String value; private FailureType(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return FailureType corresponding to the value */ public static FailureType fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (FailureType enumEntry : FailureType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
{ "content_hash": "ac39864d7cd8ce9350f3ce4ccaa1f9a3", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 91, "avg_line_length": 24.94, "alnum_prop": 0.627906976744186, "repo_name": "dagnir/aws-sdk-java", "id": "7fe038bad6a2c6246323e91e277fd56a89574687", "size": "1827", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-codepipeline/src/main/java/com/amazonaws/services/codepipeline/model/FailureType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "157317" }, { "name": "Gherkin", "bytes": "25556" }, { "name": "Java", "bytes": "165755153" }, { "name": "Scilab", "bytes": "3561" } ], "symlink_target": "" }
function rootReducer(state = { name: 'Horizons' }, action) { switch (action.type) { default: return state; } } export default rootReducer;
{ "content_hash": "7651d154264d9ce9a9d5178a1659fa03", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 60, "avg_line_length": 19.25, "alnum_prop": 0.6493506493506493, "repo_name": "ParroApp/parro", "id": "0f4927915ccb0c6494e2734b24b56a764a22f720", "size": "154", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/reducers/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1670" }, { "name": "HTML", "bytes": "31911" }, { "name": "JavaScript", "bytes": "100873" } ], "symlink_target": "" }
import React from 'react' import PropTypes from 'prop-types' import styles from '../progressbar.css' const ProgressBar = ({ progress, color, backgroundColor, className, progressClassName, }) => ( <div className={` ${styles.progressbar} ${className} `} style={{ backgroundColor }} > <div className={` ${styles.progress} ${progressClassName} ${progress == null && styles.progressIndeterminate} `} style={{ backgroundColor: color, width: progress != null ? `${progress}%` : undefined, }} /> </div> ) ProgressBar.propTypes = { progress: PropTypes.number, color: PropTypes.string, backgroundColor: PropTypes.string, className: PropTypes.string, progressClassName: PropTypes.string, } ProgressBar.defaultProps = { progress: 0, color: null, backgroundColor: null, className: '', progressClassName: '', } export default ProgressBar
{ "content_hash": "dc008f527c225ddd2b5fd8636d310194", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 61, "avg_line_length": 19.22, "alnum_prop": 0.6337148803329865, "repo_name": "fyndiq/fyndiq-ui", "id": "cea2a1c8ee421023513dc360b71764b707dd965f", "size": "961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/fyndiq-component-loader/src/progressbar.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31681" }, { "name": "HTML", "bytes": "1183" }, { "name": "JavaScript", "bytes": "256990" } ], "symlink_target": "" }
package org.pyyaml; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.yaml.snakeyaml.events.Event; import org.yaml.snakeyaml.tokens.Token; /** * @see imported from PyYAML */ public class PyCanonicalTest extends PyImportTest { public void testCanonicalScanner() throws IOException { File[] files = getStreamsByExtension(".canonical"); assertTrue("No test files found.", files.length > 0); for (int i = 0; i < files.length; i++) { InputStream input = new FileInputStream(files[i]); List<Token> tokens = canonicalScan(input); input.close(); assertFalse(tokens.isEmpty()); } } private List<Token> canonicalScan(InputStream input) throws IOException { int ch = input.read(); StringBuilder buffer = new StringBuilder(); while (ch != -1) { buffer.append((char) ch); ch = input.read(); } CanonicalScanner scanner = new CanonicalScanner(buffer.toString()); List<Token> result = new ArrayList<Token>(); while (scanner.peekToken() != null) { result.add(scanner.getToken()); } return result; } public void testCanonicalParser() throws IOException { File[] files = getStreamsByExtension(".canonical"); assertTrue("No test files found.", files.length > 0); for (int i = 0; i < files.length; i++) { InputStream input = new FileInputStream(files[i]); List<Event> tokens = canonicalParse(input); input.close(); assertFalse(tokens.isEmpty()); } } }
{ "content_hash": "91ed2e64cd5e3c072499732da595aa7a", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 77, "avg_line_length": 31.87272727272727, "alnum_prop": 0.6155162578436966, "repo_name": "henryyan/snakeyaml", "id": "499faca004eda973c0132cf22ea8dff61f73704d", "size": "2371", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/test/java/org/pyyaml/PyCanonicalTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1642134" }, { "name": "Ragel in Ruby Host", "bytes": "2860" } ], "symlink_target": "" }
/* * ratelimit.c - Do something with rate limit. * * Isolated from kernel/printk.c by Dave Young <hidave.darkstar@gmail.com> * * 2008-05-01 rewrite the function and use a ratelimit_state data struct as * parameter. Now every user can use their own standalone ratelimit_state. * * This file is released under the GPLv2. */ #include <linux/ratelimit.h> #include <linux/jiffies.h> #include <linux/export.h> /* * __ratelimit - rate limiting * @rs: ratelimit_state data * @func: name of calling function * * This enforces a rate limit: not more than @rs->burst callbacks * in every @rs->interval * * RETURNS: * 0 means callbacks will be suppressed. * 1 means go ahead and do it. */ int ___ratelimit(struct ratelimit_state *rs, const char *func) { unsigned long flags; int ret; if (!rs->interval) return 1; /* * If we contend on this state's lock then almost * by definition we are too busy to print a message, * in addition to the one that will be printed by * the entity that is holding the lock already: */ if (!raw_spin_trylock_irqsave(&rs->lock, flags)) return 0; if (!rs->begin) rs->begin = jiffies; if (time_is_before_jiffies(rs->begin + rs->interval)) { if (rs->missed) printk(KERN_WARNING "%s: %d callbacks suppressed\n", func, rs->missed); rs->begin = jiffies; rs->printed = 0; rs->missed = 0; } if (rs->burst && rs->burst > rs->printed) { rs->printed++; ret = 1; } else { rs->missed++; ret = 0; } raw_spin_unlock_irqrestore(&rs->lock, flags); return ret; } EXPORT_SYMBOL(___ratelimit);
{ "content_hash": "d1cc833be22b8ed3503bb78f5623ac49", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 75, "avg_line_length": 23.47761194029851, "alnum_prop": 0.6636999364272091, "repo_name": "AlbandeCrevoisier/ldd-athens", "id": "2c5de86460c5bb82f3d1c83b136b2f985484298a", "size": "1573", "binary": false, "copies": "272", "ref": "refs/heads/master", "path": "linux-socfpga/lib/ratelimit.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "10184236" }, { "name": "Awk", "bytes": "40418" }, { "name": "Batchfile", "bytes": "81753" }, { "name": "C", "bytes": "566858455" }, { "name": "C++", "bytes": "21399133" }, { "name": "Clojure", "bytes": "971" }, { "name": "Cucumber", "bytes": "5998" }, { "name": "FORTRAN", "bytes": "11832" }, { "name": "GDB", "bytes": "18113" }, { "name": "Groff", "bytes": "2686457" }, { "name": "HTML", "bytes": "34688334" }, { "name": "Lex", "bytes": "56961" }, { "name": "Logos", "bytes": "133810" }, { "name": "M4", "bytes": "3325" }, { "name": "Makefile", "bytes": "1685015" }, { "name": "Objective-C", "bytes": "920162" }, { "name": "Perl", "bytes": "752477" }, { "name": "Perl6", "bytes": "3783" }, { "name": "Python", "bytes": "533352" }, { "name": "Shell", "bytes": "468244" }, { "name": "SourcePawn", "bytes": "2711" }, { "name": "UnrealScript", "bytes": "12824" }, { "name": "XC", "bytes": "33970" }, { "name": "XS", "bytes": "34909" }, { "name": "Yacc", "bytes": "113516" } ], "symlink_target": "" }
![Image](../project_images/IMG_8385.JPG?raw=true "Technologies")
{ "content_hash": "b803f832f67eb0e503e3539b3e5ff8a9", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 64, "avg_line_length": 64, "alnum_prop": 0.734375, "repo_name": "sergey-serov/devart-template", "id": "2c30b9200b4afe3543d95e082de47746dd997510", "size": "64", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "project_posts/2014-03-24-Architecture-Technologies.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1379" }, { "name": "Dart", "bytes": "137" }, { "name": "JavaScript", "bytes": "1696" }, { "name": "PHP", "bytes": "7213" }, { "name": "Shell", "bytes": "995945" } ], "symlink_target": "" }
package syncmessagepassing; import semaphore.Semaphore2; /** * A handshake implemented using general semaphores. This is a class with * methods send and receive defined using class semaphore2. * * @author shivam * */ public class Handshake1 { private Object local; Semaphore2 semin = new Semaphore2(0); Semaphore2 semout = new Semaphore2(0); public void send(Object x) { local = x; // Write message. semin.V(); // Signal that message is now written. semout.P(); // Wait here until message has been read. } public Object receive() { semin.P(); // Wait here until message has been written. semout.V(); // Signal that message has been read. return (local); // Read message. (Note : Java insists that the // `return' must be the last statement in a // returning method, which is why the last two // statements appear to be the wrong way round.) } }
{ "content_hash": "7094df9377ef2fb341db6e6dbd8fbfac", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 73, "avg_line_length": 28.838709677419356, "alnum_prop": 0.6923937360178971, "repo_name": "shivam091/Java-Concurrent-Programming", "id": "0546b56b16521f0bc64c5a51b75a594ed2fab464", "size": "894", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Concurrent Programming/src/syncmessagepassing/Handshake1.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12808" }, { "name": "Java", "bytes": "33708" }, { "name": "JavaScript", "bytes": "827" } ], "symlink_target": "" }
namespace blink { class V8TestInterfaceGarbageCollected { STATIC_ONLY(V8TestInterfaceGarbageCollected); public: CORE_EXPORT static bool hasInstance(v8::Local<v8::Value>, v8::Isolate*); static v8::Local<v8::Object> findInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*); CORE_EXPORT static v8::Local<v8::FunctionTemplate> domTemplate(v8::Isolate*, const DOMWrapperWorld&); static TestInterfaceGarbageCollected* toImpl(v8::Local<v8::Object> object) { return toScriptWrappable(object)->toImpl<TestInterfaceGarbageCollected>(); } CORE_EXPORT static TestInterfaceGarbageCollected* toImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>); CORE_EXPORT static const WrapperTypeInfo wrapperTypeInfo; template<typename VisitorDispatcher> static void trace(VisitorDispatcher visitor, ScriptWrappable* scriptWrappable) { visitor->trace(scriptWrappable->toImpl<TestInterfaceGarbageCollected>()); } static void traceWrappers(WrapperVisitor* visitor, ScriptWrappable* scriptWrappable) { visitor->traceWrappers(scriptWrappable->toImpl<TestInterfaceGarbageCollected>()); } static void constructorCallback(const v8::FunctionCallbackInfo<v8::Value>&); static const int eventListenerCacheIndex = v8DefaultWrapperInternalFieldCount + 0; static const int internalFieldCount = v8DefaultWrapperInternalFieldCount + 1; }; template <> struct V8TypeOf<TestInterfaceGarbageCollected> { typedef V8TestInterfaceGarbageCollected Type; }; } // namespace blink #endif // V8TestInterfaceGarbageCollected_h
{ "content_hash": "ac144f40d29719d4a7f9c5a18574045e", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 108, "avg_line_length": 46.515151515151516, "alnum_prop": 0.7960912052117264, "repo_name": "Samsung/ChromiumGStreamerBackend", "id": "f83af87f13a3ceb3e428624e2e85d747d0e38112", "size": "2273", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/bindings/tests/results/core/V8TestInterfaceGarbageCollected.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
[![experimental](http://badges.github.io/stability-badges/dist/experimental.svg)](http://github.com/badges/stability-badges) Creates a `AudioContext` that works as expected in desktop and mobile, particularly across iOS devices. ### Motivation There is a [bug in iOS](http://stackoverflow.com/questions/26336040/how-to-fix-changing-sample-rate-bug) where the AudioContext `sampleRate` is sometimes not what you would expect, and as a result, all WebAudio plays with heavy distortion. This occurs when you play an audio/video element with a different sample rate, or when you first boot up Safari (tested on iOS9.2, iPhone5S, no headphones). To get around this, we try to detect a broken state, and if so, play a dummy buffer before returning a *new* AudioContext which should have the desired sample rate (default 44100). ## Example On iOS, this function must be called from user gesture event, such as `touchend`. ```js const createAudioContext = require('ios-safe-audio-context') clickToPlay.addEventListener('touchend', () => { const audioContext = createAudioContext() // now you can use this context for playback }) ``` ## Usage [![NPM](https://nodei.co/npm/ios-safe-audio-context.png)](https://www.npmjs.com/package/ios-safe-audio-context) #### `context = createAudioContext([desiredSampleRate])` Returns a new AudioContext, only applying the hack if we detect a broken state (iOS). `desiredSampleRate` defaults to 44100. ## License MIT, see [LICENSE.md](http://github.com/Jam3/ios-safe-audio-context/blob/master/LICENSE.md) for details.
{ "content_hash": "baafd706a8fa9043f1ff172a01f767c8", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 396, "avg_line_length": 44.714285714285715, "alnum_prop": 0.7591054313099042, "repo_name": "Jam3/ios-safe-audio-context", "id": "bc876d3cb3ebeb5edbcef745f65d47308d41d794", "size": "1591", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "866" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Bot. Jb. 14: 348 (1892) #### Original name Hexagonia niam-niamensis Henn., 1891 ### Remarks null
{ "content_hash": "565c0f95d71bd30c3ee88454796f752e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 14.23076923076923, "alnum_prop": 0.6972972972972973, "repo_name": "mdoering/backbone", "id": "af6c81f92f6305146d4b7bb5e196f9ba395eca32", "size": "245", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Polyporaceae/Hexagonia/Hexagonia niam-niamensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }