code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// Diamond-in-the-Rough // Code Wars program written in JavaScript for the RingoJS environment // // The MIT License (MIT) // // Copyright (c) 2015 Lee Jenkins // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. var stdin = require("system").stdin; var stdout = require("system").stdout; "use strict"; (function SpiralTriangles() { function run() { var inputData = readDiamondInfo(); while( inputData.size > 0 ) { printDiamonds( inputData ); inputData = readDiamondInfo(); } }; function printDiamonds( inputData ) { var midSize = inputData.size / 2; for( var gridRow=0; gridRow<inputData.rows; ++gridRow ) { for( var diamondRow=0; diamondRow<inputData.size; ++diamondRow ) { var line = ""; for( var gridCol=0; gridCol<inputData.cols; ++gridCol ) { for( var diamondCol=0; diamondCol<inputData.size; ++diamondCol ) { var c = "#"; if( diamondRow < midSize ) { // top half if( diamondCol >= (midSize-(diamondRow+1)) && diamondCol < midSize ) { c = "/"; } else if( diamondCol >= midSize && diamondCol <= (midSize+diamondRow) ) { c = "\\"; } } else { // bottom half if( diamondCol >= (diamondRow-midSize) && diamondCol < midSize ) { c = "\\"; } else if( diamondCol >= midSize && diamondCol < (inputData.size+midSize-diamondRow) ) { c = "/"; } } line += c; } } print( line ); } } }; function readDiamondInfo() { var tokens = stdin.readLine().split(/\s+/); return { size: parseInt( tokens[0] ), rows: parseInt( tokens[1] ), cols: parseInt( tokens[2] ) }; }; run(); }) ();
p473lr/i-urge-mafia-gear
HP Code Wars Documents/2015/Solutions/prob11_DiamondInTheRough-lee.js
JavaScript
apache-2.0
3,164
package apple.uikit; import java.io.*; import java.nio.*; import java.util.*; import com.google.j2objc.annotations.*; import com.google.j2objc.runtime.*; import com.google.j2objc.runtime.block.*; import apple.audiotoolbox.*; import apple.corefoundation.*; import apple.coregraphics.*; import apple.coreservices.*; import apple.foundation.*; import apple.coreanimation.*; import apple.coredata.*; import apple.coreimage.*; import apple.coretext.*; import apple.corelocation.*; @Library("UIKit/UIKit.h") @Mapping("UIMenuControllerArrowDirection") public final class UIMenuControllerArrowDirection extends ObjCEnum { @GlobalConstant("UIMenuControllerArrowDefault") public static final long Default = 0L; @GlobalConstant("UIMenuControllerArrowUp") public static final long Up = 1L; @GlobalConstant("UIMenuControllerArrowDown") public static final long Down = 2L; @GlobalConstant("UIMenuControllerArrowLeft") public static final long Left = 3L; @GlobalConstant("UIMenuControllerArrowRight") public static final long Right = 4L; }
Sellegit/j2objc
runtime/src/main/java/apple/uikit/UIMenuControllerArrowDirection.java
Java
apache-2.0
1,076
/** * @private * @providesModule CustomTabsAndroid * @flow */ 'use strict'; import { NativeModules } from 'react-native'; import type { TabOption } from './TabOption'; const CustomTabsManager = NativeModules.CustomTabsManager; /** * To open the URL of the http or https in Chrome Custom Tabs. * If Chrome is not installed, opens the URL in other browser. */ export default class CustomTabsAndroid { /** * Opens the URL on a Custom Tab. * * @param url the Uri to be opened. * @param option the Option to customize Custom Tabs of look & feel. */ static openURL(url: string, option: TabOption = {}): Promise<boolean> { return CustomTabsManager.openURL(url, option) } }
droibit/react-native-custom-tabs
src/CustomTabsAndroid.js
JavaScript
apache-2.0
701
package com.swifts.frame.modules.wx.fastweixin.company.message.req; /** * 微信企业号异步任务类型 * ==================================================================== * * -------------------------------------------------------------------- * @author Nottyjay * @version 1.0.beta * @since 1.3.6 * ==================================================================== */ public final class QYBatchJobType { private String SYNCUSER = "sync_user";// 增量更新成员 private String REPLACEUSER = "replace_user";// 全量覆盖成员 private String INVITEUSER = "invite_user";// 邀请成员关注 private String REPLACEPARTY = "replace_party";// 全量覆盖部门 private QYBatchJobType() { } }
hanyahui88/swifts
src/main/java/com/swifts/frame/modules/wx/fastweixin/company/message/req/QYBatchJobType.java
Java
apache-2.0
754
/* * Copyright (c) 2010-2017 Evolveum * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.evolveum.midpoint.model.intest.rbac; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import java.io.File; /** * @author semancik * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRbacDeprecated extends TestRbac { protected static final File ROLE_GOVERNOR_DEPRECATED_FILE = new File(TEST_DIR, "role-governor-deprecated.xml"); protected static final File ROLE_CANNIBAL_DEPRECATED_FILE = new File(TEST_DIR, "role-cannibal-deprecated.xml"); @Override protected File getRoleGovernorFile() { return ROLE_GOVERNOR_DEPRECATED_FILE; } @Override protected File getRoleCannibalFile() { return ROLE_CANNIBAL_DEPRECATED_FILE; } @Override protected boolean testMultiplicityConstraintsForNonDefaultRelations() { return false; } }
Pardus-Engerek/engerek
model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbacDeprecated.java
Java
apache-2.0
1,603
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.bpmn.model; public class EventGateway extends Gateway { public EventGateway clone() { EventGateway clone = new EventGateway(); clone.setValues(this); return clone; } public void setValues(EventGateway otherElement) { super.setValues(otherElement); } }
Activiti/Activiti
activiti-core/activiti-bpmn-model/src/main/java/org/activiti/bpmn/model/EventGateway.java
Java
apache-2.0
912
// Originally submitted to OSEHRA 2/21/2017 by DSS, Inc. // Authored by DSS, Inc. 2014-2017 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VA.Gov.Artemis.Vista.Broker { internal enum RpcMessageStatus { Uknown, Ready, Error } }
VHAINNOVATIONS/Maternity-Tracker
Dashboard/va.gov.artemis.vista/Broker/RpcMessageStatus.cs
C#
apache-2.0
316
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.skylark.io.impl; import com.facebook.buck.skylark.io.Globber; import com.facebook.buck.util.MoreCollectors; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.UnixGlob; import java.io.IOException; import java.util.Collection; import java.util.Set; /** * A simple implementation of globbing functionality that allows resolving file paths based on * include patterns (file patterns that should be returned) minus exclude patterns (file patterns * that should be excluded from the resulting set). * * <p>Since this is a simple implementation it does not support caching and other smarts. */ public class SimpleGlobber implements Globber { /** Path used as a root when resolving patterns. */ private final Path basePath; private SimpleGlobber(Path basePath) { this.basePath = basePath; } /** * @param include File patterns that should be included in the resulting set. * @param exclude File patterns that should be excluded from the resulting set. * @param excludeDirectories Whether directories should be excluded from the resulting set. * @return The set of paths resolved using include patterns minus paths excluded by exclude * patterns. */ @Override public Set<String> run( Collection<String> include, Collection<String> exclude, Boolean excludeDirectories) throws IOException { ImmutableSet<String> includePaths = resolvePathsMatchingGlobPatterns(include, basePath, excludeDirectories); ImmutableSet<String> excludePaths = resolvePathsMatchingGlobPatterns(exclude, basePath, excludeDirectories); return Sets.difference(includePaths, excludePaths); } /** * Resolves provided list of glob patterns into a set of paths. * * @param patterns The glob patterns to resolve. * @param basePath The base path used when resolving glob patterns. * @param excludeDirectories Flag indicating whether directories should be excluded from result. * @return The set of paths corresponding to requested patterns. */ private static ImmutableSet<String> resolvePathsMatchingGlobPatterns( Collection<String> patterns, Path basePath, Boolean excludeDirectories) throws IOException { UnixGlob.Builder includeGlobBuilder = UnixGlob.forPath(basePath).addPatterns(patterns); if (excludeDirectories != null) { includeGlobBuilder.setExcludeDirectories(excludeDirectories); } return includeGlobBuilder .glob() .stream() .map(includePath -> includePath.relativeTo(basePath).getPathString()) .collect(MoreCollectors.toImmutableSet()); } /** * Factory method for creating {@link SimpleGlobber} instances. * * @param basePath The base path relative to which paths matching glob patterns will be resolved. */ public static Globber create(Path basePath) { return new SimpleGlobber(basePath); } }
shybovycha/buck
src/com/facebook/buck/skylark/io/impl/SimpleGlobber.java
Java
apache-2.0
3,622
using System; using Microsoft.SPOT; namespace WeatherStation.WebServer { /// <summary> /// Base class for HTTP object (request/response) /// </summary> public class HttpBase { #region Constants ... // const string separator protected const char CR = '\r'; protected const char LF = '\n'; // request line separator protected const char REQUEST_LINE_SEPARATOR = ' '; // starting of query string protected const char QUERY_STRING_SEPARATOR = '?'; // query string parameters separator protected const char QUERY_STRING_PARAMS_SEPARATOR = '&'; // query string value separator protected const char QUERY_STRING_VALUE_SEPARATOR = '='; // header-value separator protected const char HEADER_VALUE_SEPARATOR = ':'; // form parameters separator protected const char FORM_PARAMS_SEPARATOR = '&'; // form value separator protected const char FORM_VALUE_SEPARATOR = '='; #endregion #region Properties ... /// <summary> /// Headers of the HTTP request/response /// </summary> public NameValueCollection Headers { get; protected set; } /// <summary> /// Body of HTTP request/response /// </summary> public string Body { get; set; } #endregion /// <summary> /// Constructor /// </summary> public HttpBase() { this.Headers = new NameValueCollection(); } } }
ppatierno/mfweatherstation
WeatherStation/WebServer/HttpBase.cs
C#
apache-2.0
1,574
// 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. package org.apache.cloudstack.api.command.user.loadbalancer; import javax.inject.Inject; import org.apache.log4j.Logger; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.DomainResponse; import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.SslCertResponse; import org.apache.cloudstack.context.CallContext; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import org.apache.cloudstack.network.tls.CertService; @APICommand(name = "uploadSslCert", description = "Upload a certificate to CloudStack", responseObject = SslCertResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class UploadSslCertCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UploadSslCertCmd.class.getName()); private static final String s_name = "uploadsslcertresponse"; @Inject CertService _certService; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name = ApiConstants.CERTIFICATE, type = CommandType.STRING, required = true, description = "SSL certificate", length = 16384) private String cert; @Parameter(name = ApiConstants.PRIVATE_KEY, type = CommandType.STRING, required = true, description = "Private key", length = 16384) private String key; @Parameter(name = ApiConstants.CERTIFICATE_CHAIN, type = CommandType.STRING, description = "Certificate chain of trust", length = 2097152) private String chain; @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, description = "Password for the private key") private String password; @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account that will own the SSL certificate") private String accountName; @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "an optional project for the SSL certificate") private Long projectId; @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, description = "domain ID of the account owning the SSL certificate") private Long domainId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public String getCert() { return cert; } public String getKey() { return key; } public String getChain() { return chain; } public String getPassword() { return password; } public String getAccountName() { return accountName; } public Long getDomainId() { return domainId; } public Long getProjectId() { return projectId; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { try { SslCertResponse response = _certService.uploadSslCert(this); setResponseObject(response); response.setResponseName(getCommandName()); } catch (Exception e) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } } @Override public String getCommandName() { return s_name; } @Override public long getEntityOwnerId() { return CallContext.current().getCallingAccount().getId(); } }
jcshen007/cloudstack
api/src/org/apache/cloudstack/api/command/user/loadbalancer/UploadSslCertCmd.java
Java
apache-2.0
5,159
package info.cyanac.plugin.bukkit; import java.util.ArrayList; import java.util.List; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; public class CyanACTabCompleter implements TabCompleter { @Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) { if(command.getName().equalsIgnoreCase("cyanac")){ List<String> tabCompletionList = new ArrayList(); tabCompletionList.add("help"); tabCompletionList.add("resync"); tabCompletionList.add("license"); return tabCompletionList; } return null; } }
Moritz30-Projects/CyanAC-Plugin
src/info/cyanac/plugin/bukkit/CyanACTabCompleter.java
Java
apache-2.0
675
<?php /** * This file is part of the SevenShores/NetSuite library * AND originally from the NetSuite PHP Toolkit. * * New content: * @package ryanwinchester/netsuite-php * @copyright Copyright (c) Ryan Winchester * @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 * @link https://github.com/ryanwinchester/netsuite-php * * Original content: * @copyright Copyright (c) NetSuite Inc. * @license https://raw.githubusercontent.com/ryanwinchester/netsuite-php/master/original/NetSuite%20Application%20Developer%20License%20Agreement.txt * @link http://www.netsuite.com/portal/developers/resources/suitetalk-sample-applications.shtml * * generated: 2020-04-10 09:56:55 PM UTC */ namespace NetSuite\Classes; class FolderFolderType { static $paramtypesmap = array( ); const _appPackages = "_appPackages"; const _attachmentsReceived = "_attachmentsReceived"; const _attachmentsSent = "_attachmentsSent"; const _certificates = "_certificates"; const _documentsAndFiles = "_documentsAndFiles"; const _emailTemplates = "_emailTemplates"; const _faxTemplates = "_faxTemplates"; const _images = "_images"; const _letterTemplates = "_letterTemplates"; const _mailMerge = "_mailMerge"; const _marketingTemplates = "_marketingTemplates"; const _pdfTemplates = "_pdfTemplates"; const _suitebundles = "_suitebundles"; const _suitecommerceAdvancedSiteTemplates = "_suitecommerceAdvancedSiteTemplates"; const _suitescripts = "_suitescripts"; const _templates = "_templates"; const _webSiteHostingFiles = "_webSiteHostingFiles"; }
RyanWinchester/netsuite-php
src/Classes/FolderFolderType.php
PHP
apache-2.0
1,641
<?php /** * Menu Module * * @author Bálint Horváth <balint@snett.net> */ namespace Franklin\Component; class Menu extends \Franklin\System\Object{ public $Id; public $Name; public $Status; public $CleanURL; public function __construct($Parent) { parent::__construct($Parent); $this->Status = new Status($this); } }
snett/Franklin
Modules/Component/Menu.php
PHP
apache-2.0
375
package pe.com.ccpl.siconc.web.service; import pe.com.ccpl.siconc.web.model.Role; public interface RoleService { public Role getRole(int id); }
JR-CCPL87/ccpl-affirmation
src/main/java/pe/com/ccpl/siconc/web/service/RoleService.java
Java
apache-2.0
150
/* * Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.artifact.proxyservice.validators; import org.apache.axiom.om.OMElement; import org.apache.commons.lang.StringUtils; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.wso2.developerstudio.eclipse.artifact.proxyservice.model.ProxyServiceModel; import org.wso2.developerstudio.eclipse.artifact.proxyservice.model.ProxyServiceModel.TargetEPType; import org.wso2.developerstudio.eclipse.artifact.proxyservice.utils.PsArtifactConstants; import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBArtifact; import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBProjectArtifact; import org.wso2.developerstudio.eclipse.platform.core.exception.FieldValidationException; import org.wso2.developerstudio.eclipse.platform.core.model.AbstractFieldController; import org.wso2.developerstudio.eclipse.platform.core.project.model.ProjectDataModel; import org.wso2.developerstudio.eclipse.project.extensions.templates.ArtifactTemplate; import org.wso2.developerstudio.eclipse.platform.ui.validator.CommonFieldValidator; import java.util.List; public class ProxyServiceProjectFieldController extends AbstractFieldController { public void validate(String modelProperty, Object value, ProjectDataModel model) throws FieldValidationException { boolean optWsdlbasedProxy = false; boolean optCustomProxy = false; ArtifactTemplate selectedTemplate = (ArtifactTemplate)model.getModelPropertyValue("ps.type"); if(selectedTemplate!=null){ optWsdlbasedProxy = selectedTemplate.getId().equalsIgnoreCase(PsArtifactConstants.WSDL_BASED_PROXY_TEMPL_ID); optCustomProxy = (selectedTemplate.isCustom() || selectedTemplate.getId() .equalsIgnoreCase(PsArtifactConstants.CUSTOM_PROXY_TEMPL_ID)); } if (modelProperty.equals("ps.name")) { CommonFieldValidator.validateArtifactName(value); if (value != null) { String resource = value.toString(); ProxyServiceModel proxyModel = (ProxyServiceModel) model; if (proxyModel != null) { IContainer resLocation = proxyModel.getProxyServiceSaveLocation(); if (resLocation != null) { IProject project = resLocation.getProject(); ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact(); try { esbProjectArtifact.fromFile(project.getFile("artifact.xml").getLocation().toFile()); List<ESBArtifact> allArtifacts = esbProjectArtifact.getAllESBArtifacts(); for (ESBArtifact artifact : allArtifacts) { if (resource.equals(artifact.getName())) { throw new FieldValidationException(""); } } } catch (Exception e) { throw new FieldValidationException("Specified proxy service name already exsits."); } } } } } else if (modelProperty.equals("import.file")) { CommonFieldValidator.validateImportFile(value); } else if (modelProperty.equals("proxy.target.ep.type")) { /** //TODO: if((((ProxyServiceModel)model).getTargetEPType()==TargetEPType.URL) && !(optWsdlbasedProxy||optCustomProxy)){ throw new FieldValidationException("Specified Target Endpoint"); }**/ } else if (modelProperty.equals("templ.common.ps.epurl")) { if (((ProxyServiceModel)model).getTargetEPType() == TargetEPType.URL && !(optWsdlbasedProxy||optCustomProxy)) { if (value == null || value.toString().equals("")) { throw new FieldValidationException("Target Endpoint URL cannot be empty. Please specify a valid Endpoint URL."); } else { CommonFieldValidator.isValidUrl(value.toString().trim(), "Endpoint URL"); } } } else if (modelProperty.equals("templ.common.ps.epkey")) { if ((((ProxyServiceModel)model).getTargetEPType() == TargetEPType.REGISTRY) && (value == null || value.toString().equals("")) && !(optWsdlbasedProxy||optCustomProxy)) { throw new FieldValidationException("Target Registry Endpoint key is invalid or empty. Please specify a valid Endpoint Key."); } } else if (modelProperty.equals("templ.secure.ps.secpolicy")) { } else if (modelProperty.equals("templ.wsdl.ps.wsdlurl")) { if (optWsdlbasedProxy) { if (value == null || value.toString().equals("")) { throw new FieldValidationException("Target WSDL URL cannot be empty. Please specify a valid WSDL URI."); } else { CommonFieldValidator.isValidUrl(value.toString().trim(), "WSDL URL"); } } } else if (modelProperty.equals("templ.wsdl.ps.wsdlservice")) { if (optWsdlbasedProxy && (value == null || value.toString().equals(""))) { throw new FieldValidationException("Target WSDL service is invalid or empty. Please specify a valid WSDL Service."); } } else if (modelProperty.equals("templ.wsdl.ps.wsdlport")) { if (optWsdlbasedProxy && (value == null || value.toString().equals(""))) { throw new FieldValidationException("Target WSDL port is invalid or empty. Please specify a valid WSDL Port."); } } else if (modelProperty.equals("templ.wsdl.ps.publishsame")) { } else if (modelProperty.equals("templ.logging.ps.reqloglevel")) { } else if (modelProperty.equals("templ.logging.ps.resloglevel")) { } else if (modelProperty.equals("templ.transformer.ps.xslt")) { if (selectedTemplate.getId().equalsIgnoreCase(PsArtifactConstants.TRANSFORMER_PROXY_TEMPL_ID)) { if (value == null || StringUtils.isBlank(value.toString())) { throw new FieldValidationException("Request XSLT key cannot be empty. Please specify a valid XSLT key."); } } } else if (modelProperty.equals("templ.common.ps.eplist")) { if ((((ProxyServiceModel)model).getTargetEPType()==TargetEPType.PREDEFINED) && (value==null || value.toString().equals(""))) { throw new FieldValidationException("Target Predefined Endpoint key cannot be empty. Please specify a valid Predefined Endpoint."); } } else if (modelProperty.equals("save.file")) { IResource resource = (IResource)value; if (resource == null || !resource.exists()) { throw new FieldValidationException("Please specify a valid ESB Project to Save the proxy service."); } } else if (modelProperty.equals("templ.transformer.ps.transformresponses")) { if (selectedTemplate.getId().equalsIgnoreCase(PsArtifactConstants.TRANSFORMER_PROXY_TEMPL_ID)) { if ((Boolean)value && ((ProxyServiceModel)model).getResponseXSLT().equals("")) { throw new FieldValidationException("Response XSLT key cannot be empty. Please specify a valid XSLT key."); } } } } public boolean isEnableField(String modelProperty, ProjectDataModel model) { boolean enableField = super.isEnableField(modelProperty, model); if (modelProperty.equals("import.file")) { enableField = true; } return enableField; } public List<String> getUpdateFields(String modelProperty, ProjectDataModel model) { List<String> updateFields = super.getUpdateFields(modelProperty, model); if (modelProperty.equals("import.file")) { updateFields.add("available.ps"); } else if (modelProperty.equals("create.esb.prj")) { updateFields.add("save.file"); } else if (modelProperty.equals("ps.type")) { updateFields.add("proxy.AdvancedConfig"); } return updateFields; } public boolean isVisibleField(String modelProperty, ProjectDataModel model) { boolean visibleField = super.isVisibleField(modelProperty, model); if (modelProperty.equals("available.ps")) { List<OMElement> availableEPList = ((ProxyServiceModel) model).getAvailablePSList(); visibleField = (availableEPList != null && availableEPList.size() > 0); } return visibleField; } public boolean isReadOnlyField(String modelProperty, ProjectDataModel model) { boolean readOnlyField = super.isReadOnlyField(modelProperty, model); if (modelProperty.equals("save.file")) { readOnlyField = true; } return readOnlyField; } }
prabushi/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.artifact.proxyservice/src/org/wso2/developerstudio/eclipse/artifact/proxyservice/validators/ProxyServiceProjectFieldController.java
Java
apache-2.0
8,585
/* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xys.libzxing.zxing.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Rect; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.RelativeLayout; import com.google.zxing.Result; import com.xys.libzxing.R; import com.xys.libzxing.zxing.camera.CameraManager; import com.xys.libzxing.zxing.decode.DecodeThread; import com.xys.libzxing.zxing.utils.BeepManager; import com.xys.libzxing.zxing.utils.CaptureActivityHandler; import com.xys.libzxing.zxing.utils.InactivityTimer; import java.io.IOException; import java.lang.reflect.Field; /** * This activity opens the camera and does the actual scanning on a background * thread. It draws a viewfinder to help the user place the barcode correctly, * shows feedback as the image processing is happening, and then overlays the * results when a scan is successful. * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen */ public final class CaptureActivity extends AppCompatActivity implements SurfaceHolder.Callback { private static final String TAG = CaptureActivity.class.getSimpleName(); private CameraManager cameraManager; private CaptureActivityHandler handler; private InactivityTimer inactivityTimer; private BeepManager beepManager; private SurfaceView scanPreview = null; private RelativeLayout scanContainer; private RelativeLayout scanCropView; private ImageView scanLine; private Rect mCropRect = null; private boolean isHasSurface = false; public Handler getHandler() { return handler; } public CameraManager getCameraManager() { return cameraManager; } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_capture); scanPreview = (SurfaceView) findViewById(R.id.capture_preview); scanContainer = (RelativeLayout) findViewById(R.id.capture_container); scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view); scanLine = (ImageView) findViewById(R.id.capture_scan_line); inactivityTimer = new InactivityTimer(this); beepManager = new BeepManager(this); TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation .RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.9f); animation.setDuration(4500); animation.setRepeatCount(-1); animation.setRepeatMode(Animation.RESTART); scanLine.startAnimation(animation); } @Override protected void onResume() { super.onResume(); // CameraManager must be initialized here, not in onCreate(). This is // necessary because we don't // want to open the camera driver and measure the screen size if we're // going to show the help on // first launch. That led to bugs where the scanning rectangle was the // wrong size and partially // off screen. cameraManager = new CameraManager(getApplication()); handler = null; if (isHasSurface) { // The activity was paused but not stopped, so the surface still // exists. Therefore // surfaceCreated() won't be called, so init the camera here. initCamera(scanPreview.getHolder()); } else { // Install the callback and wait for surfaceCreated() to init the // camera. scanPreview.getHolder().addCallback(this); } inactivityTimer.onResume(); } @Override protected void onPause() { if (handler != null) { handler.quitSynchronously(); handler = null; } inactivityTimer.onPause(); beepManager.close(); cameraManager.closeDriver(); if (!isHasSurface) { scanPreview.getHolder().removeCallback(this); } super.onPause(); } @Override protected void onDestroy() { inactivityTimer.shutdown(); super.onDestroy(); } @Override public void surfaceCreated(SurfaceHolder holder) { if (holder == null) { Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!"); } if (!isHasSurface) { isHasSurface = true; initCamera(holder); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { isHasSurface = false; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } /** * A valid barcode has been found, so give an indication of success and show * the results. * * @param rawResult The contents of the barcode. * @param bundle The extras */ public void handleDecode(Result rawResult, Bundle bundle) { inactivityTimer.onActivity(); beepManager.playBeepSoundAndVibrate(); Intent resultIntent = new Intent(); bundle.putInt("width", mCropRect.width()); bundle.putInt("height", mCropRect.height()); bundle.putString("result", rawResult.getText()); resultIntent.putExtras(bundle); this.setResult(RESULT_OK, resultIntent); CaptureActivity.this.finish(); } private void initCamera(SurfaceHolder surfaceHolder) { if (surfaceHolder == null) { throw new IllegalStateException("No SurfaceHolder provided"); } if (cameraManager.isOpen()) { Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?"); return; } try { cameraManager.openDriver(surfaceHolder); // Creating the handler starts the preview, which can also throw a // RuntimeException. if (handler == null) { handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE); } initCrop(); } catch (IOException ioe) { Log.w(TAG, ioe); displayFrameworkBugMessageAndExit(); } catch (RuntimeException e) { // Barcode Scanner has seen crashes in the wild of this variety: // java.?lang.?RuntimeException: Fail to connect to camera service Log.w(TAG, "Unexpected error initializing camera", e); displayFrameworkBugMessageAndExit(); } } private void displayFrameworkBugMessageAndExit() { // camera error AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.zxing_bar_name)); builder.setMessage("Camera error"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); builder.show(); } public void restartPreviewAfterDelay(long delayMS) { if (handler != null) { handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS); } } public Rect getCropRect() { return mCropRect; } /** * 初始化截取的矩形区域 */ private void initCrop() { int cameraWidth = cameraManager.getCameraResolution().y; int cameraHeight = cameraManager.getCameraResolution().x; /** 获取布局中扫描框的位置信息 */ int[] location = new int[2]; scanCropView.getLocationInWindow(location); int cropLeft = location[0]; int cropTop = location[1] - getStatusBarHeight(); int cropWidth = scanCropView.getWidth(); int cropHeight = scanCropView.getHeight(); /** 获取布局容器的宽高 */ int containerWidth = scanContainer.getWidth(); int containerHeight = scanContainer.getHeight(); /** 计算最终截取的矩形的左上角顶点x坐标 */ int x = cropLeft * cameraWidth / containerWidth; /** 计算最终截取的矩形的左上角顶点y坐标 */ int y = cropTop * cameraHeight / containerHeight; /** 计算最终截取的矩形的宽度 */ int width = cropWidth * cameraWidth / containerWidth; /** 计算最终截取的矩形的高度 */ int height = cropHeight * cameraHeight / containerHeight; /** 生成最终的截取的矩形 */ mCropRect = new Rect(x, y, width + x, height + y); } private int getStatusBarHeight() { try { Class<?> c = Class.forName("com.android.internal.R$dimen"); Object obj = c.newInstance(); Field field = c.getField("status_bar_height"); int x = Integer.parseInt(field.get(obj).toString()); return getResources().getDimensionPixelSize(x); } catch (Exception e) { e.printStackTrace(); } return 0; } }
WindFromFarEast/SmartButler
libzxing/src/main/java/com/xys/libzxing/zxing/activity/CaptureActivity.java
Java
apache-2.0
10,672
/** \file parse_options.cpp \author michael.zohner@ec-spride.de \copyright ABY - A Framework for Efficient Mixed-protocol Secure Two-party Computation Copyright (C) 2015 Engineering Cryptographic Protocols Group, TU Darmstadt This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. \brief Parse Options Implementation */ #include "parse_options.h" /** * takes a string in the Format "c i i i ..." * (1 char followed by potentially many integers) and returns a vector of all i * @param str the string to tokenize * @param tokens the result vector of wire id */ void tokenize_verilog(const std::string& str, std::vector<uint32_t>& tokens, const std::string& delimiters) { tokens.clear(); // Skip delimiters at beginning. Skip first two characters (1 Char + 1 Space) std::string::size_type lastPos = str.find_first_not_of(delimiters, 2); // Find first "non-delimiter". std::string::size_type pos = str.find_first_of(delimiters, lastPos); while (std::string::npos != pos || std::string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(atoi(str.substr(lastPos, pos - lastPos).c_str())); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } /** * takes a string in the Format "i|i|i|..." * (integers separated by '|') and returns a vector of all integers * @param str the string to tokenize * @param tokens the result vector of wire id */ void tokenize(const std::string& str, std::vector<uint32_t>& tokens, const std::string& delimiters) { tokens.clear(); // Skip delimiters at beginning std::string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". std::string::size_type pos = str.find_first_of(delimiters, lastPos); while (std::string::npos != pos || std::string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(atoi(str.substr(lastPos, pos - lastPos).c_str())); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } int32_t parse_options(int32_t* argcp, char*** argvp, parsing_ctx* options, uint32_t nops) { int result = 0; bool skip; uint32_t i; if(*argcp < 2) return 0; while ((*argcp) > 1) { if ((*argvp)[1][0] != '-' || (*argvp)[1][1] == '\0' || (*argvp)[1][2] != '\0') return result; for (i = 0, skip = false; i < nops && !skip; i++) { if (((*argvp)[1][1]) == options[i].opt_name) { switch (options[i].type) { case T_NUM: if (isdigit((*argvp)[2][0])) { ++*argvp; --*argcp; *((uint32_t*) options[i].val) = atoi((*argvp)[1]); } break; case T_DOUBLE: ++*argvp; --*argcp; *((double*) options[i].val) = atof((*argvp)[1]); break; case T_STR: ++*argvp; --*argcp; *((std::string*) options[i].val) = (*argvp)[1]; break; case T_FLAG: *((bool*) options[i].val) = true; break; } ++result; ++*argvp; --*argcp; options[i].set = true; skip = true; } } } for (i = 0; i < nops; i++) { if (options[i].required && !options[i].set) return 0; } return 1; } void print_usage(std::string progname, parsing_ctx* options, uint32_t nops) { uint32_t i; std::cout << "Usage: " << progname << std::endl; for (i = 0; i < nops; i++) { std::cout << " -" << options[i].opt_name << " [" << options[i].help_str << (options[i].required ? ", required" : ", optional") << "]" << std::endl; } std::cout << std::endl << "Program exiting" << std::endl; }
huxh10/iSDX
aby/src/abycore/util/parse_options.cpp
C++
apache-2.0
4,288
"""heroku_blog URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from blog.views import index, signup, login, logout urlpatterns = [ url(r'^$', index, name='index'), url(r'^signup', signup, name='signup'), url(r'^login', login, name='login'), url(r'^logout', logout, name='logout'), url(r'^admin/', include(admin.site.urls)), ]
barbossa/django-heroku-blog
heroku_blog/urls.py
Python
apache-2.0
1,004
/** * Copyright (c) 2005-2012 https://github.com/zhangkaitao Licensed under the Apache License, Version 2.0 (the * "License"); */ package com.yang.spinach.common.utils.spring; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import net.sf.ehcache.Ehcache; import org.apache.shiro.cache.Cache; import org.apache.shiro.cache.CacheException; import org.apache.shiro.cache.CacheManager; import org.apache.shiro.util.CollectionUtils; import org.springframework.cache.support.SimpleValueWrapper; /** * 包装Spring cache抽象 */ public class SpringCacheManagerWrapper implements CacheManager { private org.springframework.cache.CacheManager cacheManager; /** * 设置spring cache manager * * @param cacheManager */ public void setCacheManager( org.springframework.cache.CacheManager cacheManager) { this.cacheManager = cacheManager; } @Override public <K, V> Cache<K, V> getCache(String name) throws CacheException { org.springframework.cache.Cache springCache = cacheManager .getCache(name); return new SpringCacheWrapper(springCache); } static class SpringCacheWrapper implements Cache { private final org.springframework.cache.Cache springCache; SpringCacheWrapper(org.springframework.cache.Cache springCache) { this.springCache = springCache; } @Override public Object get(Object key) throws CacheException { Object value = springCache.get(key); if (value instanceof SimpleValueWrapper) { return ((SimpleValueWrapper) value).get(); } return value; } @Override public Object put(Object key, Object value) throws CacheException { springCache.put(key, value); return value; } @Override public Object remove(Object key) throws CacheException { springCache.evict(key); return null; } @Override public void clear() throws CacheException { springCache.clear(); } @Override public int size() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return ehcache.getSize(); } throw new UnsupportedOperationException( "invoke spring cache abstract size method not supported"); } @Override public Set keys() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return new HashSet(ehcache.getKeys()); } throw new UnsupportedOperationException( "invoke spring cache abstract keys method not supported"); } @Override public Collection values() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); System.out.println("cache savePath:" + ehcache.getCacheManager().getDiskStorePath() + "--------------"); List keys = ehcache.getKeys(); if (!CollectionUtils.isEmpty(keys)) { List values = new ArrayList(keys.size()); for (Object key : keys) { Object value = get(key); if (value != null) { values.add(value); } } return Collections.unmodifiableList(values); } else { return Collections.emptyList(); } } throw new UnsupportedOperationException( "invoke spring cache abstract values method not supported"); } } }
yangb0/spinach
spinach/spinach-web/src/main/java/com/yang/spinach/common/utils/spring/SpringCacheManagerWrapper.java
Java
apache-2.0
3,363
package org.javacore.io.zip; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.util.Enumeration; import java.util.zip.Adler32; import java.util.zip.CheckedInputStream; import java.util.zip.CheckedOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /* * Copyright [2015] [Jeff Lee] * * 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. */ /** * @author admin * @since 2015-10-17 14:58:59 * 利用Zip进行多文件保存 */ public class ZipCompress { private static String filePath = "src" + File.separator + "org" + File.separator + "javacore" + File.separator + "io" + File.separator; private static String[] fileNames= new String[] { filePath + "BufferedInputFileT.java", filePath + "ChangeSystemOut.java" }; public static void main(String[] args) throws IOException { zipFiles(fileNames); } private static void zipFiles(String[] fileNames) throws IOException { // 获取zip文件输出流 FileOutputStream f = new FileOutputStream("test.zip"); // 从文件输出流中获取数据校验和输出流,并设置Adler32 CheckedOutputStream csum = new CheckedOutputStream(f,new Adler32()); // 从数据校验和输出流中获取Zip输出流 ZipOutputStream zos = new ZipOutputStream(csum); // 从Zip输出流中获取缓冲输出流 BufferedOutputStream out = new BufferedOutputStream(zos); // 设置Zip文件注释 zos.setComment("测试 java zip stream"); for (String file : fileNames) { System.out.println("写入文件: " + file); // 获取文件输入字符流 BufferedReader in = new BufferedReader(new FileReader(file)); // 想Zip处理写入新的文件条目,并流定位到数据开始处 zos.putNextEntry(new ZipEntry(file)); int c; while ((c = in.read()) > 0) out.write(c); in.close(); // 刷新Zip输出流,将缓冲的流写入该流 out.flush(); } // 文件全部写入Zip输出流后,关闭 out.close(); // 输出数据校验和 System.out.println("数据校验和: " + csum.getChecksum().getValue()); System.out.println("读取zip文件"); // 读取test.zip文件输入流 FileInputStream fi = new FileInputStream("test.zip"); // 从文件输入流中获取数据校验和流 CheckedInputStream csumi = new CheckedInputStream(fi,new Adler32()); // 从数据校验和流中获取Zip解压流 ZipInputStream in2 = new ZipInputStream(csumi); // 从Zip解压流中获取缓冲输入流 BufferedInputStream bis = new BufferedInputStream(in2); // 创建文件条目 ZipEntry zipEntry; while ((zipEntry = in2.getNextEntry()) != null) { System.out.println("读取文件: " + zipEntry); int x; while ((x = bis.read()) > 0) System.out.write(x); } if (fileNames.length == 1) System.out.println("数据校验和: " + csumi.getChecksum().getValue()); bis.close(); // 获取Zip文件 ZipFile zf = new ZipFile("test.zip"); // 获取文件条目枚举 Enumeration e = zf.entries(); while (e.hasMoreElements()) { // 从Zip文件的枚举中获取文件条目 ZipEntry ze2 = (ZipEntry) e.nextElement(); System.out.println("文件: " + ze2); } } }
tzpBingo/java-example
src/main/java/org/javacore/io/zip/ZipCompress.java
Java
apache-2.0
4,471
/** * * Copyright 2014-2017 Florian Schmaus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.geekplace.javapinning.pin; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.logging.Level; import java.util.logging.Logger; import eu.geekplace.javapinning.util.HexUtilities; public abstract class Pin { private static final Logger LOGGER = Logger.getLogger(Sha256Pin.class.getName()); protected static final MessageDigest sha256md; static { MessageDigest sha256mdtemp = null; try { sha256mdtemp = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { LOGGER.log(Level.WARNING, "SHA-256 MessageDigest not available", e); } sha256md = sha256mdtemp; } protected final byte[] pinBytes; protected Pin(byte[] pinBytes) { this.pinBytes = pinBytes; } protected Pin(String pinHexString) { pinBytes = HexUtilities.decodeFromHex(pinHexString); } public abstract boolean pinsCertificate(X509Certificate x509certificate) throws CertificateEncodingException; protected abstract boolean pinsCertificate(byte[] pubkey); /** * Create a new {@link Pin} from the given String. * <p> * The Pin String must be in the format <tt>[type]:[hex-string]</tt>, where * <tt>type</tt> denotes the type of the Pin and <tt>hex-string</tt> is the * binary value of the Pin encoded in hex. Currently supported types are * <ul> * <li>PLAIN</li> * <li>SHA256</li> * <li>CERTPLAIN</li> * <li>CERTSHA256</li> * </ul> * The hex-string must contain only of whitespace characters, colons (':'), * numbers [0-9] and ASCII letters [a-fA-F]. It must be a valid hex-encoded * binary representation. First the string is lower-cased, then all * whitespace characters and colons are removed before the string is decoded * to bytes. * </p> * * @param string * the Pin String. * @return the Pin for the given Pin String. * @throws IllegalArgumentException * if the given String is not a valid Pin String */ public static Pin fromString(String string) { // The Pin's string may have multiple colons (':'), assume that // everything before the first colon is the Pin type and everything // after the colon is the Pin's byte encoded in hex. String[] pin = string.split(":", 2); if (pin.length != 2) { throw new IllegalArgumentException("Invalid pin string, expected: 'format-specifier:hex-string'."); } String type = pin[0]; String pinHex = pin[1]; switch (type) { case "SHA256": return new Sha256Pin(pinHex); case "PLAIN": return new PlainPin(pinHex); case "CERTSHA256": return new CertSha256Pin(pinHex); case "CERTPLAIN": return new CertPlainPin(pinHex); default: throw new IllegalArgumentException(); } } /** * Returns a clone of the bytes that represent this Pin. * <p> * This method is meant for unit testing only and therefore not public. * </p> * * @return a clone of the bytes that represent this Pin. */ byte[] getPinBytes() { return pinBytes.clone(); } }
Flowdalic/java-pinning
java-pinning-core/src/main/java/eu/geekplace/javapinning/pin/Pin.java
Java
apache-2.0
3,689
/* * Copyright 2014 Richard Thurston. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.northernwall.hadrian.handlers.service.dao; import com.northernwall.hadrian.domain.Audit; import java.util.LinkedList; import java.util.List; public class GetAuditData { public List<Audit> audits = new LinkedList<>(); }
Jukkorsis/Hadrian
src/main/java/com/northernwall/hadrian/handlers/service/dao/GetAuditData.java
Java
apache-2.0
840
<?php /** * NewExten listener, will capture extensions as channels step by them. * * PHP Version 5 * * @category AsterTrace * @package EventHandlers * @author Marcelo Gornstein <marcelog@gmail.com> * @license http://marcelog.github.com/ Apache License 2.0 * @version SVN: $Id$ * @link http://marcelog.github.com/ * * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com> * * 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. * */ namespace AsterTrace\EventHandlers; class NewExtenListener extends PDOListener { public function onNewexten($event) { $this->executeStatement($this->insertStatement, array( 'uniqueid' => $event->getUniqueId(), 'channel' => $event->getChannel(), 'app' => $event->getApplication(), 'data' => $event->getApplicationData(), 'context' => $event->getContext(), 'priority' => $event->getPriority(), 'exten' => $event->getExtension() )); } }
marcelog/AsterTrace
src/mg/AsterTrace/EventHandlers/NewExtenListener.php
PHP
apache-2.0
1,505
<?php namespace Elastica\Filter; use Elastica\Exception\InvalidException; /** * Geo distance filter * * @category Xodoa * @package Elastica * @author Nicolas Ruflin <spam@ruflin.com> * @link http://www.elasticsearch.org/guide/reference/query-dsl/geo-distance-filter.html */ abstract class AbstractGeoDistance extends AbstractFilter { const LOCATION_TYPE_GEOHASH = 'geohash'; const LOCATION_TYPE_LATLON = 'latlon'; /** * Location type * * Decides if this filter uses latitude/longitude or geohash for the location. * Values are "latlon" or "geohash". * * @var string */ protected $_locationType = null; /** * Key * * @var string */ protected $_key = null; /** * Latitude * * @var float */ protected $_latitude = null; /** * Longitude * * @var float */ protected $_longitude = null; /** * Geohash * * @var string */ protected $_geohash = null; /** * Create GeoDistance object * * @param string $key Key * @param array|string $location Location as array or geohash: array('lat' => 48.86, 'lon' => 2.35) OR 'drm3btev3e86' * @internal param string $distance Distance */ public function __construct($key, $location) { // Key $this->setKey($key); $this->setLocation($location); } /** * @param string $key * @return \Elastica\Filter\AbstractGeoDistance current filter */ public function setKey($key) { $this->_key = $key; return $this; } /** * @param array|string $location * @return \Elastica\Filter\AbstractGeoDistance * @throws \Elastica\Exception\InvalidException */ public function setLocation($location) { // Location if (is_array($location)) { // Latitude/Longitude // Latitude if (isset($location['lat'])) { $this->setLatitude($location['lat']); } else { throw new InvalidException('$location[\'lat\'] has to be set'); } // Longitude if (isset($location['lon'])) { $this->setLongitude($location['lon']); } else { throw new InvalidException('$location[\'lon\'] has to be set'); } } elseif (is_string($location)) { // Geohash $this->setGeohash($location); } else { // Invalid location throw new InvalidException('$location has to be an array (latitude/longitude) or a string (geohash)'); } return $this; } /** * @param float $latitude * @return \Elastica\Filter\AbstractGeoDistance current filter */ public function setLatitude($latitude) { $this->_latitude = (float) $latitude; $this->_locationType = self::LOCATION_TYPE_LATLON; return $this; } /** * @param float $longitude * @return \Elastica\Filter\AbstractGeoDistance current filter */ public function setLongitude($longitude) { $this->_longitude = (float) $longitude; $this->_locationType = self::LOCATION_TYPE_LATLON; return $this; } /** * @param string $geohash * @return \Elastica\Filter\AbstractGeoDistance current filter */ public function setGeohash($geohash) { $this->_geohash = $geohash; $this->_locationType = self::LOCATION_TYPE_GEOHASH; return $this; } /** * @return array|string * @throws \Elastica\Exception\InvalidException */ protected function _getLocationData() { if ($this->_locationType === self::LOCATION_TYPE_LATLON) { // Latitude/longitude $location = array(); if (isset($this->_latitude)) { // Latitude $location['lat'] = $this->_latitude; } else { throw new InvalidException('Latitude has to be set'); } if (isset($this->_longitude)) { // Geohash $location['lon'] = $this->_longitude; } else { throw new InvalidException('Longitude has to be set'); } } elseif ($this->_locationType === self::LOCATION_TYPE_GEOHASH) { // Geohash $location = $this->_geohash; } else { // Invalid location type throw new InvalidException('Invalid location type'); } return $location; } /** * @see \Elastica\Param::toArray() * @throws \Elastica\Exception\InvalidException */ public function toArray() { $this->setParam($this->_key, $this->_getLocationData()); return parent::toArray(); } }
ramanna/elastica
lib/Elastica/Filter/AbstractGeoDistance.php
PHP
apache-2.0
5,209
/** * Copyright (C) 2015 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.fabric8.kubernetes.client.dsl.internal; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.api.model.ListOptions; import io.fabric8.kubernetes.client.Watcher; import io.fabric8.kubernetes.client.http.HttpClient; import io.fabric8.kubernetes.client.http.HttpRequest; import io.fabric8.kubernetes.client.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WatchHTTPManager<T extends HasMetadata, L extends KubernetesResourceList<T>> extends AbstractWatchManager<T> { private static final Logger logger = LoggerFactory.getLogger(WatchHTTPManager.class); private CompletableFuture<HttpResponse<InputStream>> call; public WatchHTTPManager(final HttpClient client, final BaseOperation<T, L, ?> baseOperation, final ListOptions listOptions, final Watcher<T> watcher, final int reconnectInterval, final int reconnectLimit) throws MalformedURLException { // Default max 32x slowdown from base interval this(client, baseOperation, listOptions, watcher, reconnectInterval, reconnectLimit, 5); } public WatchHTTPManager(final HttpClient client, final BaseOperation<T, L, ?> baseOperation, final ListOptions listOptions, final Watcher<T> watcher, final int reconnectInterval, final int reconnectLimit, int maxIntervalExponent) throws MalformedURLException { super( watcher, baseOperation, listOptions, reconnectLimit, reconnectInterval, maxIntervalExponent, () -> client.newBuilder() .readTimeout(0, TimeUnit.MILLISECONDS) .forStreaming() .build()); } @Override protected synchronized void run(URL url, Map<String, String> headers) { HttpRequest.Builder builder = client.newHttpRequestBuilder().url(url); headers.forEach(builder::header); call = client.sendAsync(builder.build(), InputStream.class); call.whenComplete((response, t) -> { if (!call.isCancelled() && t != null) { logger.info("Watch connection failed. reason: {}", t.getMessage()); } if (response != null) { try (InputStream body = response.body()){ if (!response.isSuccessful()) { if (onStatus(OperationSupport.createStatus(response.code(), response.message()))) { return; // terminal state } } else { resetReconnectAttempts(); BufferedReader source = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); String message = null; while ((message = source.readLine()) != null) { onMessage(message); } } } catch (Exception e) { logger.info("Watch terminated unexpectedly. reason: {}", e.getMessage()); } } if (!call.isCancelled()) { scheduleReconnect(); } }); } @Override protected synchronized void closeRequest() { if (call != null) { call.cancel(true); call = null; } } }
fabric8io/kubernetes-client
kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/WatchHTTPManager.java
Java
apache-2.0
4,143
<?php declare(strict_types=1); /** * DO NOT EDIT THIS FILE as it will be overwritten by the Pbj compiler. * @link https://github.com/gdbots/pbjc-php * * Returns an array of curies using mixin "triniti:curator:mixin:has-related-teasers:v1" * @link http://schemas.triniti.io/json-schema/triniti/curator/mixin/has-related-teasers/1-0-0.json# */ return [ ];
triniti/schemas
build/php/src/manifests/triniti/curator/mixin/has-related-teasers/v1.php
PHP
apache-2.0
362
package com.google.api.ads.adwords.jaxws.v201406.cm; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * * Service used to manage campaign feed links, and matching functions. * * * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.4-b01 * Generated source version: 2.1 * */ @WebService(name = "CampaignFeedServiceInterface", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406") @XmlSeeAlso({ ObjectFactory.class }) public interface CampaignFeedServiceInterface { /** * * Returns a list of CampaignFeeds that meet the selector criteria. * * @param selector Determines which CampaignFeeds to return. If empty all * Campaign feeds are returned. * @return The list of CampaignFeeds. * @throws ApiException Indicates a problem with the request. * * * @param selector * @return * returns com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedPage * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406") @RequestWrapper(localName = "get", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfaceget") @ResponseWrapper(localName = "getResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacegetResponse") public CampaignFeedPage get( @WebParam(name = "selector", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406") Selector selector) throws ApiException_Exception ; /** * * Adds, sets or removes CampaignFeeds. * * @param operations The operations to apply. * @return The resulting Feeds. * @throws ApiException Indicates a problem with the request. * * * @param operations * @return * returns com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedReturnValue * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406") @RequestWrapper(localName = "mutate", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacemutate") @ResponseWrapper(localName = "mutateResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacemutateResponse") public CampaignFeedReturnValue mutate( @WebParam(name = "operations", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406") List<CampaignFeedOperation> operations) throws ApiException_Exception ; /** * * Returns a list of {@link CampaignFeed}s inside a {@link CampaignFeedPage} that matches * the query. * * @param query The SQL-like AWQL query string. * @throws ApiException when there are one or more errors with the request. * * * @param query * @return * returns com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedPage * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406") @RequestWrapper(localName = "query", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacequery") @ResponseWrapper(localName = "queryResponse", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406", className = "com.google.api.ads.adwords.jaxws.v201406.cm.CampaignFeedServiceInterfacequeryResponse") public CampaignFeedPage query( @WebParam(name = "query", targetNamespace = "https://adwords.google.com/api/adwords/cm/v201406") String query) throws ApiException_Exception ; }
nafae/developer
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/cm/CampaignFeedServiceInterface.java
Java
apache-2.0
4,521
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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. */ package io.druid.query.extraction; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.metamx.common.StringUtils; import java.nio.ByteBuffer; import java.util.regex.Matcher; import java.util.regex.Pattern; /** */ public class MatchingDimExtractionFn extends DimExtractionFn { private final String expr; private final Pattern pattern; @JsonCreator public MatchingDimExtractionFn( @JsonProperty("expr") String expr ) { Preconditions.checkNotNull(expr, "expr must not be null"); this.expr = expr; this.pattern = Pattern.compile(expr); } @Override public byte[] getCacheKey() { byte[] exprBytes = StringUtils.toUtf8(expr); return ByteBuffer.allocate(1 + exprBytes.length) .put(ExtractionCacheHelper.CACHE_TYPE_ID_MATCHING_DIM) .put(exprBytes) .array(); } @Override public String apply(String dimValue) { Matcher matcher = pattern.matcher(Strings.nullToEmpty(dimValue)); return matcher.find() ? Strings.emptyToNull(dimValue) : null; } @JsonProperty("expr") public String getExpr() { return expr; } @Override public boolean preservesOrdering() { return false; } @Override public ExtractionType getExtractionType() { return ExtractionType.MANY_TO_ONE; } @Override public String toString() { return String.format("regex_matches(%s)", expr); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MatchingDimExtractionFn that = (MatchingDimExtractionFn) o; if (!expr.equals(that.expr)) { return false; } return true; } @Override public int hashCode() { return expr.hashCode(); } }
pdeva/druid
processing/src/main/java/io/druid/query/extraction/MatchingDimExtractionFn.java
Java
apache-2.0
2,777
/* * Copyright 2009-2020 Aarhus University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dk.brics.tajs.analysis.dom.event; import dk.brics.tajs.analysis.InitialStateBuilder; import dk.brics.tajs.analysis.PropVarOperations; import dk.brics.tajs.analysis.Solver; import dk.brics.tajs.analysis.dom.DOMObjects; import dk.brics.tajs.analysis.dom.DOMWindow; import dk.brics.tajs.lattice.ObjectLabel; import dk.brics.tajs.lattice.State; import dk.brics.tajs.lattice.Value; import static dk.brics.tajs.analysis.dom.DOMFunctions.createDOMProperty; public class EventException { public static ObjectLabel CONSTRUCTOR; public static ObjectLabel PROTOTYPE; public static ObjectLabel INSTANCES; public static void build(Solver.SolverInterface c) { State s = c.getState(); PropVarOperations pv = c.getAnalysis().getPropVarOperations(); CONSTRUCTOR = ObjectLabel.make(DOMObjects.EVENT_EXCEPTION_CONSTRUCTOR, ObjectLabel.Kind.FUNCTION); PROTOTYPE = ObjectLabel.make(DOMObjects.EVENT_EXCEPTION_PROTOTYPE, ObjectLabel.Kind.OBJECT); INSTANCES = ObjectLabel.make(DOMObjects.EVENT_EXCEPTION_INSTANCES, ObjectLabel.Kind.OBJECT); // Constructor Object s.newObject(CONSTRUCTOR); pv.writePropertyWithAttributes(CONSTRUCTOR, "length", Value.makeNum(0).setAttributes(true, true, true)); pv.writePropertyWithAttributes(CONSTRUCTOR, "prototype", Value.makeObject(PROTOTYPE).setAttributes(true, true, true)); s.writeInternalPrototype(CONSTRUCTOR, Value.makeObject(InitialStateBuilder.OBJECT_PROTOTYPE)); pv.writeProperty(DOMWindow.WINDOW, "EventException", Value.makeObject(CONSTRUCTOR)); // Prototype object. s.newObject(PROTOTYPE); s.writeInternalPrototype(PROTOTYPE, Value.makeObject(InitialStateBuilder.OBJECT_PROTOTYPE)); // Multiplied object. s.newObject(INSTANCES); s.writeInternalPrototype(INSTANCES, Value.makeObject(PROTOTYPE)); /* * Properties. */ createDOMProperty(INSTANCES, "code", Value.makeAnyNumUInt(), c); s.multiplyObject(INSTANCES); INSTANCES = INSTANCES.makeSingleton().makeSummary(); /* * Constants. */ createDOMProperty(PROTOTYPE, "UNSPECIFIED_EVENT_TYPE_ERR", Value.makeNum(0), c); /* * Functions. */ } }
cs-au-dk/TAJS
src/dk/brics/tajs/analysis/dom/event/EventException.java
Java
apache-2.0
2,982
package com.svcet.cashportal.service; import com.svcet.cashportal.web.beans.UserRequest; import com.svcet.cashportal.web.beans.UserRolesScreenRequest; import com.svcet.cashportal.web.beans.UserRolesScreenResponse; public interface UserRoleService { UserRolesScreenResponse editUserRoles(UserRequest userRequest); void updateUserRoles(UserRolesScreenRequest userRolesScreenRequest); }
blessonkavala/cp
cashportal/src/main/java/com/svcet/cashportal/service/UserRoleService.java
Java
apache-2.0
391
package com.igoldin.qa.school.appmanager; import com.igoldin.qa.school.model.ContactData; import com.igoldin.qa.school.model.Contacts; import com.igoldin.qa.school.model.GroupData; import com.igoldin.qa.school.model.Groups; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import java.util.List; public class DbHelper { private final SessionFactory sessionFactory; public DbHelper() { // A SessionFactory is set up once for an application! final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure() // configures settings from hibernate.cfg.xml .build(); sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory(); } public Groups groups() { Session session = sessionFactory.openSession(); session.beginTransaction(); List<GroupData> result = session.createQuery("from GroupData" ).list(); session.getTransaction().commit(); session.close(); return new Groups(result); } public Contacts contacts() { Session session = sessionFactory.openSession(); session.beginTransaction(); List<ContactData> result = session.createQuery("from ContactData where deprecated = '0000-00-00 00:00:00'" ).list(); session.getTransaction().commit(); session.close(); return new Contacts(result); } }
igoldin74/java_for_testers
addressbook_tests/src/test/java/com/igoldin/qa/school/appmanager/DbHelper.java
Java
apache-2.0
1,614
package org.netbeans.modules.manifestsupport.dataobject; import org.openide.loaders.DataNode; import org.openide.nodes.Children; public class ManifestDataNode extends DataNode { private static final String IMAGE_ICON_BASE = "SET/PATH/TO/ICON/HERE"; public ManifestDataNode(ManifestDataObject obj) { super(obj, Children.LEAF); // setIconBaseWithExtension(IMAGE_ICON_BASE); } // /** Creates a property sheet. */ // protected Sheet createSheet() { // Sheet s = super.createSheet(); // Sheet.Set ss = s.get(Sheet.PROPERTIES); // if (ss == null) { // ss = Sheet.createPropertiesSet(); // s.put(ss); // } // // TODO add some relevant properties: ss.put(...) // return s; // } }
bernhardhuber/netbeansplugins
nb-manifest-support/zip/ManifestSupport/src/org/netbeans/modules/manifestsupport/dataobject/ManifestDataNode.java
Java
apache-2.0
805
<?php session_start(); if(isset($_SESSION['id'])) { $zoubouboubou=$_SESSION['mail']; $id_etudiant=$_SESSION['id']; require_once("includes/connexion.php"); $sql="SELECT id, mail FROM compte_etudiant WHERE id='$id_etudiant'"; $req=mysql_query($sql); $ligne=mysql_fetch_assoc($req); if($id_etudiant==$ligne['id']) { if (isset($_GET['section'])) { $sql="DELETE FROM compte_etudiant WHERE mail='$zoubouboubou'"; mysql_query($sql); mysql_close($db); header('location:index.php'); exit; } elseif (isset($_GET['numeri'])) { $sql="DELETE FROM commande_new WHERE id_etudiant='$id_etudiant'"; mysql_query($sql); mysql_close($db); header('location:accueilUtilisateur.php'); exit; } else { header('location:connexion.php'); exit; } } } else { header('location:index.php'); exit; }
r0mdau/espelette
effUser.php
PHP
apache-2.0
880
using Aggregator.Core.Monitoring; namespace Aggregator.Core.Configuration { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; #pragma warning disable S101 // Types should be named in camel case /// <summary> /// This class represents Core settings as properties /// </summary> /// <remarks>Marked partial to apply nested trick</remarks> public partial class TFSAggregatorSettings #pragma warning restore S101 // Types should be named in camel case { private static readonly char[] ListSeparators = new char[] { ',', ';' }; /// <summary> /// Load configuration from file. Main scenario. /// </summary> /// <param name="settingsPath">Path to policies file</param> /// <param name="logger">Logging object</param> /// <returns>An instance of <see cref="TFSAggregatorSettings"/> or null</returns> public static TFSAggregatorSettings LoadFromFile(string settingsPath, ILogEvents logger) { DateTime lastWriteTime = System.IO.File.GetLastWriteTimeUtc(settingsPath); var parser = new AggregatorSettingsXmlParser(logger); return parser.Parse(lastWriteTime, (xmlLoadOptions) => XDocument.Load(settingsPath, xmlLoadOptions)); } /// <summary> /// Load configuration from string. Used by automated tests. /// </summary> /// <param name="content">Configuration data to parse</param> /// <param name="logger">Logging object</param> /// <returns>An instance of <see cref="TFSAggregatorSettings"/> or null</returns> public static TFSAggregatorSettings LoadXml(string content, ILogEvents logger) { // conventional point in time reference DateTime staticTimestamp = new DateTime(0, DateTimeKind.Utc); var parser = new AggregatorSettingsXmlParser(logger); return parser.Parse(staticTimestamp, (xmlLoadOptions) => XDocument.Parse(content, xmlLoadOptions)); } public LogLevel LogLevel { get; private set; } public string ScriptLanguage { get; private set; } public bool AutoImpersonate { get; private set; } public Uri ServerBaseUrl { get; private set; } public string PersonalToken { get; private set; } public string BasicPassword { get; private set; } public string BasicUsername { get; private set; } public string Hash { get; private set; } public IEnumerable<Snippet> Snippets { get; private set; } public IEnumerable<Function> Functions { get; private set; } public IEnumerable<Rule> Rules { get; private set; } public IEnumerable<Policy> Policies { get; private set; } public bool Debug { get; set; } public RateLimit RateLimit { get; set; } public bool WhatIf { get; set; } public bool IgnoreSslErrors { get; set; } } }
tfsaggregator/tfsaggregator
Aggregator.Core/Aggregator.Core/Configuration/TFSAggregatorSettings.cs
C#
apache-2.0
3,073
/** * Copyright [2009-2010] [dennis zhuang(killme2008@gmail.com)] 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 */ /** * Copyright [2009-2010] [dennis zhuang(killme2008@gmail.com)] Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance with the License. You * may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by * applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License */ package net.rubyeye.xmemcached.command.text; import java.util.Collection; import java.util.concurrent.CountDownLatch; import net.rubyeye.xmemcached.command.Command; import net.rubyeye.xmemcached.command.CommandType; import net.rubyeye.xmemcached.transcoders.CachedData; /** * Get command for text protocol * * @author dennis * */ public class TextGetOneCommand extends TextGetCommand { public TextGetOneCommand(String key, byte[] keyBytes, CommandType cmdType, CountDownLatch latch) { super(key, keyBytes, cmdType, latch); } @Override public void dispatch() { if (this.mergeCount < 0) { // single get if (this.returnValues.get(this.getKey()) == null) { if (!this.wasFirst) { decodeError(); } else { this.countDownLatch(); } } else { CachedData data = this.returnValues.get(this.getKey()); setResult(data); this.countDownLatch(); } } else { // merge get // Collection<Command> mergeCommands = mergeCommands.values(); getIoBuffer().free(); for (Command nextCommand : mergeCommands.values()) { TextGetCommand textGetCommand = (TextGetCommand) nextCommand; textGetCommand.countDownLatch(); if (textGetCommand.assocCommands != null) { for (Command assocCommand : textGetCommand.assocCommands) { assocCommand.countDownLatch(); } } } } } }
killme2008/xmemcached
src/main/java/net/rubyeye/xmemcached/command/text/TextGetOneCommand.java
Java
apache-2.0
2,662
package com.gbaldera.yts.fragments; import android.content.Loader; import com.gbaldera.yts.loaders.PopularMoviesLoader; import com.jakewharton.trakt.entities.Movie; import java.util.List; public class PopularMoviesFragment extends BaseMovieFragment { @Override protected int getLoaderId() { return BaseMovieFragment.POPULAR_MOVIES_LOADER_ID; } @Override protected Loader<List<Movie>> getLoader() { return new PopularMoviesLoader(getActivity()); } }
gbaldera/Yts
app/src/main/java/com/gbaldera/yts/fragments/PopularMoviesFragment.java
Java
apache-2.0
495
using System.Collections.Generic; using System.Windows.Forms; using System.Xml; using System.Xml.XPath; namespace PlaylistEditor { class HTMLHandler { public static string XPathHTML(HtmlElement elem) { string elemXPath = ""; string children = ""; List<string> ParentTagsList = new List<string>(); List<string> TagsList = new List<string>(); while (elem.Parent != null) { //from actual node go to parent HtmlElement prnt = elem.Parent; ParentTagsList.Add(prnt.TagName); children += "|" + prnt.TagName; //loop through all the children foreach (HtmlElement chld in prnt.Children) { //=> this code is retrieving all the paths to the root. //=>I will create an array with it instead of looping trough all the childern of the parent TagsList.Add(chld.TagName); } elem = elem.Parent; TagsList.Add(elem.TagName); } string prevtag = ""; //holds the previous tag to create the duplicate tag index int tagcount = 1; //holds the duplicate tag index foreach (string tag in TagsList) { if (tag == prevtag) { //if (tagcount == 1) //{ // tagcount++; // int prvtaglength = ("/" + tag + "/").Length; // if (prvtaglength > elemXPath.Length - prvtaglength) // { // elemXPath = "/" + tag + "[" + tagcount + "]"; // } // else // { // elemXPath = elemXPath.Substring(prvtaglength, elemXPath.Length - prvtaglength); // elemXPath = "/" + tag + "[" + tagcount + "]/" + elemXPath; // } //} //else //{ int prvtaglength = ("/" + tag + "[" + tagcount + "]/").Length; if (prvtaglength > elemXPath.Length - prvtaglength) { elemXPath = "/" + tag + "[" + tagcount + "]"; } else { elemXPath = elemXPath.Substring(prvtaglength, elemXPath.Length - prvtaglength); tagcount++; elemXPath = "/" + tag + "[" + tagcount + "]/" + elemXPath; } //} } else { tagcount = 1; elemXPath = "/" + tag + "[" + tagcount + "]" + elemXPath; } prevtag = tag; } //this.txtExtracted.Text = children + Environment.NewLine + elemXPath.ToLower(); return elemXPath.ToLower(); } public static string XPathHTMLSimple(HtmlElement elem) { HtmlElement selelem = elem; string elemXPath = ""; string prntXPath = ""; string children = ""; List<string> ParentTagsList = new List<string>(); List<string> TagsList = new List<string>(); //loop through the parents until reaching root while (elem.Parent != null) { //from actual node go to parent HtmlElement prnt = elem.Parent; ParentTagsList.Add(prnt.TagName); prntXPath = getParentLocation(prnt) + prntXPath; elem = elem.Parent; } //Add selected element to path; elemXPath = getParentLocation(selelem); //Join the selected path with the route to root elemXPath = prntXPath + elemXPath; ////br[1]/div[1]/ul[8]/li[1]/a //TODO: The XPath should be shorten to the nearest unique value and use // (from root XPath indicator) //this.txtExtracted.Text = children + Environment.NewLine + elemXPath.ToLower(); return elemXPath.ToLower(); } public static string XPathHTMLtoXMLBackwards(HtmlElement elem) { string prntXPath = ""; List<string> ParentTagsList = new List<string>(); string XMLelem = ""; XPathNavigator xpathNav = null; //Convert selected element to XML XMLelem = XMLHandler.HTMLtoXMLString(elem.OuterHtml); //TODO!! ==V //The search has to be done after the complete document is in xml not using parent and intermediate conversions //the result is not the same XmlDocument prntXDoc = null; //loop through the parents until reaching root while (elem.Parent != null) { //(Using HTMLElement) //from actual node go to parent //HtmlElement prnt = elem.Parent; //ParentTagsList.Add(prnt.TagName); //prntXPath = getParentLocation(prnt) + prntXPath; //(Using HTMLDocument) prntXDoc = XMLHandler.HTMLtoXML(elem.Parent.OuterHtml); string Xelem = XMLHandler.HTMLtoXMLString(elem.OuterHtml); ParentTagsList.Add(prntXDoc.DocumentElement.Name); prntXPath = XMLHandler.getParentXPath(prntXDoc.FirstChild.ChildNodes, Xelem, elem.TagName.ToLower()) + prntXPath; elem = elem.Parent; } if (prntXDoc != null) { prntXPath = "/" + prntXDoc.FirstChild.Name + "[1]" + prntXPath; } ////br[1]/div[1]/ul[8]/li[1]/a ///html[1]/body[1]/br[1]/p[1]/hr[1]/center[1]/hr[1]/p[1]/p[1] //TODO: The XPath should be shorten to the nearest unique value and use // (from root XPath indicator) //this.txtExtracted.Text = prntXPath; return prntXPath.ToLower(); } public static string XPathHTMLtoXML(string html, string elem, string tagname) { string prntXPath = ""; List<string> ParentTagsList = new List<string>(); string XMLelem = ""; //Convert selected element to XML XMLelem = XMLHandler.HTMLtoXMLString(elem); //TODO!! ==V //The search has to be done after the complete document is in xml not using parent and intermediate conversions //the result is not the same XmlDocument prntXDoc = null; prntXDoc = XMLHandler.HTMLtoXML(html); prntXPath = XMLHandler.getChildrenXPath(prntXDoc.FirstChild.ChildNodes, XMLelem) + prntXPath; if (prntXDoc != null) { prntXPath = "//" + prntXDoc.FirstChild.Name + "[1]" + prntXPath; } ////br[1]/div[1]/ul[8]/li[1]/a ///html[1]/body[1]/br[1]/p[1]/hr[1]/center[1]/hr[1]/p[1]/p[1] //TODO: The XPath should be shorten to the nearest unique value and use // (from root XPath indicator) //this.txtExtracted.Text = prntXPath; return prntXPath.ToLower(); } public static string getParentLocation(HtmlElement selelem) { string elemXPath = ""; string prevtag = ""; //holds the previous tag to create the duplicate tag index int tagcount = 0; //holds the duplicate tag index if (selelem.Parent != null && selelem.Parent.Children != null) { foreach (HtmlElement chld in selelem.Parent.Children) { string tag = chld.TagName; if (tag == selelem.TagName)//Only write to XPath if the tag is the same not if it is a sibling. 7-13-2015 { //if (tag == prevtag) //{ tagcount++; int prvtaglength = ("/" + tag + "[" + tagcount + "]/").Length; if (prvtaglength > elemXPath.Length - prvtaglength) { elemXPath = "/" + tag + "[" + tagcount + "]"; } else { elemXPath = elemXPath.Substring(prvtaglength, elemXPath.Length - prvtaglength); tagcount++; elemXPath = elemXPath + "/" + tag + "[" + tagcount + "]"; } //} //else //{ // tagcount = 1; // elemXPath = elemXPath + "/" + tag + "[" + tagcount + "]"; //} } prevtag = tag; if (chld.InnerHtml == selelem.InnerHtml) { break; } } } return elemXPath; } } }
jeborgesm/PlaylistEditor
PlaylistEditor/Objects/HTMLHandler.cs
C#
apache-2.0
9,234
/* * Copyright 2003-2019 Dave Griffith, Bas Leijdekkers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.siyeh.ig.javadoc; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.Navigatable; import com.intellij.psi.*; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.javadoc.PsiDocTag; import com.intellij.psi.javadoc.PsiDocTagValue; import com.intellij.psi.javadoc.PsiDocToken; import com.intellij.psi.util.PsiUtil; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.psiutils.MethodUtils; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import javax.swing.*; final class MissingDeprecatedAnnotationInspection extends BaseInspection { @SuppressWarnings("PublicField") public boolean warnOnMissingJavadoc = false; @Override @NotNull protected String buildErrorString(Object... infos) { final boolean annotationWarning = ((Boolean)infos[0]).booleanValue(); return annotationWarning ? InspectionGadgetsBundle.message("missing.deprecated.annotation.problem.descriptor") : InspectionGadgetsBundle.message("missing.deprecated.tag.problem.descriptor"); } @NotNull @Override public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message("missing.deprecated.tag.option"), this, "warnOnMissingJavadoc"); } @Override public boolean runForWholeFile() { return true; } @Override protected InspectionGadgetsFix buildFix(Object... infos) { final boolean annotationWarning = ((Boolean)infos[0]).booleanValue(); return annotationWarning ? new MissingDeprecatedAnnotationFix() : new MissingDeprecatedTagFix(); } private static class MissingDeprecatedAnnotationFix extends InspectionGadgetsFix { @Override @NotNull public String getFamilyName() { return InspectionGadgetsBundle.message("missing.deprecated.annotation.add.quickfix"); } @Override public void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement identifier = descriptor.getPsiElement(); final PsiModifierListOwner parent = (PsiModifierListOwner)identifier.getParent(); if (parent == null) { return; } final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); final PsiAnnotation annotation = factory.createAnnotationFromText("@java.lang.Deprecated", parent); final PsiModifierList modifierList = parent.getModifierList(); if (modifierList == null) { return; } modifierList.addAfter(annotation, null); } } private static class MissingDeprecatedTagFix extends InspectionGadgetsFix { private static final String DEPRECATED_TAG_NAME = "deprecated"; @Nls(capitalization = Nls.Capitalization.Sentence) @NotNull @Override public String getFamilyName() { return InspectionGadgetsBundle.message("missing.add.deprecated.javadoc.tag.quickfix"); } @Override protected void doFix(Project project, ProblemDescriptor descriptor) { PsiElement parent = descriptor.getPsiElement().getParent(); if (!(parent instanceof PsiJavaDocumentedElement)) { return; } PsiJavaDocumentedElement documentedElement = (PsiJavaDocumentedElement)parent; PsiDocComment docComment = documentedElement.getDocComment(); if (docComment != null) { PsiDocTag existingTag = docComment.findTagByName(DEPRECATED_TAG_NAME); if (existingTag != null) { moveCaretAfter(existingTag); return; } PsiDocTag deprecatedTag = JavaPsiFacade.getElementFactory(project).createDocTagFromText("@" + DEPRECATED_TAG_NAME + " TODO: explain"); PsiElement addedTag = docComment.add(deprecatedTag); moveCaretAfter(addedTag); } else { PsiDocComment newDocComment = JavaPsiFacade.getElementFactory(project).createDocCommentFromText( StringUtil.join("/**\n", " * ", "@" + DEPRECATED_TAG_NAME + " TODO: explain", "\n */") ); PsiElement addedComment = documentedElement.addBefore(newDocComment, documentedElement.getFirstChild()); if (addedComment instanceof PsiDocComment) { PsiDocTag addedTag = ((PsiDocComment)addedComment).findTagByName(DEPRECATED_TAG_NAME); if (addedTag != null) { moveCaretAfter(addedTag); } } } } private static void moveCaretAfter(PsiElement newCaretPosition) { PsiElement sibling = newCaretPosition.getNextSibling(); if (sibling instanceof Navigatable) { ((Navigatable)sibling).navigate(true); } } } @Override public boolean shouldInspect(PsiFile file) { return PsiUtil.isLanguageLevel5OrHigher(file); } @Override public BaseInspectionVisitor buildVisitor() { return new MissingDeprecatedAnnotationVisitor(); } private class MissingDeprecatedAnnotationVisitor extends BaseInspectionVisitor { @Override public void visitModule(@NotNull PsiJavaModule module) { super.visitModule(module); if (hasDeprecatedAnnotation(module)) { if (warnOnMissingJavadoc && !hasDeprecatedComment(module, true)) { registerModuleError(module, Boolean.FALSE); } } else if (hasDeprecatedComment(module, false)) { registerModuleError(module, Boolean.TRUE); } } @Override public void visitClass(@NotNull PsiClass aClass) { super.visitClass(aClass); if (hasDeprecatedAnnotation(aClass)) { if (warnOnMissingJavadoc && !hasDeprecatedComment(aClass, true)) { registerClassError(aClass, Boolean.FALSE); } } else if (hasDeprecatedComment(aClass, false)) { registerClassError(aClass, Boolean.TRUE); } } @Override public void visitMethod(@NotNull PsiMethod method) { if (method.getNameIdentifier() == null) { return; } if (hasDeprecatedAnnotation(method)) { if (warnOnMissingJavadoc) { PsiMethod m = method; while (m != null) { if (hasDeprecatedComment(m, true)) { return; } m = MethodUtils.getSuper(m); } registerMethodError(method, Boolean.FALSE); } } else if (hasDeprecatedComment(method, false)) { registerMethodError(method, Boolean.TRUE); } } @Override public void visitField(@NotNull PsiField field) { if (hasDeprecatedAnnotation(field)) { if (warnOnMissingJavadoc && !hasDeprecatedComment(field, true)) { registerFieldError(field, Boolean.FALSE); } } else if (hasDeprecatedComment(field, false)) { registerFieldError(field, Boolean.TRUE); } } private boolean hasDeprecatedAnnotation(PsiModifierListOwner element) { final PsiModifierList modifierList = element.getModifierList(); return modifierList != null && modifierList.hasAnnotation(CommonClassNames.JAVA_LANG_DEPRECATED); } private boolean hasDeprecatedComment(PsiJavaDocumentedElement documentedElement, boolean checkContent) { final PsiDocComment comment = documentedElement.getDocComment(); if (comment == null) { return false; } final PsiDocTag deprecatedTag = comment.findTagByName("deprecated"); if (deprecatedTag == null) { return false; } if (!checkContent) { return true; } for (PsiElement element : deprecatedTag.getDataElements()) { if (element instanceof PsiDocTagValue || element instanceof PsiDocToken && ((PsiDocToken)element).getTokenType() == JavaDocTokenType.DOC_COMMENT_DATA) { return true; } } return false; } } }
leafclick/intellij-community
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/javadoc/MissingDeprecatedAnnotationInspection.java
Java
apache-2.0
8,667
#!/usr/bin/env ruby # Encoding: utf-8 # # Author:: api.davidtorres@gmail.com (David Torres) # # Copyright:: Copyright 2013, Google Inc. All Rights Reserved. # # License:: Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # This example gets uninvited contacts. To create contacts, run # create_contacts.rb. # # Tags: ContactService.getContactsByStatement. require 'dfp_api' API_VERSION = :v201405 PAGE_SIZE = 500 def get_uninvited_contacts() # Get DfpApi instance and load configuration from ~/dfp_api.yml. dfp = DfpApi::Api.new # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in # the configuration file or provide your own logger: # dfp.logger = Logger.new('dfp_xml.log') # Get the ContactService. contact_service = dfp.service(:ContactService, API_VERSION) # Define initial values. offset = 0 page = {} query_base = 'WHERE status = :status ORDER BY id LIMIT %d OFFSET %d' # Create statement. statement = { :values => [ {:key => 'status', :value => {:value => 'UNINVITED', :xsi_type => 'TextValue'}} ] } begin # Update statement for one page with current offset. statement[:query] = query_base % [PAGE_SIZE, offset] # Get contacts by statement. page = contact_service.get_contacts_by_statement(statement) if page[:results] # Increase query offset by page size. offset += PAGE_SIZE # Get the start index for printout. start_index = page[:start_index] # Print details about each content object in results page. page[:results].each_with_index do |contact, index| puts "%d) Contact ID: %d, name: %s." % [index + start_index, contact[:id], contact[:name]] end end end while offset < page[:total_result_set_size] # Print a footer if page.include?(:total_result_set_size) puts "Total number of results: %d" % page[:total_result_set_size] end end if __FILE__ == $0 begin get_uninvited_contacts() # HTTP errors. rescue AdsCommon::Errors::HttpError => e puts "HTTP Error: %s" % e # API errors. rescue DfpApi::Errors::ApiException => e puts "Message: %s" % e.message puts 'Errors:' e.errors.each_with_index do |error, index| puts "\tError [%d]:" % (index + 1) error.each do |field, value| puts "\t\t%s: %s" % [field, value] end end end end
pngarland/google-api-ads-ruby
dfp_api/examples/v201405/contact_service/get_uninvited_contacts.rb
Ruby
apache-2.0
2,965
package com.google.api.ads.adwords.jaxws.v201406.video; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import com.google.api.ads.adwords.jaxws.v201406.cm.Money; /** * * Class representing the various summary budgets for a campaign page. * * * <p>Java class for SummaryBudgets complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SummaryBudgets"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="totalVideoBudget" type="{https://adwords.google.com/api/adwords/video/v201406}VideoBudget" minOccurs="0"/> * &lt;element name="nonVideoBudget" type="{https://adwords.google.com/api/adwords/cm/v201406}Money" minOccurs="0"/> * &lt;element name="combinedBudget" type="{https://adwords.google.com/api/adwords/cm/v201406}Money" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SummaryBudgets", propOrder = { "totalVideoBudget", "nonVideoBudget", "combinedBudget" }) public class SummaryBudgets { protected VideoBudget totalVideoBudget; protected Money nonVideoBudget; protected Money combinedBudget; /** * Gets the value of the totalVideoBudget property. * * @return * possible object is * {@link VideoBudget } * */ public VideoBudget getTotalVideoBudget() { return totalVideoBudget; } /** * Sets the value of the totalVideoBudget property. * * @param value * allowed object is * {@link VideoBudget } * */ public void setTotalVideoBudget(VideoBudget value) { this.totalVideoBudget = value; } /** * Gets the value of the nonVideoBudget property. * * @return * possible object is * {@link Money } * */ public Money getNonVideoBudget() { return nonVideoBudget; } /** * Sets the value of the nonVideoBudget property. * * @param value * allowed object is * {@link Money } * */ public void setNonVideoBudget(Money value) { this.nonVideoBudget = value; } /** * Gets the value of the combinedBudget property. * * @return * possible object is * {@link Money } * */ public Money getCombinedBudget() { return combinedBudget; } /** * Sets the value of the combinedBudget property. * * @param value * allowed object is * {@link Money } * */ public void setCombinedBudget(Money value) { this.combinedBudget = value; } }
nafae/developer
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/video/SummaryBudgets.java
Java
apache-2.0
3,027
var assert = require("assert"), expect = require('expect.js'), cda = require("../utils/xml.js").cda, DOMParser = require('xmldom').DOMParser, XmlSerializer = require('xmldom').XMLSerializer, xmlUtils = require("../utils/xml.js").xml, FunctionalStatusSectionCreator = require("../Model/FunctionalStatusSection.js"), FunctionalStatusEntryCreator = require("../Model/FunctionalStatusEntry.js"), FunctionalStatusPainScaleEntryCreator = require("../Model/FunctionalStatusPainScaleEntry.js"), Σ = xmlUtils.CreateNode, A = xmlUtils.CreateAttributeWithNameAndValue, adapter = require("../CDA/ModeltoCDA.js").cda; var createMockEntry = function(num) { var entry = FunctionalStatusEntryCreator.create(); entry.Name = "Name " + num; entry.Value = "Value " + num; entry.EffectiveTime = new Date().toString(); return entry; }; var createMockPainScaleEntry = function (num) { var entry = FunctionalStatusPainScaleEntryCreator.create(); entry.id = num; entry.PainScore = 1; entry.PainScoreEffectiveTime = '2/1/2013'; return entry; }; describe("Build Functional Status Section.", function() { it("Should be able to generate an entry for each type.", function() { var e = new adapter.FunctionalStatusSection(); var document = new DOMParser().parseFromString("<?xml version='1.0' standalone='yes'?><ClinicalDocument xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='urn:hl7-org:v3 CDA/infrastructure/cda/CDA_SDTC.xsd' xmlns='urn:hl7-org:v3' xmlns:cda='urn:hl7-org:v3' xmlns:sdtc='urn:hl7-org:sdtc'></ClinicalDocument>", "text/xml"); var section = FunctionalStatusSectionCreator.create(); section.Capabilities.push(createMockEntry(1)); section.Cognitions.push(createMockEntry(1)); section.DailyLivings.push(createMockEntry(1)); section.PainScales.push(createMockPainScaleEntry(1)); var cdaAdapter = new adapter.FunctionalStatusSection(); var node = cdaAdapter.BuildAll(section, document); assert.equal(node.getElementsByTagName("title")[0].childNodes[0].nodeValue, "FUNCTIONAL STATUS"); assert.equal(node.getElementsByTagName("templateId")[0].getAttributeNode("root").value, "2.16.840.1.113883.10.20.22.2.14"); assert.equal(node.getElementsByTagName("code")[0].getAttributeNode("code").value, "47420-5"); //var output = new XmlSerializer().serializeToString(node); //console.log(output); }); });
lantanagroup/SEE-Tool
test/functionalStatus.js
JavaScript
apache-2.0
2,525
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2018 Contributor # # 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. """Contains the logic for `aq add rack --bunker`.""" from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.add_rack import CommandAddRack class CommandAddRackBunker(CommandAddRack): required_parameters = ["bunker", "row", "column"]
quattor/aquilon
lib/aquilon/worker/commands/add_rack_bunker.py
Python
apache-2.0
1,006
package com.rodbate.httpserver.nioserver.old; public interface WriterChannel { }
rodbate/httpserver
src/main/java/com/rodbate/httpserver/nioserver/old/WriterChannel.java
Java
apache-2.0
86
package com.glaf.base.modules.sys.model; import java.io.Serializable; import java.util.Date; public class Dictory implements Serializable { private static final long serialVersionUID = 2756737871937885934L; private long id; private long typeId; private String code; private String name; private int sort; private String desc; private int blocked; private String ext1; private String ext2; private String ext3; private String ext4; private Date ext5; private Date ext6; public int getBlocked() { return blocked; } public String getCode() { return code; } public String getDesc() { return desc; } public String getExt1() { return ext1; } public String getExt2() { return ext2; } public String getExt3() { return ext3; } public String getExt4() { return ext4; } public Date getExt5() { return ext5; } public Date getExt6() { return ext6; } public long getId() { return id; } public String getName() { return name; } public int getSort() { return sort; } public long getTypeId() { return typeId; } public void setBlocked(int blocked) { this.blocked = blocked; } public void setCode(String code) { this.code = code; } public void setDesc(String desc) { this.desc = desc; } public void setExt1(String ext1) { this.ext1 = ext1; } public void setExt2(String ext2) { this.ext2 = ext2; } public void setExt3(String ext3) { this.ext3 = ext3; } public void setExt4(String ext4) { this.ext4 = ext4; } public void setExt5(Date ext5) { this.ext5 = ext5; } public void setExt6(Date ext6) { this.ext6 = ext6; } public void setId(long id) { this.id = id; } public void setName(String name) { this.name = name; } public void setSort(int sort) { this.sort = sort; } public void setTypeId(long typeId) { this.typeId = typeId; } }
jior/glaf-gac
glaf-base/src/main/java/com/glaf/base/modules/sys/model/Dictory.java
Java
apache-2.0
1,856
# Copyright 2018 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import netaddr from rally.common import logging from rally.common.utils import RandomNameGeneratorMixin from rally_ovs.plugins.ovs import ovsclients from rally_ovs.plugins.ovs import utils LOG = logging.getLogger(__name__) class OvnClientMixin(ovsclients.ClientsMixin, RandomNameGeneratorMixin): def _get_ovn_controller(self, install_method="sandbox"): ovn_nbctl = self.controller_client("ovn-nbctl") ovn_nbctl.set_sandbox("controller-sandbox", install_method, self.context['controller']['host_container']) ovn_nbctl.set_daemon_socket(self.context.get("daemon_socket", None)) return ovn_nbctl def _start_daemon(self): ovn_nbctl = self._get_ovn_controller(self.install_method) return ovn_nbctl.start_daemon() def _stop_daemon(self): ovn_nbctl = self._get_ovn_controller(self.install_method) ovn_nbctl.stop_daemon() def _restart_daemon(self): self._stop_daemon() return self._start_daemon() def _create_lswitches(self, lswitch_create_args, num_switches=-1): self.RESOURCE_NAME_FORMAT = "lswitch_XXXXXX_XXXXXX" if (num_switches == -1): num_switches = lswitch_create_args.get("amount", 1) batch = lswitch_create_args.get("batch", num_switches) start_cidr = lswitch_create_args.get("start_cidr", "") if start_cidr: start_cidr = netaddr.IPNetwork(start_cidr) mcast_snoop = lswitch_create_args.get("mcast_snoop", "true") mcast_idle = lswitch_create_args.get("mcast_idle_timeout", 300) mcast_table_size = lswitch_create_args.get("mcast_table_size", 2048) LOG.info("Create lswitches method: %s" % self.install_method) ovn_nbctl = self._get_ovn_controller(self.install_method) ovn_nbctl.enable_batch_mode() flush_count = batch lswitches = [] for i in range(num_switches): name = self.generate_random_name() if start_cidr: cidr = start_cidr.next(i) name = "lswitch_%s" % cidr else: name = self.generate_random_name() other_cfg = { 'mcast_snoop': mcast_snoop, 'mcast_idle_timeout': mcast_idle, 'mcast_table_size': mcast_table_size } lswitch = ovn_nbctl.lswitch_add(name, other_cfg) if start_cidr: lswitch["cidr"] = cidr LOG.info("create %(name)s %(cidr)s" % \ {"name": name, "cidr": lswitch.get("cidr", "")}) lswitches.append(lswitch) flush_count -= 1 if flush_count < 1: ovn_nbctl.flush() flush_count = batch ovn_nbctl.flush() # ensure all commands be run ovn_nbctl.enable_batch_mode(False) return lswitches def _create_routers(self, router_create_args): self.RESOURCE_NAME_FORMAT = "lrouter_XXXXXX_XXXXXX" amount = router_create_args.get("amount", 1) batch = router_create_args.get("batch", 1) ovn_nbctl = self._get_ovn_controller(self.install_method) ovn_nbctl.enable_batch_mode() flush_count = batch lrouters = [] for i in range(amount): name = self.generate_random_name() lrouter = ovn_nbctl.lrouter_add(name) lrouters.append(lrouter) flush_count -= 1 if flush_count < 1: ovn_nbctl.flush() flush_count = batch ovn_nbctl.flush() # ensure all commands be run ovn_nbctl.enable_batch_mode(False) return lrouters def _connect_network_to_router(self, router, network): LOG.info("Connect network %s to router %s" % (network["name"], router["name"])) ovn_nbctl = self.controller_client("ovn-nbctl") ovn_nbctl.set_sandbox("controller-sandbox", self.install_method, self.context['controller']['host_container']) ovn_nbctl.enable_batch_mode(False) base_mac = [i[:2] for i in self.task["uuid"].split('-')] base_mac[0] = str(hex(int(base_mac[0], 16) & 254)) base_mac[3:] = ['00']*3 mac = utils.get_random_mac(base_mac) lrouter_port = ovn_nbctl.lrouter_port_add(router["name"], network["name"], mac, str(network["cidr"])) ovn_nbctl.flush() switch_router_port = "rp-" + network["name"] lport = ovn_nbctl.lswitch_port_add(network["name"], switch_router_port) ovn_nbctl.db_set('Logical_Switch_Port', switch_router_port, ('options', {"router-port":network["name"]}), ('type', 'router'), ('address', 'router')) ovn_nbctl.flush() def _connect_networks_to_routers(self, lnetworks, lrouters, networks_per_router): for lrouter in lrouters: LOG.info("Connect %s networks to router %s" % (networks_per_router, lrouter["name"])) for lnetwork in lnetworks[:networks_per_router]: LOG.info("connect networks %s cidr %s" % (lnetwork["name"], lnetwork["cidr"])) self._connect_network_to_router(lrouter, lnetwork) lnetworks = lnetworks[networks_per_router:]
openvswitch/ovn-scale-test
rally_ovs/plugins/ovs/ovnclients.py
Python
apache-2.0
5,955
<?php // Check for empty fields if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; return false; } $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; // Create the email and send the message $to = 'development@sharay.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to. $email_subject = "Website Contact Form: $name"; $email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message"; $headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com. $headers .= "Reply-To: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
seanwash/sharay.com
mail/contact_me.php
PHP
apache-2.0
1,091
'use strict'; goog.provide('Blockly.JavaScript.serial'); goog.require('Blockly.JavaScript'); Blockly.JavaScript.serial_print = function() { var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '\"\"' var code = 'serial.writeString(\'\' + '+content+');\n'; return code; }; Blockly.JavaScript.serial_println = function() { var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '\"\"' var code = 'serial.writeLine(\'\' + '+content+');\n'; return code; }; Blockly.JavaScript.serial_print_hex = function() { var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '0'; var code = 'serial.writeLine('+content+'.toString(16));\n'; return code; }; Blockly.JavaScript.serial_receive_data_event = function() { var char_marker = Blockly.JavaScript.valueToCode(this, 'char_marker', Blockly.JavaScript.ORDER_ATOMIC) || ';'; var branch = Blockly.JavaScript.statementToCode(this, 'DO'); Blockly.JavaScript.definitions_['func_serial_receive_data_event_' + char_marker.charCodeAt(1)] = "serial.onDataReceived(" + char_marker + ", () => {\n" + branch + "};\n"; }; Blockly.JavaScript.serial_readstr = function() { var code ="serial.readString()"; return [code,Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript.serial_readline = function() { var code ="serial.readLine()"; return [code,Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript.serial_readstr_until = function() { var char_marker = this.getFieldValue('char_marker'); var code ="serial.readUntil("+char_marker + ")"; return [code,Blockly.JavaScript.ORDER_ATOMIC]; }; Blockly.JavaScript.serial_softserial = function () { var dropdown_pin1 = Blockly.JavaScript.valueToCode(this, 'RX',Blockly.JavaScript.ORDER_ATOMIC); var dropdown_pin2 = Blockly.JavaScript.valueToCode(this, 'TX',Blockly.JavaScript.ORDER_ATOMIC); var baudrate = this.getFieldValue('baudrate'); return "serial.redirect(" + dropdown_pin1 + ", " + dropdown_pin2 + ", BaudRate.BaudRate" + baudrate + ");\n"; };
xbed/Mixly_Arduino
mixly_arduino/blockly/generators/microbit_js/serial.js
JavaScript
apache-2.0
2,128
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.cloud.spanner_v1.proto import ( result_set_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2, ) from google.cloud.spanner_v1.proto import ( spanner_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2, ) from google.cloud.spanner_v1.proto import ( transaction_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2, ) from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 class SpannerStub(object): """Cloud Spanner API The Cloud Spanner API can be used to manage sessions and execute transactions on data stored in Cloud Spanner databases. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.CreateSession = channel.unary_unary( "/google.spanner.v1.Spanner/CreateSession", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CreateSessionRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.FromString, ) self.BatchCreateSessions = channel.unary_unary( "/google.spanner.v1.Spanner/BatchCreateSessions", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsResponse.FromString, ) self.GetSession = channel.unary_unary( "/google.spanner.v1.Spanner/GetSession", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.GetSessionRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.FromString, ) self.ListSessions = channel.unary_unary( "/google.spanner.v1.Spanner/ListSessions", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsResponse.FromString, ) self.DeleteSession = channel.unary_unary( "/google.spanner.v1.Spanner/DeleteSession", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.DeleteSessionRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.ExecuteSql = channel.unary_unary( "/google.spanner.v1.Spanner/ExecuteSql", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString, ) self.ExecuteStreamingSql = channel.unary_stream( "/google.spanner.v1.Spanner/ExecuteStreamingSql", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString, ) self.ExecuteBatchDml = channel.unary_unary( "/google.spanner.v1.Spanner/ExecuteBatchDml", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlResponse.FromString, ) self.Read = channel.unary_unary( "/google.spanner.v1.Spanner/Read", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString, ) self.StreamingRead = channel.unary_stream( "/google.spanner.v1.Spanner/StreamingRead", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString, ) self.BeginTransaction = channel.unary_unary( "/google.spanner.v1.Spanner/BeginTransaction", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BeginTransactionRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.FromString, ) self.Commit = channel.unary_unary( "/google.spanner.v1.Spanner/Commit", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitResponse.FromString, ) self.Rollback = channel.unary_unary( "/google.spanner.v1.Spanner/Rollback", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.RollbackRequest.SerializeToString, response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, ) self.PartitionQuery = channel.unary_unary( "/google.spanner.v1.Spanner/PartitionQuery", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionQueryRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.FromString, ) self.PartitionRead = channel.unary_unary( "/google.spanner.v1.Spanner/PartitionRead", request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionReadRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.FromString, ) class SpannerServicer(object): """Cloud Spanner API The Cloud Spanner API can be used to manage sessions and execute transactions on data stored in Cloud Spanner databases. """ def CreateSession(self, request, context): """Creates a new session. A session can be used to perform transactions that read and/or modify data in a Cloud Spanner database. Sessions are meant to be reused for many consecutive transactions. Sessions can only execute one transaction at a time. To execute multiple concurrent read-write/write-only transactions, create multiple sessions. Note that standalone reads and queries use a transaction internally, and count toward the one transaction limit. Active sessions use additional server resources, so it is a good idea to delete idle and unneeded sessions. Aside from explicit deletes, Cloud Spanner can delete sessions for which no operations are sent for more than an hour. If a session is deleted, requests to it return `NOT_FOUND`. Idle sessions can be kept alive by sending a trivial SQL query periodically, e.g., `"SELECT 1"`. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def BatchCreateSessions(self, request, context): """Creates multiple new sessions. This API can be used to initialize a session cache on the clients. See https://goo.gl/TgSFN2 for best practices on session cache management. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def GetSession(self, request, context): """Gets a session. Returns `NOT_FOUND` if the session does not exist. This is mainly useful for determining whether a session is still alive. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def ListSessions(self, request, context): """Lists all sessions in a given database. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def DeleteSession(self, request, context): """Ends a session, releasing server resources associated with it. This will asynchronously trigger cancellation of any operations that are running with this session. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def ExecuteSql(self, request, context): """Executes an SQL statement, returning all results in a single reply. This method cannot be used to return a result set larger than 10 MiB; if the query yields more data than that, the query fails with a `FAILED_PRECONDITION` error. Operations inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. Larger result sets can be fetched in streaming fashion by calling [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def ExecuteStreamingSql(self, request, context): """Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def ExecuteBatchDml(self, request, context): """Executes a batch of SQL DML statements. This method allows many statements to be run with lower latency than submitting them sequentially with [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. Statements are executed in sequential order. A request can succeed even if a statement fails. The [ExecuteBatchDmlResponse.status][google.spanner.v1.ExecuteBatchDmlResponse.status] field in the response provides information about the statement that failed. Clients must inspect this field to determine whether an error occurred. Execution stops after the first failed statement; the remaining statements are not executed. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def Read(self, request, context): """Reads rows from the database using key lookups and scans, as a simple key/value style alternative to [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to return a result set larger than 10 MiB; if the read matches more data than that, the read fails with a `FAILED_PRECONDITION` error. Reads inside read-write transactions might return `ABORTED`. If this occurs, the application should restart the transaction from the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. Larger result sets can be yielded in streaming fashion by calling [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def StreamingRead(self, request, context): """Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the size of the returned result set. However, no individual row in the result set can exceed 100 MiB, and no column value can exceed 10 MiB. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def BeginTransaction(self, request, context): """Begins a new transaction. This step can often be skipped: [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a side-effect. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def Commit(self, request, context): """Commits a transaction. The request includes the mutations to be applied to rows in the database. `Commit` might return an `ABORTED` error. This can occur at any time; commonly, the cause is conflicts with concurrent transactions. However, it can also happen for a variety of other reasons. If `Commit` returns `ABORTED`, the caller should re-attempt the transaction from the beginning, re-using the same session. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def Rollback(self, request, context): """Rolls back a transaction, releasing any locks it holds. It is a good idea to call this for any transaction that includes one or more [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and ultimately decides not to commit. `Rollback` returns `OK` if it successfully aborts the transaction, the transaction was already aborted, or the transaction is not found. `Rollback` never returns `ABORTED`. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def PartitionQuery(self, request, context): """Creates a set of partition tokens that can be used to execute a query operation in parallel. Each of the returned partition tokens can be used by [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] to specify a subset of the query result to read. The same session and read-only transaction must be used by the PartitionQueryRequest used to create the partition tokens and the ExecuteSqlRequests that use the partition tokens. Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the query, and the whole operation must be restarted from the beginning. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def PartitionRead(self, request, context): """Creates a set of partition tokens that can be used to execute a read operation in parallel. Each of the returned partition tokens can be used by [StreamingRead][google.spanner.v1.Spanner.StreamingRead] to specify a subset of the read result to read. The same session and read-only transaction must be used by the PartitionReadRequest used to create the partition tokens and the ReadRequests that use the partition tokens. There are no ordering guarantees on rows returned among the returned partition tokens, or even within each individual StreamingRead call issued with a partition_token. Partition tokens become invalid when the session used to create them is deleted, is idle for too long, begins a new transaction, or becomes too old. When any of these happen, it is not possible to resume the read, and the whole operation must be restarted from the beginning. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def add_SpannerServicer_to_server(servicer, server): rpc_method_handlers = { "CreateSession": grpc.unary_unary_rpc_method_handler( servicer.CreateSession, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CreateSessionRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.SerializeToString, ), "BatchCreateSessions": grpc.unary_unary_rpc_method_handler( servicer.BatchCreateSessions, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BatchCreateSessionsResponse.SerializeToString, ), "GetSession": grpc.unary_unary_rpc_method_handler( servicer.GetSession, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.GetSessionRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.SerializeToString, ), "ListSessions": grpc.unary_unary_rpc_method_handler( servicer.ListSessions, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ListSessionsResponse.SerializeToString, ), "DeleteSession": grpc.unary_unary_rpc_method_handler( servicer.DeleteSession, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.DeleteSessionRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), "ExecuteSql": grpc.unary_unary_rpc_method_handler( servicer.ExecuteSql, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString, ), "ExecuteStreamingSql": grpc.unary_stream_rpc_method_handler( servicer.ExecuteStreamingSql, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString, ), "ExecuteBatchDml": grpc.unary_unary_rpc_method_handler( servicer.ExecuteBatchDml, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteBatchDmlResponse.SerializeToString, ), "Read": grpc.unary_unary_rpc_method_handler( servicer.Read, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString, ), "StreamingRead": grpc.unary_stream_rpc_method_handler( servicer.StreamingRead, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString, ), "BeginTransaction": grpc.unary_unary_rpc_method_handler( servicer.BeginTransaction, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BeginTransactionRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.SerializeToString, ), "Commit": grpc.unary_unary_rpc_method_handler( servicer.Commit, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitResponse.SerializeToString, ), "Rollback": grpc.unary_unary_rpc_method_handler( servicer.Rollback, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.RollbackRequest.FromString, response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, ), "PartitionQuery": grpc.unary_unary_rpc_method_handler( servicer.PartitionQuery, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionQueryRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.SerializeToString, ), "PartitionRead": grpc.unary_unary_rpc_method_handler( servicer.PartitionRead, request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionReadRequest.FromString, response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.PartitionResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( "google.spanner.v1.Spanner", rpc_method_handlers ) server.add_generic_rpc_handlers((generic_handler,))
tseaver/google-cloud-python
spanner/google/cloud/spanner_v1/proto/spanner_pb2_grpc.py
Python
apache-2.0
22,552
package com.comps.util; import com.google.gson.Gson; public class GsonManager { private static Gson instance; public static Gson getInstance(){ if (instance == null){ instance = new Gson(); } return instance; } }
diogocs1/comps
mobile/src/com/comps/util/GsonManager.java
Java
apache-2.0
231
import { IInjectable } from "../common/common"; import { TypedMap } from "../common/common"; import { StateProvider } from "./stateProvider"; import { ResolveContext } from "../resolve/resolveContext"; import * as angular from 'angular'; import IScope = angular.IScope; /** * Annotates a controller expression (may be a controller function(), a "controllername", * or "controllername as name") * * - Temporarily decorates $injector.instantiate. * - Invokes $controller() service * - Calls $injector.instantiate with controller constructor * - Annotate constructor * - Undecorate $injector * * returns an array of strings, which are the arguments of the controller expression */ export declare function annotateController(controllerExpression: (IInjectable | string)): string[]; declare module "../router" { interface UIRouter { /** @hidden TODO: move this to ng1.ts */ stateProvider: StateProvider; } } export declare function watchDigests($rootScope: IScope): void; export declare const getLocals: (ctx: ResolveContext) => TypedMap<any>;
sztymelq/sztymelscy-webpack
node_modules/angular-ui-router/release/ng1/services.d.ts
TypeScript
apache-2.0
1,103
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.09.17 at 02:39:44 오후 KST // package com.athena.chameleon.engine.entity.xml.application.jeus.v5_0; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; /** * <p>Java class for vendorType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="vendorType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}token"> * &lt;enumeration value="oracle"/> * &lt;enumeration value="sybase"/> * &lt;enumeration value="mssql"/> * &lt;enumeration value="db2"/> * &lt;enumeration value="tibero"/> * &lt;enumeration value="informix"/> * &lt;enumeration value="mysql"/> * &lt;enumeration value="others"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlEnum public enum VendorType { @XmlEnumValue("db2") DB_2("db2"), @XmlEnumValue("informix") INFORMIX("informix"), @XmlEnumValue("mssql") MSSQL("mssql"), @XmlEnumValue("mysql") MYSQL("mysql"), @XmlEnumValue("oracle") ORACLE("oracle"), @XmlEnumValue("others") OTHERS("others"), @XmlEnumValue("sybase") SYBASE("sybase"), @XmlEnumValue("tibero") TIBERO("tibero"); private final String value; VendorType(String v) { value = v; } public String value() { return value; } public static VendorType fromValue(String v) { for (VendorType c: VendorType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v.toString()); } }
OpenSourceConsulting/athena-chameleon
src/main/java/com/athena/chameleon/engine/entity/xml/application/jeus/v5_0/VendorType.java
Java
apache-2.0
1,969
package it.unibz.inf.ontop.renderer; /* * #%L * ontop-obdalib-core * %% * Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano * %% * 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. * #L% */ import it.unibz.inf.ontop.io.PrefixManager; import it.unibz.inf.ontop.io.SimplePrefixManager; import it.unibz.inf.ontop.model.Constant; import it.unibz.inf.ontop.model.DatatypeFactory; import it.unibz.inf.ontop.model.ExpressionOperation; import it.unibz.inf.ontop.model.Function; import it.unibz.inf.ontop.model.Predicate; import it.unibz.inf.ontop.model.Term; import it.unibz.inf.ontop.model.URIConstant; import it.unibz.inf.ontop.model.URITemplatePredicate; import it.unibz.inf.ontop.model.ValueConstant; import it.unibz.inf.ontop.model.Variable; import it.unibz.inf.ontop.model.impl.OBDADataFactoryImpl; import it.unibz.inf.ontop.model.impl.OBDAVocabulary; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * A utility class to render a Target Query object into its representational * string. */ public class TargetQueryRenderer { private static final DatatypeFactory dtfac = OBDADataFactoryImpl.getInstance().getDatatypeFactory(); /** * Transforms the given <code>OBDAQuery</code> into a string. The method requires * a prefix manager to shorten full IRI name. */ public static String encode(List<Function> input, PrefixManager prefixManager) { TurtleWriter turtleWriter = new TurtleWriter(); List<Function> body = input; for (Function atom : body) { String subject, predicate, object = ""; String originalString = atom.getFunctionSymbol().toString(); if (isUnary(atom)) { Term subjectTerm = atom.getTerm(0); subject = getDisplayName(subjectTerm, prefixManager); predicate = "a"; object = getAbbreviatedName(originalString, prefixManager, false); if (originalString.equals(object)) { object = "<" + object + ">"; } } else if (originalString.equals("triple")) { Term subjectTerm = atom.getTerm(0); subject = getDisplayName(subjectTerm, prefixManager); Term predicateTerm = atom.getTerm(1); predicate = getDisplayName(predicateTerm, prefixManager); Term objectTerm = atom.getTerm(2); object = getDisplayName(objectTerm, prefixManager); } else { Term subjectTerm = atom.getTerm(0); subject = getDisplayName(subjectTerm, prefixManager); predicate = getAbbreviatedName(originalString, prefixManager, false); if (originalString.equals(predicate)) { predicate = "<" + predicate + ">"; } Term objectTerm = atom.getTerm(1); object = getDisplayName(objectTerm, prefixManager); } turtleWriter.put(subject, predicate, object); } return turtleWriter.print(); } /** * Checks if the atom is unary or not. */ private static boolean isUnary(Function atom) { return atom.getArity() == 1 ? true : false; } /** * Prints the short form of the predicate (by omitting the complete URI and * replacing it by a prefix name). * * Note that by default this method will consider a set of predefined * prefixes, i.e., rdf:, rdfs:, owl:, xsd: and quest: To support this * prefixes the method will temporally add the prefixes if they dont exist * already, taken care to remove them if they didn't exist. * * The implementation requires at the moment, the implementation requires * cloning the existing prefix manager, and hence this is highly inefficient * method. * */ private static String getAbbreviatedName(String uri, PrefixManager pm, boolean insideQuotes) { // Cloning the existing manager PrefixManager prefManClone = new SimplePrefixManager(); Map<String,String> currentMap = pm.getPrefixMap(); for (String prefix: currentMap.keySet()) { prefManClone.addPrefix(prefix, pm.getURIDefinition(prefix)); } return prefManClone.getShortForm(uri, insideQuotes); } private static String appendTerms(Term term){ if (term instanceof Constant){ String st = ((Constant) term).getValue(); if (st.contains("{")){ st = st.replace("{", "\\{"); st = st.replace("}", "\\}"); } return st; }else{ return "{"+((Variable) term).getName()+"}"; } } //Appends nested concats public static void getNestedConcats(StringBuilder stb, Term term1, Term term2){ if (term1 instanceof Function){ Function f = (Function) term1; getNestedConcats(stb, f.getTerms().get(0), f.getTerms().get(1)); }else{ stb.append(appendTerms(term1)); } if (term2 instanceof Function){ Function f = (Function) term2; getNestedConcats(stb, f.getTerms().get(0), f.getTerms().get(1)); }else{ stb.append(appendTerms(term2)); } } /** * Prints the text representation of different terms. */ private static String getDisplayName(Term term, PrefixManager prefixManager) { StringBuilder sb = new StringBuilder(); if (term instanceof Function) { Function function = (Function) term; Predicate functionSymbol = function.getFunctionSymbol(); String fname = getAbbreviatedName(functionSymbol.toString(), prefixManager, false); if (function.isDataTypeFunction()) { // if the function symbol is a data type predicate if (dtfac.isLiteral(functionSymbol)) { // if it is rdfs:Literal int arity = function.getArity(); if (arity == 1) { // without the language tag Term var = function.getTerms().get(0); sb.append(getDisplayName(var, prefixManager)); sb.append("^^rdfs:Literal"); } else if (arity == 2) { // with the language tag Term var = function.getTerms().get(0); Term lang = function.getTerms().get(1); sb.append(getDisplayName(var, prefixManager)); sb.append("@"); if (lang instanceof ValueConstant) { // Don't pass this to getDisplayName() because // language constant is not written as @"lang-tag" sb.append(((ValueConstant) lang).getValue()); } else { sb.append(getDisplayName(lang, prefixManager)); } } } else { // for the other data types Term var = function.getTerms().get(0); sb.append(getDisplayName(var, prefixManager)); sb.append("^^"); sb.append(fname); } } else if (functionSymbol instanceof URITemplatePredicate) { Term firstTerm = function.getTerms().get(0); if(firstTerm instanceof Variable) { sb.append("<{"); sb.append(((Variable) firstTerm).getName()); sb.append("}>"); } else { String template = ((ValueConstant) firstTerm).getValue(); // Utilize the String.format() method so we replaced placeholders '{}' with '%s' String templateFormat = template.replace("{}", "%s"); List<String> varNames = new ArrayList<String>(); for (Term innerTerm : function.getTerms()) { if (innerTerm instanceof Variable) { varNames.add(getDisplayName(innerTerm, prefixManager)); } } String originalUri = String.format(templateFormat, varNames.toArray()); if (originalUri.equals(OBDAVocabulary.RDF_TYPE)) { sb.append("a"); } else { String shortenUri = getAbbreviatedName(originalUri, prefixManager, false); // shorten the URI if possible if (!shortenUri.equals(originalUri)) { sb.append(shortenUri); } else { // If the URI can't be shorten then use the full URI within brackets sb.append("<"); sb.append(originalUri); sb.append(">"); } } } } else if (functionSymbol == ExpressionOperation.CONCAT) { //Concat List<Term> terms = function.getTerms(); sb.append("\""); getNestedConcats(sb, terms.get(0),terms.get(1)); sb.append("\""); //sb.append("^^rdfs:Literal"); } else { // for any ordinary function symbol sb.append(fname); sb.append("("); boolean separator = false; for (Term innerTerm : function.getTerms()) { if (separator) { sb.append(", "); } sb.append(getDisplayName(innerTerm, prefixManager)); separator = true; } sb.append(")"); } } else if (term instanceof Variable) { sb.append("{"); sb.append(((Variable) term).getName()); sb.append("}"); } else if (term instanceof URIConstant) { String originalUri = term.toString(); String shortenUri = getAbbreviatedName(originalUri, prefixManager, false); // shorten the URI if possible if (!shortenUri.equals(originalUri)) { sb.append(shortenUri); } else { // If the URI can't be shorten then use the full URI within brackets sb.append("<"); sb.append(originalUri); sb.append(">"); } } else if (term instanceof ValueConstant) { sb.append("\""); sb.append(((ValueConstant) term).getValue()); sb.append("\""); } return sb.toString(); } private TargetQueryRenderer() { // Prevent initialization } }
srapisarda/ontop
obdalib-core/src/main/java/it/unibz/inf/ontop/renderer/TargetQueryRenderer.java
Java
apache-2.0
9,391
#define SQLITE_ASCII #define SQLITE_DISABLE_LFS #define SQLITE_ENABLE_OVERSIZE_CELL_CHECK #define SQLITE_MUTEX_OMIT #define SQLITE_OMIT_AUTHORIZATION #define SQLITE_OMIT_DEPRECATED #define SQLITE_OMIT_GET_TABLE #define SQLITE_OMIT_INCRBLOB #define SQLITE_OMIT_LOOKASIDE #define SQLITE_OMIT_SHARED_CACHE #define SQLITE_OMIT_UTF16 #define SQLITE_OMIT_WAL #define SQLITE_OS_WIN #define SQLITE_SYSTEM_MALLOC #define VDBE_PROFILE_OFF #define WINDOWS_MOBILE #define NDEBUG #define _MSC_VER #define YYFALLBACK //#define SQLITE_HAS_CODEC using System; using System.Diagnostics; using System.Text; using u8 = System.Byte; using u32 = System.UInt32; namespace Community.CsharpSqlite { using sqlite3_value = Sqlite3.Mem; public partial class Sqlite3 { /* ** 2003 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the ATTACH and DETACH commands. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_OMIT_ATTACH /* ** Resolve an expression that was part of an ATTACH or DETACH statement. This ** is slightly different from resolving a normal SQL expression, because simple ** identifiers are treated as strings, not possible column names or aliases. ** ** i.e. if the parser sees: ** ** ATTACH DATABASE abc AS def ** ** it treats the two expressions as literal strings 'abc' and 'def' instead of ** looking for columns of the same name. ** ** This only applies to the root node of pExpr, so the statement: ** ** ATTACH DATABASE abc||def AS 'db2' ** ** will fail because neither abc or def can be resolved. */ static int resolveAttachExpr( NameContext pName, Expr pExpr ) { int rc = SQLITE_OK; if ( pExpr != null ) { if ( pExpr.op != TK_ID ) { rc = sqlite3ResolveExprNames( pName, ref pExpr ); if ( rc == SQLITE_OK && sqlite3ExprIsConstant( pExpr ) == 0 ) { sqlite3ErrorMsg( pName.pParse, "invalid name: \"%s\"", pExpr.u.zToken ); return SQLITE_ERROR; } } else { pExpr.op = TK_STRING; } } return rc; } /* ** An SQL user-function registered to do the work of an ATTACH statement. The ** three arguments to the function come directly from an attach statement: ** ** ATTACH DATABASE x AS y KEY z ** ** SELECT sqlite_attach(x, y, z) ** ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the ** third argument. */ static void attachFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { int i; int rc = 0; sqlite3 db = sqlite3_context_db_handle( context ); string zName; string zFile; string zPath = ""; string zErr = ""; int flags; Db aNew = null; string zErrDyn = ""; sqlite3_vfs pVfs = null; UNUSED_PARAMETER( NotUsed ); zFile = argv[0].z != null && ( argv[0].z.Length > 0 ) && argv[0].flags != MEM_Null ? sqlite3_value_text( argv[0] ) : ""; zName = argv[1].z != null && ( argv[1].z.Length > 0 ) && argv[1].flags != MEM_Null ? sqlite3_value_text( argv[1] ) : ""; //if( zFile==null ) zFile = ""; //if ( zName == null ) zName = ""; /* Check for the following errors: ** ** * Too many attached databases, ** * Transaction currently open ** * Specified database name already being used. */ if ( db.nDb >= db.aLimit[SQLITE_LIMIT_ATTACHED] + 2 ) { zErrDyn = sqlite3MPrintf( db, "too many attached databases - max %d", db.aLimit[SQLITE_LIMIT_ATTACHED] ); goto attach_error; } if ( 0 == db.autoCommit ) { zErrDyn = sqlite3MPrintf( db, "cannot ATTACH database within transaction" ); goto attach_error; } for ( i = 0; i < db.nDb; i++ ) { string z = db.aDb[i].zName; Debug.Assert( z != null && zName != null ); if ( z.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) ) { zErrDyn = sqlite3MPrintf( db, "database %s is already in use", zName ); goto attach_error; } } /* Allocate the new entry in the db.aDb[] array and initialise the schema ** hash tables. */ /* Allocate the new entry in the db.aDb[] array and initialise the schema ** hash tables. */ //if( db.aDb==db.aDbStatic ){ // aNew = sqlite3DbMallocRaw(db, sizeof(db.aDb[0])*3 ); // if( aNew==0 ) return; // memcpy(aNew, db.aDb, sizeof(db.aDb[0])*2); //}else { if ( db.aDb.Length <= db.nDb ) Array.Resize( ref db.aDb, db.nDb + 1 );//aNew = sqlite3DbRealloc(db, db.aDb, sizeof(db.aDb[0])*(db.nDb+1) ); if ( db.aDb == null ) return; // if( aNew==0 ) return; //} db.aDb[db.nDb] = new Db();//db.aDb = aNew; aNew = db.aDb[db.nDb];//memset(aNew, 0, sizeof(*aNew)); // memset(aNew, 0, sizeof(*aNew)); /* Open the database file. If the btree is successfully opened, use ** it to obtain the database schema. At this point the schema may ** or may not be initialised. */ flags = (int)db.openFlags; rc = sqlite3ParseUri( db.pVfs.zName, zFile, ref flags, ref pVfs, ref zPath, ref zErr ); if ( rc != SQLITE_OK ) { //if ( rc == SQLITE_NOMEM ) //db.mallocFailed = 1; sqlite3_result_error( context, zErr, -1 ); //sqlite3_free( zErr ); return; } Debug.Assert( pVfs != null); flags |= SQLITE_OPEN_MAIN_DB; rc = sqlite3BtreeOpen( pVfs, zPath, db, ref aNew.pBt, 0, (int)flags ); //sqlite3_free( zPath ); db.nDb++; if ( rc == SQLITE_CONSTRAINT ) { rc = SQLITE_ERROR; zErrDyn = sqlite3MPrintf( db, "database is already attached" ); } else if ( rc == SQLITE_OK ) { Pager pPager; aNew.pSchema = sqlite3SchemaGet( db, aNew.pBt ); //if ( aNew.pSchema == null ) //{ // rc = SQLITE_NOMEM; //} //else if ( aNew.pSchema.file_format != 0 && aNew.pSchema.enc != ENC( db ) ) { zErrDyn = sqlite3MPrintf( db, "attached databases must use the same text encoding as main database" ); rc = SQLITE_ERROR; } pPager = sqlite3BtreePager( aNew.pBt ); sqlite3PagerLockingMode( pPager, db.dfltLockMode ); sqlite3BtreeSecureDelete( aNew.pBt, sqlite3BtreeSecureDelete( db.aDb[0].pBt, -1 ) ); } aNew.safety_level = 3; aNew.zName = zName;//sqlite3DbStrDup(db, zName); //if( rc==SQLITE_OK && aNew.zName==0 ){ // rc = SQLITE_NOMEM; //} #if SQLITE_HAS_CODEC if ( rc == SQLITE_OK ) { //extern int sqlite3CodecAttach(sqlite3*, int, const void*, int); //extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); int nKey; string zKey; int t = sqlite3_value_type( argv[2] ); switch ( t ) { case SQLITE_INTEGER: case SQLITE_FLOAT: zErrDyn = "Invalid key value"; //sqlite3DbStrDup( db, "Invalid key value" ); rc = SQLITE_ERROR; break; case SQLITE_TEXT: case SQLITE_BLOB: nKey = sqlite3_value_bytes( argv[2] ); zKey = sqlite3_value_blob( argv[2] ).ToString(); // (char *)sqlite3_value_blob(argv[2]); rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey ); break; case SQLITE_NULL: /* No key specified. Use the key from the main database */ sqlite3CodecGetKey( db, 0, out zKey, out nKey ); //sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey); if ( nKey > 0 || sqlite3BtreeGetReserve( db.aDb[0].pBt ) > 0 ) { rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey ); } break; } } #endif /* If the file was opened successfully, read the schema for the new database. ** If this fails, or if opening the file failed, then close the file and ** remove the entry from the db.aDb[] array. i.e. put everything back the way ** we found it. */ if ( rc == SQLITE_OK ) { sqlite3BtreeEnterAll( db ); rc = sqlite3Init( db, ref zErrDyn ); sqlite3BtreeLeaveAll( db ); } if ( rc != 0 ) { int iDb = db.nDb - 1; Debug.Assert( iDb >= 2 ); if ( db.aDb[iDb].pBt != null ) { sqlite3BtreeClose( ref db.aDb[iDb].pBt ); db.aDb[iDb].pBt = null; db.aDb[iDb].pSchema = null; } sqlite3ResetInternalSchema( db, -1 ); db.nDb = iDb; if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM ) { //// db.mallocFailed = 1; sqlite3DbFree( db, ref zErrDyn ); zErrDyn = sqlite3MPrintf( db, "out of memory" ); } else if ( zErrDyn == "" ) { zErrDyn = sqlite3MPrintf( db, "unable to open database: %s", zFile ); } goto attach_error; } return; attach_error: /* Return an error if we get here */ if ( zErrDyn != "" ) { sqlite3_result_error( context, zErrDyn, -1 ); sqlite3DbFree( db, ref zErrDyn ); } if ( rc != 0 ) sqlite3_result_error_code( context, rc ); } /* ** An SQL user-function registered to do the work of an DETACH statement. The ** three arguments to the function come directly from a detach statement: ** ** DETACH DATABASE x ** ** SELECT sqlite_detach(x) */ static void detachFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { string zName = argv[0].z != null && ( argv[0].z.Length > 0 ) ? sqlite3_value_text( argv[0] ) : "";//(sqlite3_value_text(argv[0]); sqlite3 db = sqlite3_context_db_handle( context ); int i; Db pDb = null; StringBuilder zErr = new StringBuilder( 200 ); UNUSED_PARAMETER( NotUsed ); if ( zName == null ) zName = ""; for ( i = 0; i < db.nDb; i++ ) { pDb = db.aDb[i]; if ( pDb.pBt == null ) continue; if ( pDb.zName.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) ) break; } if ( i >= db.nDb ) { sqlite3_snprintf( 200, zErr, "no such database: %s", zName ); goto detach_error; } if ( i < 2 ) { sqlite3_snprintf( 200, zErr, "cannot detach database %s", zName ); goto detach_error; } if ( 0 == db.autoCommit ) { sqlite3_snprintf( 200, zErr, "cannot DETACH database within transaction" ); goto detach_error; } if ( sqlite3BtreeIsInReadTrans( pDb.pBt ) || sqlite3BtreeIsInBackup( pDb.pBt ) ) { sqlite3_snprintf( 200, zErr, "database %s is locked", zName ); goto detach_error; } sqlite3BtreeClose( ref pDb.pBt ); pDb.pBt = null; pDb.pSchema = null; sqlite3ResetInternalSchema( db, -1 ); return; detach_error: sqlite3_result_error( context, zErr.ToString(), -1 ); } /* ** This procedure generates VDBE code for a single invocation of either the ** sqlite_detach() or sqlite_attach() SQL user functions. */ static void codeAttach( Parse pParse, /* The parser context */ int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */ FuncDef pFunc, /* FuncDef wrapper for detachFunc() or attachFunc() */ Expr pAuthArg, /* Expression to pass to authorization callback */ Expr pFilename, /* Name of database file */ Expr pDbname, /* Name of the database to use internally */ Expr pKey /* Database key for encryption extension */ ) { NameContext sName; Vdbe v; sqlite3 db = pParse.db; int regArgs; sName = new NameContext();// memset( &sName, 0, sizeof(NameContext)); sName.pParse = pParse; if ( SQLITE_OK != resolveAttachExpr( sName, pFilename ) || SQLITE_OK != resolveAttachExpr( sName, pDbname ) || SQLITE_OK != resolveAttachExpr( sName, pKey ) ) { pParse.nErr++; goto attach_end; } #if !SQLITE_OMIT_AUTHORIZATION if( pAuthArg ){ char *zAuthArg; if( pAuthArg->op==TK_STRING ){ zAuthArg = pAuthArg->u.zToken; }else{ zAuthArg = 0; } int rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0); if(rc!=SQLITE_OK ){ goto attach_end; } } #endif //* SQLITE_OMIT_AUTHORIZATION */ v = sqlite3GetVdbe( pParse ); regArgs = sqlite3GetTempRange( pParse, 4 ); sqlite3ExprCode( pParse, pFilename, regArgs ); sqlite3ExprCode( pParse, pDbname, regArgs + 1 ); sqlite3ExprCode( pParse, pKey, regArgs + 2 ); Debug.Assert( v != null /*|| db.mallocFailed != 0 */ ); if ( v != null ) { sqlite3VdbeAddOp3( v, OP_Function, 0, regArgs + 3 - pFunc.nArg, regArgs + 3 ); Debug.Assert( pFunc.nArg == -1 || ( pFunc.nArg & 0xff ) == pFunc.nArg ); sqlite3VdbeChangeP5( v, (u8)( pFunc.nArg ) ); sqlite3VdbeChangeP4( v, -1, pFunc, P4_FUNCDEF ); /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this ** statement only). For DETACH, set it to false (expire all existing ** statements). */ sqlite3VdbeAddOp1( v, OP_Expire, ( type == SQLITE_ATTACH ) ? 1 : 0 ); } attach_end: sqlite3ExprDelete( db, ref pFilename ); sqlite3ExprDelete( db, ref pDbname ); sqlite3ExprDelete( db, ref pKey ); } /* ** Called by the parser to compile a DETACH statement. ** ** DETACH pDbname */ static FuncDef detach_func = new FuncDef( 1, /* nArg */ SQLITE_UTF8, /* iPrefEnc */ 0, /* flags */ null, /* pUserData */ null, /* pNext */ detachFunc, /* xFunc */ null, /* xStep */ null, /* xFinalize */ "sqlite_detach", /* zName */ null, /* pHash */ null /* pDestructor */ ); static void sqlite3Detach( Parse pParse, Expr pDbname ) { codeAttach( pParse, SQLITE_DETACH, detach_func, pDbname, null, null, pDbname ); } /* ** Called by the parser to compile an ATTACH statement. ** ** ATTACH p AS pDbname KEY pKey */ static FuncDef attach_func = new FuncDef( 3, /* nArg */ SQLITE_UTF8, /* iPrefEnc */ 0, /* flags */ null, /* pUserData */ null, /* pNext */ attachFunc, /* xFunc */ null, /* xStep */ null, /* xFinalize */ "sqlite_attach", /* zName */ null, /* pHash */ null /* pDestructor */ ); static void sqlite3Attach( Parse pParse, Expr p, Expr pDbname, Expr pKey ) { codeAttach( pParse, SQLITE_ATTACH, attach_func, p, p, pDbname, pKey ); } #endif // * SQLITE_OMIT_ATTACH */ /* ** Initialize a DbFixer structure. This routine must be called prior ** to passing the structure to one of the sqliteFixAAAA() routines below. ** ** The return value indicates whether or not fixation is required. TRUE ** means we do need to fix the database references, FALSE means we do not. */ static int sqlite3FixInit( DbFixer pFix, /* The fixer to be initialized */ Parse pParse, /* Error messages will be written here */ int iDb, /* This is the database that must be used */ string zType, /* "view", "trigger", or "index" */ Token pName /* Name of the view, trigger, or index */ ) { sqlite3 db; if ( NEVER( iDb < 0 ) || iDb == 1 ) return 0; db = pParse.db; Debug.Assert( db.nDb > iDb ); pFix.pParse = pParse; pFix.zDb = db.aDb[iDb].zName; pFix.zType = zType; pFix.pName = pName; return 1; } /* ** The following set of routines walk through the parse tree and assign ** a specific database to all table references where the database name ** was left unspecified in the original SQL statement. The pFix structure ** must have been initialized by a prior call to sqlite3FixInit(). ** ** These routines are used to make sure that an index, trigger, or ** view in one database does not refer to objects in a different database. ** (Exception: indices, triggers, and views in the TEMP database are ** allowed to refer to anything.) If a reference is explicitly made ** to an object in a different database, an error message is added to ** pParse.zErrMsg and these routines return non-zero. If everything ** checks out, these routines return 0. */ static int sqlite3FixSrcList( DbFixer pFix, /* Context of the fixation */ SrcList pList /* The Source list to check and modify */ ) { int i; string zDb; SrcList_item pItem; if ( NEVER( pList == null ) ) return 0; zDb = pFix.zDb; for ( i = 0; i < pList.nSrc; i++ ) {//, pItem++){ pItem = pList.a[i]; if ( pItem.zDatabase == null ) { pItem.zDatabase = zDb;// sqlite3DbStrDup( pFix.pParse.db, zDb ); } else if ( !pItem.zDatabase.Equals( zDb ,StringComparison.InvariantCultureIgnoreCase ) ) { sqlite3ErrorMsg( pFix.pParse, "%s %T cannot reference objects in database %s", pFix.zType, pFix.pName, pItem.zDatabase ); return 1; } #if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER if ( sqlite3FixSelect( pFix, pItem.pSelect ) != 0 ) return 1; if ( sqlite3FixExpr( pFix, pItem.pOn ) != 0 ) return 1; #endif } return 0; } #if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER static int sqlite3FixSelect( DbFixer pFix, /* Context of the fixation */ Select pSelect /* The SELECT statement to be fixed to one database */ ) { while ( pSelect != null ) { if ( sqlite3FixExprList( pFix, pSelect.pEList ) != 0 ) { return 1; } if ( sqlite3FixSrcList( pFix, pSelect.pSrc ) != 0 ) { return 1; } if ( sqlite3FixExpr( pFix, pSelect.pWhere ) != 0 ) { return 1; } if ( sqlite3FixExpr( pFix, pSelect.pHaving ) != 0 ) { return 1; } pSelect = pSelect.pPrior; } return 0; } static int sqlite3FixExpr( DbFixer pFix, /* Context of the fixation */ Expr pExpr /* The expression to be fixed to one database */ ) { while ( pExpr != null ) { if ( ExprHasAnyProperty( pExpr, EP_TokenOnly ) ) break; if ( ExprHasProperty( pExpr, EP_xIsSelect ) ) { if ( sqlite3FixSelect( pFix, pExpr.x.pSelect ) != 0 ) return 1; } else { if ( sqlite3FixExprList( pFix, pExpr.x.pList ) != 0 ) return 1; } if ( sqlite3FixExpr( pFix, pExpr.pRight ) != 0 ) { return 1; } pExpr = pExpr.pLeft; } return 0; } static int sqlite3FixExprList( DbFixer pFix, /* Context of the fixation */ ExprList pList /* The expression to be fixed to one database */ ) { int i; ExprList_item pItem; if ( pList == null ) return 0; for ( i = 0; i < pList.nExpr; i++ )//, pItem++ ) { pItem = pList.a[i]; if ( sqlite3FixExpr( pFix, pItem.pExpr ) != 0 ) { return 1; } } return 0; } #endif #if !SQLITE_OMIT_TRIGGER static int sqlite3FixTriggerStep( DbFixer pFix, /* Context of the fixation */ TriggerStep pStep /* The trigger step be fixed to one database */ ) { while ( pStep != null ) { if ( sqlite3FixSelect( pFix, pStep.pSelect ) != 0 ) { return 1; } if ( sqlite3FixExpr( pFix, pStep.pWhere ) != 0 ) { return 1; } if ( sqlite3FixExprList( pFix, pStep.pExprList ) != 0 ) { return 1; } pStep = pStep.pNext; } return 0; } #endif } }
hsu1994/Terminator
Client/Assets/Scripts/Air2000/Utility/Sqlite/Sqlite3/source/src/attach_c.cs
C#
apache-2.0
19,135
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ // This code is auto-generated, do not modify package com.spectralogic.ds3client.commands.parsers; import com.spectralogic.ds3client.commands.parsers.interfaces.AbstractResponseParser; import com.spectralogic.ds3client.commands.parsers.utils.ResponseParserUtils; import com.spectralogic.ds3client.commands.spectrads3.ModifyUserSpectraS3Response; import com.spectralogic.ds3client.models.SpectraUser; import com.spectralogic.ds3client.networking.WebResponse; import com.spectralogic.ds3client.serializer.XmlOutput; import java.io.IOException; import java.io.InputStream; public class ModifyUserSpectraS3ResponseParser extends AbstractResponseParser<ModifyUserSpectraS3Response> { private final int[] expectedStatusCodes = new int[]{200}; @Override public ModifyUserSpectraS3Response parseXmlResponse(final WebResponse response) throws IOException { final int statusCode = response.getStatusCode(); if (ResponseParserUtils.validateStatusCode(statusCode, expectedStatusCodes)) { switch (statusCode) { case 200: try (final InputStream inputStream = response.getResponseStream()) { final SpectraUser result = XmlOutput.fromXml(inputStream, SpectraUser.class); return new ModifyUserSpectraS3Response(result, this.getChecksum(), this.getChecksumType()); } default: assert false: "validateStatusCode should have made it impossible to reach this line"; } } throw ResponseParserUtils.createFailedRequest(response, expectedStatusCodes); } }
DenverM80/ds3_java_sdk
ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/parsers/ModifyUserSpectraS3ResponseParser.java
Java
apache-2.0
2,377
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.MessagePopover. sap.ui.define(["jquery.sap.global", "./ResponsivePopover", "./Button", "./Toolbar", "./ToolbarSpacer", "./Bar", "./List", "./StandardListItem", "./library", "sap/ui/core/Control", "./PlacementType", "sap/ui/core/IconPool", "sap/ui/core/HTML", "./Text", "sap/ui/core/Icon", "./SegmentedButton", "./Page", "./NavContainer", "./semantic/SemanticPage", "./Popover", "./MessagePopoverItem", "jquery.sap.dom"], function (jQuery, ResponsivePopover, Button, Toolbar, ToolbarSpacer, Bar, List, StandardListItem, library, Control, PlacementType, IconPool, HTML, Text, Icon, SegmentedButton, Page, NavContainer, SemanticPage, Popover, MessagePopoverItem) { "use strict"; /** * Constructor for a new MessagePopover * * @param {string} [sId] ID for the new control, generated automatically if no id is given * @param {object} [mSettings] Initial settings for the new control * * @class * A MessagePopover is a Popover containing a summarized list with messages. * @extends sap.ui.core.Control * * @author SAP SE * @version 1.36.11 * * @constructor * @public * @since 1.28 * @alias sap.m.MessagePopover * @ui5-metamodel This control also will be described in the legacy UI5 design-time metamodel */ var MessagePopover = Control.extend("sap.m.MessagePopover", /** @lends sap.m.MessagePopover.prototype */ { metadata: { library: "sap.m", properties: { /** * Callback function for resolving a promise after description has been asynchronously loaded inside this function * @callback sap.m.MessagePopover~asyncDescriptionHandler * @param {object} config A single parameter object * @param {MessagePopoverItem} config.item Reference to respective MessagePopoverItem instance * @param {object} config.promise Object grouping a promise's reject and resolve methods * @param {function} config.promise.resolve Method to resolve promise * @param {function} config.promise.reject Method to reject promise */ asyncDescriptionHandler: {type: "any", group: "Behavior", defaultValue: null}, /** * Callback function for resolving a promise after a link has been asynchronously validated inside this function * @callback sap.m.MessagePopover~asyncURLHandler * @param {object} config A single parameter object * @param {string} config.url URL to validate * @param {string|Int} config.id ID of the validation job * @param {object} config.promise Object grouping a promise's reject and resolve methods * @param {function} config.promise.resolve Method to resolve promise * @param {function} config.promise.reject Method to reject promise */ asyncURLHandler: {type: "any", group: "Behavior", defaultValue: null}, /** * Determines the position, where the control will appear on the screen. Possible values are: sap.m.VerticalPlacementType.Top, sap.m.VerticalPlacementType.Bottom and sap.m.VerticalPlacementType.Vertical. * The default value is sap.m.VerticalPlacementType.Vertical. Setting this property while the control is open, will not cause any re-rendering and changing of the position. Changes will only be applied with the next interaction. */ placement: {type: "sap.m.VerticalPlacementType", group: "Behavior", defaultValue: "Vertical"}, /** * Sets the initial state of the control - expanded or collapsed. By default the control opens as expanded */ initiallyExpanded: {type: "boolean", group: "Behavior", defaultValue: true} }, defaultAggregation: "items", aggregations: { /** * A list with message items */ items: {type: "sap.m.MessagePopoverItem", multiple: true, singularName: "item"} }, events: { /** * This event will be fired after the popover is opened */ afterOpen: { parameters: { /** * This refers to the control which opens the popover */ openBy: {type: "sap.ui.core.Control"} } }, /** * This event will be fired after the popover is closed */ afterClose: { parameters: { /** * Refers to the control which opens the popover */ openBy: {type: "sap.ui.core.Control"} } }, /** * This event will be fired before the popover is opened */ beforeOpen: { parameters: { /** * Refers to the control which opens the popover */ openBy: {type: "sap.ui.core.Control"} } }, /** * This event will be fired before the popover is closed */ beforeClose: { parameters: { /** * Refers to the control which opens the popover * See sap.ui.core.MessageType enum values for types */ openBy: {type: "sap.ui.core.Control"} } }, /** * This event will be fired when description is shown */ itemSelect: { parameters: { /** * Refers to the message popover item that is being presented */ item: {type: "sap.m.MessagePopoverItem"}, /** * Refers to the type of messages being shown * See sap.ui.core.MessageType values for types */ messageTypeFilter: {type: "sap.ui.core.MessageType"} } }, /** * This event will be fired when one of the lists is shown when (not) filtered by type */ listSelect: { parameters: { /** * This parameter refers to the type of messages being shown. */ messageTypeFilter: {type: "sap.ui.core.MessageType"} } }, /** * This event will be fired when the long text description data from a remote URL is loaded */ longtextLoaded: {}, /** * This event will be fired when a validation of a URL from long text description is ready */ urlValidated: {} } } }); var CSS_CLASS = "sapMMsgPopover", ICONS = { back: IconPool.getIconURI("nav-back"), close: IconPool.getIconURI("decline"), information: IconPool.getIconURI("message-information"), warning: IconPool.getIconURI("message-warning"), error: IconPool.getIconURI("message-error"), success: IconPool.getIconURI("message-success") }, LIST_TYPES = ["all", "error", "warning", "success", "information"], // Property names array ASYNC_HANDLER_NAMES = ["asyncDescriptionHandler", "asyncURLHandler"], // Private class variable used for static method below that sets default async handlers DEFAULT_ASYNC_HANDLERS = { asyncDescriptionHandler: function (config) { var sLongTextUrl = config.item.getLongtextUrl(); if (sLongTextUrl) { jQuery.ajax({ type: "GET", url: sLongTextUrl, success: function (data) { config.item.setDescription(data); config.promise.resolve(); }, error: function() { var sError = "A request has failed for long text data. URL: " + sLongTextUrl; jQuery.sap.log.error(sError); config.promise.reject(sError); } }); } } }; /** * Setter for default description and URL validation callbacks across all instances of MessagePopover * @static * @protected * @param {object} mDefaultHandlers An object setting default callbacks * @param {function} mDefaultHandlers.asyncDescriptionHandler * @param {function} mDefaultHandlers.asyncURLHandler */ MessagePopover.setDefaultHandlers = function (mDefaultHandlers) { ASYNC_HANDLER_NAMES.forEach(function (sFuncName) { if (mDefaultHandlers.hasOwnProperty(sFuncName)) { DEFAULT_ASYNC_HANDLERS[sFuncName] = mDefaultHandlers[sFuncName]; } }); }; /** * Initializes the control * * @override * @private */ MessagePopover.prototype.init = function () { var that = this; var oPopupControl; this._oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.m"); this._oPopover = new ResponsivePopover(this.getId() + "-messagePopover", { showHeader: false, contentWidth: "440px", placement: this.getPlacement(), showCloseButton: false, modal: false, afterOpen: function (oEvent) { that.fireAfterOpen({openBy: oEvent.getParameter("openBy")}); }, afterClose: function (oEvent) { that._navContainer.backToTop(); that.fireAfterClose({openBy: oEvent.getParameter("openBy")}); }, beforeOpen: function (oEvent) { that.fireBeforeOpen({openBy: oEvent.getParameter("openBy")}); }, beforeClose: function (oEvent) { that.fireBeforeClose({openBy: oEvent.getParameter("openBy")}); } }).addStyleClass(CSS_CLASS); this._createNavigationPages(); this._createLists(); oPopupControl = this._oPopover.getAggregation("_popup"); oPopupControl.oPopup.setAutoClose(false); oPopupControl.addEventDelegate({ onBeforeRendering: this.onBeforeRenderingPopover, onkeypress: this._onkeypress }, this); if (sap.ui.Device.system.phone) { this._oPopover.setBeginButton(new Button({ text: this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE"), press: this.close.bind(this) })); } // Check for default async handlers and set them appropriately ASYNC_HANDLER_NAMES.forEach(function (sFuncName) { if (DEFAULT_ASYNC_HANDLERS.hasOwnProperty(sFuncName)) { that.setProperty(sFuncName, DEFAULT_ASYNC_HANDLERS[sFuncName]); } }); }; /** * Called when the control is destroyed * * @private */ MessagePopover.prototype.exit = function () { this._oResourceBundle = null; this._oListHeader = null; this._oDetailsHeader = null; this._oSegmentedButton = null; this._oBackButton = null; this._navContainer = null; this._listPage = null; this._detailsPage = null; this._sCurrentList = null; if (this._oLists) { this._destroyLists(); } // Destroys ResponsivePopover control that is used by MessagePopover // This will walk through all aggregations in the Popover and destroy them (in our case this is NavContainer) // Next this will walk through all aggregations in the NavContainer, etc. if (this._oPopover) { this._oPopover.destroy(); this._oPopover = null; } }; /** * Required adaptations before rendering MessagePopover * * @private */ MessagePopover.prototype.onBeforeRenderingPopover = function () { // Bind automatically to the MessageModel if no items are bound if (!this.getBindingInfo("items")) { this._makeAutomaticBinding(); } // Update lists only if 'items' aggregation is changed if (this._bItemsChanged) { this._clearLists(); this._fillLists(this.getItems()); this._clearSegmentedButton(); this._fillSegmentedButton(); this._bItemsChanged = false; } this._setInitialFocus(); }; /** * Makes automatic binding to the Message Model with default template * * @private */ MessagePopover.prototype._makeAutomaticBinding = function () { this.setModel(sap.ui.getCore().getMessageManager().getMessageModel(), "message"); this.bindAggregation("items", { path: "message>/", template: new MessagePopoverItem({ type: "{message>type}", title: "{message>title}", description: "{message>description}", longtextUrl: "{message>longtextUrl}" }) } ); }; /** * Handles keyup event * * @param {jQuery.Event} oEvent - keyup event object * @private */ MessagePopover.prototype._onkeypress = function (oEvent) { if (oEvent.shiftKey && oEvent.keyCode == jQuery.sap.KeyCodes.ENTER) { this._fnHandleBackPress(); } }; /** * Returns header of the MessagePopover's ListPage * * @returns {sap.m.Toolbar} ListPage header * @private */ MessagePopover.prototype._getListHeader = function () { return this._oListHeader || this._createListHeader(); }; /** * Returns header of the MessagePopover's ListPage * * @returns {sap.m.Toolbar} DetailsPage header * @private */ MessagePopover.prototype._getDetailsHeader = function () { return this._oDetailsHeader || this._createDetailsHeader(); }; /** * Creates header of MessagePopover's ListPage * * @returns {sap.m.Toolbar} ListPage header * @private */ MessagePopover.prototype._createListHeader = function () { var sCloseBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE"); var sCloseBtnDescrId = this.getId() + "-CloseBtnDescr"; var oCloseBtnARIAHiddenDescr = new HTML(sCloseBtnDescrId, { content: "<span id=\"" + sCloseBtnDescrId + "\" style=\"display: none;\">" + sCloseBtnDescr + "</span>" }); var sHeadingDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_ARIA_HEADING"); var sHeadingDescrId = this.getId() + "-HeadingDescr"; var oHeadingARIAHiddenDescr = new HTML(sHeadingDescrId, { content: "<span id=\"" + sHeadingDescrId + "\" style=\"display: none;\" role=\"heading\">" + sHeadingDescr + "</span>" }); this._oPopover.addAssociation("ariaDescribedBy", sHeadingDescrId, true); var oCloseBtn = new Button({ icon: ICONS["close"], visible: !sap.ui.Device.system.phone, ariaLabelledBy: oCloseBtnARIAHiddenDescr, tooltip: sCloseBtnDescr, press: this.close.bind(this) }).addStyleClass(CSS_CLASS + "CloseBtn"); this._oSegmentedButton = new SegmentedButton(this.getId() + "-segmented", {}).addStyleClass("sapMSegmentedButtonNoAutoWidth"); this._oListHeader = new Toolbar({ content: [this._oSegmentedButton, new ToolbarSpacer(), oCloseBtn, oCloseBtnARIAHiddenDescr, oHeadingARIAHiddenDescr] }); return this._oListHeader; }; /** * Creates header of MessagePopover's ListPage * * @returns {sap.m.Toolbar} DetailsPage header * @private */ MessagePopover.prototype._createDetailsHeader = function () { var sCloseBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_CLOSE"); var sCloseBtnDescrId = this.getId() + "-CloseBtnDetDescr"; var oCloseBtnARIAHiddenDescr = new HTML(sCloseBtnDescrId, { content: "<span id=\"" + sCloseBtnDescrId + "\" style=\"display: none;\">" + sCloseBtnDescr + "</span>" }); var sBackBtnDescr = this._oResourceBundle.getText("MESSAGEPOPOVER_ARIA_BACK_BUTTON"); var sBackBtnDescrId = this.getId() + "-BackBtnDetDescr"; var oBackBtnARIAHiddenDescr = new HTML(sBackBtnDescrId, { content: "<span id=\"" + sBackBtnDescrId + "\" style=\"display: none;\">" + sBackBtnDescr + "</span>" }); var oCloseBtn = new Button({ icon: ICONS["close"], visible: !sap.ui.Device.system.phone, ariaLabelledBy: oCloseBtnARIAHiddenDescr, tooltip: sCloseBtnDescr, press: this.close.bind(this) }).addStyleClass(CSS_CLASS + "CloseBtn"); this._oBackButton = new Button({ icon: ICONS["back"], press: this._fnHandleBackPress.bind(this), ariaLabelledBy: oBackBtnARIAHiddenDescr, tooltip: sBackBtnDescr }); this._oDetailsHeader = new Toolbar({ content: [this._oBackButton, new ToolbarSpacer(), oCloseBtn, oCloseBtnARIAHiddenDescr, oBackBtnARIAHiddenDescr] }); return this._oDetailsHeader; }; /** * Creates navigation pages * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @private */ MessagePopover.prototype._createNavigationPages = function () { // Create two main pages this._listPage = new Page(this.getId() + "listPage", { customHeader: this._getListHeader() }); this._detailsPage = new Page(this.getId() + "-detailsPage", { customHeader: this._getDetailsHeader() }); // TODO: check if this is the best location for this // Disable clicks on disabled and/or pending links this._detailsPage.addEventDelegate({ onclick: function(oEvent) { var target = oEvent.target; if (target.nodeName.toUpperCase() === 'A' && (target.className.indexOf('sapMMsgPopoverItemDisabledLink') !== -1 || target.className.indexOf('sapMMsgPopoverItemPendingLink') !== -1)) { oEvent.preventDefault(); } } }); // Initialize nav container with two main pages this._navContainer = new NavContainer(this.getId() + "-navContainer", { initialPage: this.getId() + "listPage", pages: [this._listPage, this._detailsPage], navigate: this._navigate.bind(this), afterNavigate: this._afterNavigate.bind(this) }); // Assign nav container to content of _oPopover this._oPopover.addContent(this._navContainer); return this; }; /** * Creates Lists of the MessagePopover * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @private */ MessagePopover.prototype._createLists = function () { this._oLists = {}; LIST_TYPES.forEach(function (sListName) { this._oLists[sListName] = new List({ itemPress: this._fnHandleItemPress.bind(this), visible: false }); // no re-rendering this._listPage.addAggregation("content", this._oLists[sListName], true); }, this); return this; }; /** * Destroy items in the MessagePopover's Lists * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @private */ MessagePopover.prototype._clearLists = function () { LIST_TYPES.forEach(function (sListName) { if (this._oLists[sListName]) { this._oLists[sListName].destroyAggregation("items", true); } }, this); return this; }; /** * Destroys internal Lists of the MessagePopover * * @private */ MessagePopover.prototype._destroyLists = function () { LIST_TYPES.forEach(function (sListName) { this._oLists[sListName] = null; }, this); this._oLists = null; }; /** * Fill the list with items * * @param {array} aItems An array with items type of sap.ui.core.Item. * @private */ MessagePopover.prototype._fillLists = function (aItems) { aItems.forEach(function (oMessagePopoverItem) { var oListItem = this._mapItemToListItem(oMessagePopoverItem), oCloneListItem = this._mapItemToListItem(oMessagePopoverItem); // add the mapped item to the List this._oLists["all"].addAggregation("items", oListItem, true); this._oLists[oMessagePopoverItem.getType().toLowerCase()].addAggregation("items", oCloneListItem, true); }, this); }; /** * Map a MessagePopoverItem to StandardListItem * * @param {sap.m.MessagePopoverItem} oMessagePopoverItem Base information to generate the list items * @returns {sap.m.StandardListItem | null} oListItem List item which will be displayed * @private */ MessagePopover.prototype._mapItemToListItem = function (oMessagePopoverItem) { if (!oMessagePopoverItem) { return null; } var sType = oMessagePopoverItem.getType(), oListItem = new StandardListItem({ title: oMessagePopoverItem.getTitle(), icon: this._mapIcon(sType), type: sap.m.ListType.Navigation }).addStyleClass(CSS_CLASS + "Item").addStyleClass(CSS_CLASS + "Item" + sType); oListItem._oMessagePopoverItem = oMessagePopoverItem; return oListItem; }; /** * Map an MessageType to the Icon URL. * * @param {sap.ui.core.ValueState} sIcon Type of Error * @returns {string | null} Icon string * @private */ MessagePopover.prototype._mapIcon = function (sIcon) { if (!sIcon) { return null; } return ICONS[sIcon.toLowerCase()]; }; /** * Destroy the buttons in the SegmentedButton * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @private */ MessagePopover.prototype._clearSegmentedButton = function () { if (this._oSegmentedButton) { this._oSegmentedButton.destroyAggregation("buttons", true); } return this; }; /** * Fill SegmentedButton with needed Buttons for filtering * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @private */ MessagePopover.prototype._fillSegmentedButton = function () { var that = this; var pressClosure = function (sListName) { return function () { that._fnFilterList(sListName); }; }; LIST_TYPES.forEach(function (sListName) { var oList = this._oLists[sListName], iCount = oList.getItems().length, oButton; if (iCount > 0) { oButton = new Button(this.getId() + "-" + sListName, { text: sListName == "all" ? this._oResourceBundle.getText("MESSAGEPOPOVER_ALL") : iCount, icon: ICONS[sListName], press: pressClosure(sListName) }).addStyleClass(CSS_CLASS + "Btn" + sListName.charAt(0).toUpperCase() + sListName.slice(1)); this._oSegmentedButton.addButton(oButton, true); } }, this); return this; }; /** * Sets icon in details page * @param {sap.m.MessagePopoverItem} oMessagePopoverItem * @param {sap.m.StandardListItem} oListItem * @private */ MessagePopover.prototype._setIcon = function (oMessagePopoverItem, oListItem) { this._previousIconTypeClass = CSS_CLASS + "DescIcon" + oMessagePopoverItem.getType(); this._oMessageIcon = new Icon({ src: oListItem.getIcon() }) .addStyleClass(CSS_CLASS + "DescIcon") .addStyleClass(this._previousIconTypeClass); this._detailsPage.addContent(this._oMessageIcon); }; /** * Sets title part of details page * @param {sap.m.MessagePopoverItem} oMessagePopoverItem * @private */ MessagePopover.prototype._setTitle = function (oMessagePopoverItem) { this._oMessageTitleText = new Text(this.getId() + 'MessageTitleText', { text: oMessagePopoverItem.getTitle() }).addStyleClass('sapMMsgPopoverTitleText'); this._detailsPage.addAggregation("content", this._oMessageTitleText); }; /** * Sets description text part of details page * When markup description is used it is sanitized within it's container's setter method (MessagePopoverItem) * @param {sap.m.MessagePopoverItem} oMessagePopoverItem * @private */ MessagePopover.prototype._setDescription = function (oMessagePopoverItem) { if (oMessagePopoverItem.getMarkupDescription()) { // description is sanitized in MessagePopoverItem.setDescription() this._oMessageDescriptionText = new HTML(this.getId() + 'MarkupDescription', { content: "<div class='markupDescription'>" + oMessagePopoverItem.getDescription() + "</div>" }); } else { this._oMessageDescriptionText = new Text(this.getId() + 'MessageDescriptionText', { text: oMessagePopoverItem.getDescription() }).addStyleClass('sapMMsgPopoverDescriptionText'); } this._detailsPage.addContent(this._oMessageDescriptionText); }; MessagePopover.prototype._iNextValidationTaskId = 0; MessagePopover.prototype._validateURL = function (sUrl) { if (jQuery.sap.validateUrl(sUrl)) { return sUrl; } jQuery.sap.log.warning("You have entered invalid URL"); return ''; }; MessagePopover.prototype._queueValidation = function (href) { var fnAsyncURLHandler = this.getAsyncURLHandler(); var iValidationTaskId = ++this._iNextValidationTaskId; var oPromiseArgument = {}; var oPromise = new window.Promise(function(resolve, reject) { oPromiseArgument.resolve = resolve; oPromiseArgument.reject = reject; var config = { url: href, id: iValidationTaskId, promise: oPromiseArgument }; fnAsyncURLHandler(config); }); oPromise.id = iValidationTaskId; return oPromise; }; MessagePopover.prototype._getTagPolicy = function () { var that = this, i; /*global html*/ var defaultTagPolicy = html.makeTagPolicy(this._validateURL()); return function customTagPolicy(tagName, attrs) { var href, validateLink = false; if (tagName.toUpperCase() === "A") { for (i = 0; i < attrs.length;) { // if there is href the link should be validated, href's value is on position(i+1) if (attrs[i] === "href") { validateLink = true; href = attrs[i + 1]; attrs.splice(0, 2); continue; } i += 2; } } // let the default sanitizer do its work // it won't see the href attribute attrs = defaultTagPolicy(tagName, attrs); // if we detected a link before, we modify the <A> tag // and keep the link in a dataset attribute if (validateLink && typeof that.getAsyncURLHandler() === "function") { attrs = attrs || []; var done = false; // first check if there is a class attribute and enrich it with 'sapMMsgPopoverItemDisabledLink' for (i = 0; i < attrs.length; i += 2) { if (attrs[i] === "class") { attrs[i + 1] += "sapMMsgPopoverItemDisabledLink sapMMsgPopoverItemPendingLink"; done = true; break; } } // check for existing id var indexOfId = attrs.indexOf("id"); if (indexOfId > -1) { // we start backwards attrs.splice(indexOfId + 1, 1); attrs.splice(indexOfId, 1); } // if no class attribute was found, add one if (!done) { attrs.unshift("sapMMsgPopoverItemDisabledLink sapMMsgPopoverItemPendingLink"); attrs.unshift("class"); } var oValidation = that._queueValidation(href); // add other attributes attrs.push("href"); // the link is deactivated via class names later read by event delegate on the description page attrs.push(href); // let the page open in another window, so state is preserved attrs.push("target"); attrs.push("_blank"); // use id here as data attributes are not passing through caja attrs.push("id"); attrs.push("sap-ui-" + that.getId() + "-link-under-validation-" + oValidation.id); oValidation .then(function (result) { // Update link in output var $link = jQuery.sap.byId("sap-ui-" + that.getId() + "-link-under-validation-" + result.id); if (result.allowed) { jQuery.sap.log.info("Allow link " + href); } else { jQuery.sap.log.info("Disallow link " + href); } // Adapt the link style $link.removeClass('sapMMsgPopoverItemPendingLink'); $link.toggleClass('sapMMsgPopoverItemDisabledLink', !result.allowed); that.fireUrlValidated(); }) .catch(function () { jQuery.sap.log.warning("Async URL validation could not be performed."); }); } return attrs; }; }; /** * Perform description sanitization based on Caja HTML sanitizer * @param {sap.m.MessagePopoverItem} oMessagePopoverItem * @private */ MessagePopover.prototype._sanitizeDescription = function (oMessagePopoverItem) { jQuery.sap.require("jquery.sap.encoder"); jQuery.sap.require("sap.ui.thirdparty.caja-html-sanitizer"); var tagPolicy = this._getTagPolicy(); /*global html*/ var sanitized = html.sanitizeWithPolicy(oMessagePopoverItem.getDescription(), tagPolicy); oMessagePopoverItem.setDescription(sanitized); this._setDescription(oMessagePopoverItem); }; /** * Handles click of the ListItems * * @param {jQuery.Event} oEvent ListItem click event object * @private */ MessagePopover.prototype._fnHandleItemPress = function (oEvent) { var oListItem = oEvent.getParameter("listItem"), oMessagePopoverItem = oListItem._oMessagePopoverItem; var asyncDescHandler = this.getAsyncDescriptionHandler(); var loadAndNavigateToDetailsPage = function (suppressNavigate) { this._setTitle(oMessagePopoverItem); this._sanitizeDescription(oMessagePopoverItem); this._setIcon(oMessagePopoverItem, oListItem); this.fireLongtextLoaded(); if (!suppressNavigate) { this._navContainer.to(this._detailsPage); } }.bind(this); this._previousIconTypeClass = this._previousIconTypeClass || ''; this.fireItemSelect({ item: oMessagePopoverItem, messageTypeFilter: this._getCurrentMessageTypeFilter() }); this._detailsPage.destroyContent(); if (typeof asyncDescHandler === "function" && !!oMessagePopoverItem.getLongtextUrl()) { // Set markupDescription to true as markup description should be processed as markup oMessagePopoverItem.setMarkupDescription(true); var oPromiseArgument = {}; var oPromise = new window.Promise(function (resolve, reject) { oPromiseArgument.resolve = resolve; oPromiseArgument.reject = reject; }); var proceed = function () { this._detailsPage.setBusy(false); loadAndNavigateToDetailsPage(true); }.bind(this); oPromise .then(function () { proceed(); }) .catch(function () { jQuery.sap.log.warning("Async description loading could not be performed."); proceed(); }); this._navContainer.to(this._detailsPage); this._detailsPage.setBusy(true); asyncDescHandler({ promise: oPromiseArgument, item: oMessagePopoverItem }); } else { loadAndNavigateToDetailsPage(); } this._listPage.$().attr("aria-hidden", "true"); }; /** * Handles click of the BackButton * * @private */ MessagePopover.prototype._fnHandleBackPress = function () { this._listPage.$().removeAttr("aria-hidden"); this._navContainer.back(); }; /** * Handles click of the SegmentedButton * * @param {string} sCurrentListName ListName to be shown * @private */ MessagePopover.prototype._fnFilterList = function (sCurrentListName) { LIST_TYPES.forEach(function (sListIterName) { if (sListIterName != sCurrentListName && this._oLists[sListIterName].getVisible()) { // Hide Lists if they are visible and their name is not the same as current list name this._oLists[sListIterName].setVisible(false); } }, this); this._sCurrentList = sCurrentListName; this._oLists[sCurrentListName].setVisible(true); this._expandMsgPopover(); this.fireListSelect({messageTypeFilter: this._getCurrentMessageTypeFilter()}); }; /** * Returns current selected List name * * @returns {string} Current list name * @private */ MessagePopover.prototype._getCurrentMessageTypeFilter = function () { return this._sCurrentList == "all" ? "" : this._sCurrentList; }; /** * Handles navigate event of the NavContainer * * @private */ MessagePopover.prototype._navigate = function () { if (this._isListPage()) { this._oRestoreFocus = jQuery(document.activeElement); } }; /** * Handles navigate event of the NavContainer * * @private */ MessagePopover.prototype._afterNavigate = function () { // Just wait for the next tick to apply the focus jQuery.sap.delayedCall(0, this, this._restoreFocus); }; /** * Checks whether the current page is ListPage * * @returns {boolean} Whether the current page is ListPage * @private */ MessagePopover.prototype._isListPage = function () { return (this._navContainer.getCurrentPage() == this._listPage); }; /** * Sets initial focus of the control * * @private */ MessagePopover.prototype._setInitialFocus = function () { if (this._isListPage()) { // if current page is the list page - set initial focus to the list. // otherwise use default functionality built-in the popover this._oPopover.setInitialFocus(this._oLists[this._sCurrentList]); } }; /** * Restores the focus after navigation * * @private */ MessagePopover.prototype._restoreFocus = function () { if (this._isListPage()) { var oRestoreFocus = this._oRestoreFocus && this._oRestoreFocus.control(0); if (oRestoreFocus) { oRestoreFocus.focus(); } } else { this._oBackButton.focus(); } }; /** * Restores the state defined by the initiallyExpanded property of the MessagePopover * @private */ MessagePopover.prototype._restoreExpansionDefaults = function () { if (this.getInitiallyExpanded()) { this._fnFilterList("all"); this._oSegmentedButton.setSelectedButton(null); } else { this._collapseMsgPopover(); } }; /** * Expands the MessagePopover so that the width and height are equal * @private */ MessagePopover.prototype._expandMsgPopover = function () { this._oPopover .setContentHeight(this._oPopover.getContentWidth()) .removeStyleClass(CSS_CLASS + "-init"); }; /** * Sets the height of the MessagePopover to auto so that only the header with * the SegmentedButton is visible * @private */ MessagePopover.prototype._collapseMsgPopover = function () { LIST_TYPES.forEach(function (sListName) { this._oLists[sListName].setVisible(false); }, this); this._oPopover .addStyleClass(CSS_CLASS + "-init") .setContentHeight("auto"); this._oSegmentedButton.setSelectedButton("none"); }; /** * Opens the MessagePopover * * @param {sap.ui.core.Control} oControl Control which opens the MessagePopover * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @public * @ui5-metamodel */ MessagePopover.prototype.openBy = function (oControl) { var oResponsivePopoverControl = this._oPopover.getAggregation("_popup"), oParent = oControl.getParent(); // If MessagePopover is opened from an instance of sap.m.Toolbar and is instance of sap.m.Popover remove the Arrow if (oResponsivePopoverControl instanceof Popover) { if ((oParent instanceof Toolbar || oParent instanceof Bar || oParent instanceof SemanticPage)) { oResponsivePopoverControl.setShowArrow(false); } else { oResponsivePopoverControl.setShowArrow(true); } } if (this._oPopover) { this._restoreExpansionDefaults(); this._oPopover.openBy(oControl); } return this; }; /** * Closes the MessagePopover * * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @public */ MessagePopover.prototype.close = function () { if (this._oPopover) { this._oPopover.close(); } return this; }; /** * The method checks if the MessagePopover is open. It returns true when the MessagePopover is currently open * (this includes opening and closing animations), otherwise it returns false * * @public * @returns {boolean} Whether the MessagePopover is open */ MessagePopover.prototype.isOpen = function () { return this._oPopover.isOpen(); }; /** * This method toggles between open and closed state of the MessagePopover instance. * oControl parameter is mandatory in the same way as in 'openBy' method * * @param {sap.ui.core.Control} oControl Control which opens the MessagePopover * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes * @public */ MessagePopover.prototype.toggle = function (oControl) { if (this.isOpen()) { this.close(); } else { this.openBy(oControl); } return this; }; /** * The method sets the placement position of the MessagePopover. Only accepted Values are: * sap.m.PlacementType.Top, sap.m.PlacementType.Bottom and sap.m.PlacementType.Vertical * * @param {sap.m.PlacementType} sPlacement Placement type * @returns {sap.m.MessagePopover} Reference to the 'this' for chaining purposes */ MessagePopover.prototype.setPlacement = function (sPlacement) { this.setProperty("placement", sPlacement, true); this._oPopover.setPlacement(sPlacement); return this; }; MessagePopover.prototype.getDomRef = function (sSuffix) { return this._oPopover && this._oPopover.getAggregation("_popup").getDomRef(sSuffix); }; ["addStyleClass", "removeStyleClass", "toggleStyleClass", "hasStyleClass", "getBusyIndicatorDelay", "setBusyIndicatorDelay", "getVisible", "setVisible", "getBusy", "setBusy"].forEach(function(sName){ MessagePopover.prototype[sName] = function() { if (this._oPopover && this._oPopover[sName]) { var oPopover = this._oPopover; var res = oPopover[sName].apply(oPopover, arguments); return res === oPopover ? this : res; } }; }); // The following inherited methods of this control are extended because this control uses ResponsivePopover for rendering ["setModel", "bindAggregation", "setAggregation", "insertAggregation", "addAggregation", "removeAggregation", "removeAllAggregation", "destroyAggregation"].forEach(function (sFuncName) { // First, they are saved for later reference MessagePopover.prototype["_" + sFuncName + "Old"] = MessagePopover.prototype[sFuncName]; // Once they are called MessagePopover.prototype[sFuncName] = function () { // We immediately call the saved method first var result = MessagePopover.prototype["_" + sFuncName + "Old"].apply(this, arguments); // Then there is additional logic // Mark items aggregation as changed and invalidate popover to trigger rendering // See 'MessagePopover.prototype.onBeforeRenderingPopover' this._bItemsChanged = true; // If Popover dependency has already been instantiated ... if (this._oPopover) { // ... invalidate it this._oPopover.invalidate(); } // If the called method is 'removeAggregation' or 'removeAllAggregation' ... if (["removeAggregation", "removeAllAggregation"].indexOf(sFuncName) !== -1) { // ... return the result of the operation return result; } return this; }; }); return MessagePopover; }, /* bExport= */ true);
pro100den/openui5-bundle
Resources/public/sap/m/MessagePopover-dbg.js
JavaScript
apache-2.0
37,700
using BdlIBMS.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BdlIBMS.Repositories { public interface IUserRepository : IRepository<string, User> { User FindByUserNameAndPassword(string userName, string password); } }
chengliangkaka/PazhouBanghua_BMS
BdlIBMS/Repositories/IUserRepository.cs
C#
apache-2.0
328
package com.github.particlesystem.modifiers; import com.github.particlesystem.Particle; public interface ParticleModifier { /** * modifies the specific value of a particle given the current miliseconds * * @param particle * @param miliseconds */ void apply(Particle particle, long miliseconds); }
rohitiskul/ParticleSystem
particlesystem/src/main/java/com/github/particlesystem/modifiers/ParticleModifier.java
Java
apache-2.0
335
package com.ftfl.icare; import java.util.List; import com.ftfl.icare.adapter.CustomAppointmentAdapter; import com.ftfl.icare.adapter.CustomDoctorAdapter; import com.ftfl.icare.helper.AppointmentDataSource; import com.ftfl.icare.helper.DoctorProfileDataSource; import com.ftfl.icare.model.Appointment; import com.ftfl.icare.model.DoctorProfile; import com.ftfl.icare.util.FragmentHome; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentManager; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class FragmentAppointmentList extends Fragment { TextView mId_tv = null; AppointmentDataSource mAppointmentDataSource; Appointment mAppointment; FragmentManager mFrgManager; Fragment mFragment; Context mContext; ListView mLvProfileList; List<Appointment> mDoctorProfileList; String mId; Bundle mArgs = new Bundle(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_doctor_list, container, false); mContext = container.getContext(); mAppointmentDataSource = new AppointmentDataSource(getActivity()); mDoctorProfileList = mAppointmentDataSource.appointmentList(); CustomAppointmentAdapter arrayAdapter = new CustomAppointmentAdapter( getActivity(), mDoctorProfileList); mLvProfileList = (ListView) view.findViewById(R.id.lvDoctorList); mLvProfileList.setAdapter(arrayAdapter); mLvProfileList .setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final int pos = position; new AlertDialog.Builder(mContext) .setTitle("Delete entry") .setMessage( "Are you sure you want to delete this entry?") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { mAppointmentDataSource = new AppointmentDataSource( getActivity()); if (mAppointmentDataSource.deleteData(Integer .parseInt(mDoctorProfileList .get(pos) .getId())) == true) { Toast toast = Toast .makeText( getActivity(), "Successfully Deleted.", Toast.LENGTH_LONG); toast.show(); mFragment = new FragmentHome(); mFrgManager = getFragmentManager(); mFrgManager .beginTransaction() .replace( R.id.content_frame, mFragment) .commit(); setTitle("Home"); } else { Toast toast = Toast .makeText( getActivity(), "Error, Couldn't inserted data to database", Toast.LENGTH_LONG); toast.show(); } } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { // do nothing } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } }); return view; } public void setTitle(CharSequence title) { getActivity().getActionBar().setTitle(title); } }
FTFL02-ANDROID/julkarnine
ICare/src/com/ftfl/icare/FragmentAppointmentList.java
Java
apache-2.0
3,803
package com.ymsino.water.service.manager.manager; import java.util.List; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * This class was generated by the JAX-WS RI. JAX-WS RI 2.1.3-hudson-390- Generated source version: 2.0 * */ @WebService(name = "ManagerService", targetNamespace = "http://api.service.manager.esb.ymsino.com/") public interface ManagerService { /** * 登录(密码为明文密码,只有状态为开通的管理员才能登录) * * @param mangerId * @param password * @return returns com.ymsino.water.service.manager.manager.ManagerReturn */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "login", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Login") @ResponseWrapper(localName = "loginResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.LoginResponse") public ManagerReturn login(@WebParam(name = "mangerId", targetNamespace = "") String mangerId, @WebParam(name = "password", targetNamespace = "") String password); /** * 保存管理员 * * @param managerSaveParam * @return returns java.lang.Boolean */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "save", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Save") @ResponseWrapper(localName = "saveResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.SaveResponse") public Boolean save(@WebParam(name = "managerSaveParam", targetNamespace = "") ManagerSaveParam managerSaveParam); /** * 根据查询参数获取管理员分页列表 * * @param queryParam * @param startRow * @param pageSize * @return returns java.util.List<com.ymsino.water.service.manager.manager.ManagerReturn> */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "getListpager", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetListpager") @ResponseWrapper(localName = "getListpagerResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetListpagerResponse") public List<ManagerReturn> getListpager(@WebParam(name = "queryParam", targetNamespace = "") QueryParam queryParam, @WebParam(name = "startRow", targetNamespace = "") Integer startRow, @WebParam(name = "pageSize", targetNamespace = "") Integer pageSize); /** * 停用帐号(审核不通过) * * @param mangerId * @return returns java.lang.Boolean */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "closeStatus", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.CloseStatus") @ResponseWrapper(localName = "closeStatusResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.CloseStatusResponse") public Boolean closeStatus(@WebParam(name = "mangerId", targetNamespace = "") String mangerId); /** * 修改管理员 * * @param managerModifyParam * @return returns java.lang.Boolean */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "modify", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.Modify") @ResponseWrapper(localName = "modifyResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.ModifyResponse") public Boolean modify(@WebParam(name = "managerModifyParam", targetNamespace = "") ManagerModifyParam managerModifyParam); /** * 根据查询参数获取管理员记录数 * * @param queryParam * @return returns java.lang.Integer */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "getCount", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetCount") @ResponseWrapper(localName = "getCountResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetCountResponse") public Integer getCount(@WebParam(name = "queryParam", targetNamespace = "") QueryParam queryParam); /** * 启用帐号(审核通过) * * @param managerId * @return returns java.lang.Boolean */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "openStatus", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.OpenStatus") @ResponseWrapper(localName = "openStatusResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.OpenStatusResponse") public Boolean openStatus(@WebParam(name = "managerId", targetNamespace = "") String managerId); /** * 根据管理员id获取管理员实体 * * @param mangerId * @return returns com.ymsino.water.service.manager.manager.ManagerReturn */ @WebMethod @WebResult(targetNamespace = "") @RequestWrapper(localName = "getByManagerId", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetByManagerId") @ResponseWrapper(localName = "getByManagerIdResponse", targetNamespace = "http://api.service.manager.esb.ymsino.com/", className = "com.ymsino.water.service.manager.manager.GetByManagerIdResponse") public ManagerReturn getByManagerId(@WebParam(name = "mangerId", targetNamespace = "") String mangerId); }
xcjava/ymWaterWeb
manager_ws_client/com/ymsino/water/service/manager/manager/ManagerService.java
Java
apache-2.0
6,070
# -*- coding: utf-8 -*- import allure from selenium.webdriver.common.by import By from .base import BasePage from .elements import SimpleInput, SimpleText from .blocks.nav import NavBlock class BrowseMoviePageLocators(object): """Локаторы страницы просмотра информации о фильме""" TITLE_LOCATOR = (By.CSS_SELECTOR, '#movie h2') COUNTRY_LOCATOR = (By.NAME, 'country') DIRECTOR_LOCATOR = (By.NAME, 'director') WRITER_LOCATOR = (By.NAME, 'writer') PRODUCER_LOCATOR = (By.NAME, 'producer') EDIT_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Edit"]') REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class BrowseMoviePage(BasePage): """Страница просмотра информации о фильме""" def __init__(self, driver): super(BrowseMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleText(BrowseMoviePageLocators.TITLE_LOCATOR) director = SimpleText(BrowseMoviePageLocators.DIRECTOR_LOCATOR) writer = SimpleText(BrowseMoviePageLocators.WRITER_LOCATOR) producer = SimpleText(BrowseMoviePageLocators.PRODUCER_LOCATOR) @allure.step('Нажмем на кноку "Edit"') def click_edit_button(self): """ :rtype: EditMoviePage """ self._click(BrowseMoviePageLocators.EDIT_BUTTON_LOCATOR) return EditMoviePage(self._driver) @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(BrowseMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver) class AddMoviePageLocators(object): """Локаторы страницы создания описания фильма""" TITLE_INPUT_LOCATOR = (By.NAME, 'name') TITLE_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="name"].error') ALSO_KNOWN_AS_INPUT_LOCATOR = (By.NAME, 'aka') YEAR_INPUT_LOCATOR = (By.NAME, 'year') YEAR_INPUT_ERROR_LOCATOR = (By.CSS_SELECTOR, 'input[name="year"].error') DURATION_INPUT_LOCATOR = (By.NAME, 'duration') TRAILER_URL_INPUT_LOCATOR = (By.NAME, 'trailer') FORMAT_INPUT_LOCATOR = (By.NAME, 'format') COUNTRY_INPUT_LOCATOR = (By.NAME, 'country') DIRECTOR_INPUT_LOCATOR = (By.NAME, 'director') WRITER_INPUT_LOCATOR = (By.NAME, 'writer') PRODUCER_INPUT_LOCATOR = (By.NAME, 'producer') SAVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Save"]') class AddMoviePage(BasePage): """Страница создания описания фильма""" def __init__(self, driver): super(AddMoviePage, self).__init__(driver) self.nav = NavBlock(driver) title = SimpleInput(AddMoviePageLocators.TITLE_INPUT_LOCATOR, 'название фильма') also_know_as = SimpleInput(AddMoviePageLocators.ALSO_KNOWN_AS_INPUT_LOCATOR, 'оригинальное название фильма') year = SimpleInput(AddMoviePageLocators.YEAR_INPUT_LOCATOR, 'год') duration = SimpleInput(AddMoviePageLocators.DURATION_INPUT_LOCATOR, 'продолжительность') trailer_url = SimpleInput(AddMoviePageLocators.TRAILER_URL_INPUT_LOCATOR, 'адрес трейлера') format = SimpleInput(AddMoviePageLocators.FORMAT_INPUT_LOCATOR, 'формат') country = SimpleInput(AddMoviePageLocators.COUNTRY_INPUT_LOCATOR, 'страну') director = SimpleInput(AddMoviePageLocators.DIRECTOR_INPUT_LOCATOR, 'директора') writer = SimpleInput(AddMoviePageLocators.WRITER_INPUT_LOCATOR, 'сценариста') producer = SimpleInput(AddMoviePageLocators.PRODUCER_INPUT_LOCATOR, 'продюсера') @allure.step('Нажмем на кноку "Save"') def click_save_button(self): """ :rtype: BrowseMoviePage """ self._click(AddMoviePageLocators.SAVE_BUTTON_LOCATOR) return BrowseMoviePage(self._driver) def title_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.TITLE_INPUT_ERROR_LOCATOR) def year_field_is_required_present(self): """ :rtype: bool """ return self._is_element_present(AddMoviePageLocators.YEAR_INPUT_ERROR_LOCATOR) class EditMoviePageLocators(object): """Локаторы для страницы редактирования описания фильма""" REMOVE_BUTTON_LOCATOR = (By.CSS_SELECTOR, 'img[title="Remove"]') class EditMoviePage(AddMoviePage): """Страница редактирования описания фильма""" @allure.step('Нажмем на кноку "Remove"') def click_remove_button(self): """ :rtype: HomePage """ self._click(EditMoviePageLocators.REMOVE_BUTTON_LOCATOR) self.alert_accept() from .home import HomePage return HomePage(self._driver)
adv-tsk/Course-Se-Python
php4dvd/pages/movie.py
Python
apache-2.0
5,067
package app.yweather.com.yweather.util; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import org.json.JSONArray; import org.json.JSONObject; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * 解析JSON工具类 */ public class Utility { //解析服务器返回的JSON数据,并将解析出的数据存储到本地。 public static void handleWeatherResponse(Context context, String response){ try{ JSONArray jsonObjs = new JSONObject(response).getJSONArray("results"); JSONObject locationJsonObj = ((JSONObject)jsonObjs.opt(0)).getJSONObject("location"); String id = locationJsonObj.getString("id"); String name = locationJsonObj.getString("name"); JSONObject nowJsonObj = ((JSONObject)jsonObjs.opt(0)).getJSONObject("now"); String text = nowJsonObj.getString("text"); String temperature = nowJsonObj.getString("temperature"); String wind = nowJsonObj.getString("wind_direction"); String lastUpdateTime = ((JSONObject) jsonObjs.opt(0)).getString("last_update"); lastUpdateTime = lastUpdateTime.substring(lastUpdateTime.indexOf("+") + 1,lastUpdateTime.length()); LogUtil.e("Utility", "name:" + name + ",text:"+ text + "wind:" + wind + ",lastUpdateTime:" + lastUpdateTime); saveWeatherInfo(context,name,id,temperature,text,lastUpdateTime); }catch (Exception e){ e.printStackTrace(); } } /** * 将服务器返回的天气信息存储到SharedPreferences文件中 * context : Context对象 * cityName : 城市名称 * cityId : 城市id * temperature: 温度 * text :天气现象文字说明,如多云 * lastUpdateTime : 数据更新时间 * 2016-07-16T13:10:00+08:00 */ @TargetApi(Build.VERSION_CODES.N) //指定使用的系统版本 public static void saveWeatherInfo(Context context, String cityName, String cityId, String temperature, String text, String lastUpdateTime){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日", Locale.CANADA); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putBoolean("city_selected",true); editor.putString("city_name",cityName); editor.putString("city_id",cityId); editor.putString("temperature",temperature); editor.putString("text",text); editor.putString("last_update_time",lastUpdateTime); editor.putString("current_date",sdf.format(new Date())); editor.commit(); } }
llxyhuang/YWeather
app/src/main/java/app/yweather/com/yweather/util/Utility.java
Java
apache-2.0
2,845
/* * Copyright (C) 2017 grandcentrix GmbH * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.grandcentrix.thirtyinch; import android.content.res.Configuration; import android.os.Bundle; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import java.util.List; import java.util.concurrent.Executor; import net.grandcentrix.thirtyinch.internal.DelegatedTiActivity; import net.grandcentrix.thirtyinch.internal.InterceptableViewBinder; import net.grandcentrix.thirtyinch.internal.PresenterAccessor; import net.grandcentrix.thirtyinch.internal.PresenterSavior; import net.grandcentrix.thirtyinch.internal.TiActivityDelegate; import net.grandcentrix.thirtyinch.internal.TiLoggingTagProvider; import net.grandcentrix.thirtyinch.internal.TiPresenterProvider; import net.grandcentrix.thirtyinch.internal.TiViewProvider; import net.grandcentrix.thirtyinch.internal.UiThreadExecutor; import net.grandcentrix.thirtyinch.util.AnnotationUtil; /** * An Activity which has a {@link TiPresenter} to build the Model View Presenter architecture on * Android. * * <p> * The {@link TiPresenter} will be created in {@link #providePresenter()} called in * {@link #onCreate(Bundle)}. Depending on the {@link TiConfiguration} passed into the * {@link TiPresenter#TiPresenter(TiConfiguration)} constructor the {@link TiPresenter} survives * orientation changes (default). * </p> * <p> * The {@link TiPresenter} requires a interface to communicate with the View. Normally the Activity * implements the View interface (which must extend {@link TiView}) and is returned by default * from {@link #provideView()}. * </p> * * <p> * Example: * <code> * <pre> * public class MyActivity extends TiActivity&lt;MyPresenter, MyView&gt; implements MyView { * * &#064;Override * public MyPresenter providePresenter() { * return new MyPresenter(); * } * } * * public class MyPresenter extends TiPresenter&lt;MyView&gt; { * * &#064;Override * protected void onCreate() { * super.onCreate(); * } * } * * public interface MyView extends TiView { * * // void showItems(List&lt;Item&gt; items); * * // Observable&lt;Item&gt; onItemClicked(); * } * </pre> * </code> * </p> * * @param <V> the View type, must implement {@link TiView} * @param <P> the Presenter type, must extend {@link TiPresenter} */ public abstract class TiActivity<P extends TiPresenter<V>, V extends TiView> extends AppCompatActivity implements TiPresenterProvider<P>, TiViewProvider<V>, DelegatedTiActivity, TiLoggingTagProvider, InterceptableViewBinder<V>, PresenterAccessor<P, V> { private final String TAG = this.getClass().getSimpleName() + ":" + TiActivity.class.getSimpleName() + "@" + Integer.toHexString(this.hashCode()); private final TiActivityDelegate<P, V> mDelegate = new TiActivityDelegate<>(this, this, this, this, PresenterSavior.getInstance()); private final UiThreadExecutor mUiThreadExecutor = new UiThreadExecutor(); @CallSuper @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDelegate.onCreate_afterSuper(savedInstanceState); } @CallSuper @Override protected void onStart() { super.onStart(); mDelegate.onStart_afterSuper(); } @CallSuper @Override protected void onStop() { mDelegate.onStop_beforeSuper(); super.onStop(); mDelegate.onStop_afterSuper(); } @CallSuper @Override protected void onSaveInstanceState(@NonNull final Bundle outState) { super.onSaveInstanceState(outState); mDelegate.onSaveInstanceState_afterSuper(outState); } @CallSuper @Override protected void onDestroy() { super.onDestroy(); mDelegate.onDestroy_afterSuper(); } @NonNull @Override public final Removable addBindViewInterceptor(@NonNull final BindViewInterceptor interceptor) { return mDelegate.addBindViewInterceptor(interceptor); } @Override public final Object getHostingContainer() { return this; } @Nullable @Override public final V getInterceptedViewOf(@NonNull final BindViewInterceptor interceptor) { return mDelegate.getInterceptedViewOf(interceptor); } @NonNull @Override public final List<BindViewInterceptor> getInterceptors( @NonNull final Filter<BindViewInterceptor> predicate) { return mDelegate.getInterceptors(predicate); } @Override public String getLoggingTag() { return TAG; } /** * is {@code null} before {@link #onCreate(Bundle)} */ @Override public final P getPresenter() { return mDelegate.getPresenter(); } @Override public final Executor getUiThreadExecutor() { return mUiThreadExecutor; } /** * Invalidates the cache of the latest bound view. Forces the next binding of the view to run * through all the interceptors (again). */ @Override public final void invalidateView() { mDelegate.invalidateView(); } @Override public final boolean isActivityFinishing() { return isFinishing(); } @CallSuper @Override public void onConfigurationChanged(@NonNull final Configuration newConfig) { super.onConfigurationChanged(newConfig); mDelegate.onConfigurationChanged_afterSuper(newConfig); } @SuppressWarnings("unchecked") @NonNull @Override public V provideView() { final Class<?> foundViewInterface = AnnotationUtil .getInterfaceOfClassExtendingGivenInterface(this.getClass(), TiView.class); if (foundViewInterface == null) { throw new IllegalArgumentException( "This Activity doesn't implement a TiView interface. " + "This is the default behaviour. Override provideView() to explicitly change this."); } else { if (foundViewInterface.getSimpleName().equals("TiView")) { throw new IllegalArgumentException( "extending TiView doesn't make sense, it's an empty interface." + " This is the default behaviour. Override provideView() to explicitly change this."); } else { // assume that the activity itself is the view and implements the TiView interface return (V) this; } } } @Override public String toString() { String presenter = mDelegate.getPresenter() == null ? "null" : mDelegate.getPresenter().getClass().getSimpleName() + "@" + Integer.toHexString(mDelegate.getPresenter().hashCode()); return getClass().getSimpleName() + ":" + TiActivity.class.getSimpleName() + "@" + Integer.toHexString(hashCode()) + "{presenter = " + presenter + "}"; } }
grandcentrix/ThirtyInch
thirtyinch/src/main/java/net/grandcentrix/thirtyinch/TiActivity.java
Java
apache-2.0
7,692
/*jslint browser: true*/ /*global $, jQuery, alert*/ (function ($) { "use strict"; $(document).ready(function () { $("input[name=dob]").datepicker({ dateFormat: 'yy-mm-dd', inline: true, showOtherMonths: true }); }); $(document).ready(function () { $("input[name='rep_password']").focusout(function () { var p1 = $('input[name="password"]').val(), p2 = $('input[name="rep_password"]').val(); if (p1 !== p2) { $('#passDM').show(300); } else if (p1 === "") { $('#passDM').show(300); } else { $('#passDM').hide(300); } }); }); $(document).ready(function () { $("input[name=password]").focusin(function () { $('#passDM').hide(300); }); $("input[name=rep_password]").focusin(function () { $('#passDM').hide(300); }); }); }(jQuery));
manoj2509/Sensa
js/logIn.js
JavaScript
apache-2.0
1,018
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V. licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. // // Code generated from specification version 7.7.0: DO NOT EDIT package esapi import ( "context" "io" "net/http" "strings" ) func newAutoscalingPutAutoscalingPolicyFunc(t Transport) AutoscalingPutAutoscalingPolicy { return func(name string, body io.Reader, o ...func(*AutoscalingPutAutoscalingPolicyRequest)) (*Response, error) { var r = AutoscalingPutAutoscalingPolicyRequest{Name: name, Body: body} for _, f := range o { f(&r) } return r.Do(r.ctx, t) } } // ----- API Definition ------------------------------------------------------- // AutoscalingPutAutoscalingPolicy - // // This API is experimental. // // See full documentation at https://www.elastic.co/guide/en/elasticsearch/reference/current/autoscaling-put-autoscaling-policy.html. // type AutoscalingPutAutoscalingPolicy func(name string, body io.Reader, o ...func(*AutoscalingPutAutoscalingPolicyRequest)) (*Response, error) // AutoscalingPutAutoscalingPolicyRequest configures the Autoscaling Put Autoscaling Policy API request. // type AutoscalingPutAutoscalingPolicyRequest struct { Body io.Reader Name string Pretty bool Human bool ErrorTrace bool FilterPath []string Header http.Header ctx context.Context } // Do executes the request and returns response or error. // func (r AutoscalingPutAutoscalingPolicyRequest) Do(ctx context.Context, transport Transport) (*Response, error) { var ( method string path strings.Builder params map[string]string ) method = "PUT" path.Grow(1 + len("_autoscaling") + 1 + len("policy") + 1 + len(r.Name)) path.WriteString("/") path.WriteString("_autoscaling") path.WriteString("/") path.WriteString("policy") path.WriteString("/") path.WriteString(r.Name) params = make(map[string]string) if r.Pretty { params["pretty"] = "true" } if r.Human { params["human"] = "true" } if r.ErrorTrace { params["error_trace"] = "true" } if len(r.FilterPath) > 0 { params["filter_path"] = strings.Join(r.FilterPath, ",") } req, err := newRequest(method, path.String(), r.Body) if err != nil { return nil, err } if len(params) > 0 { q := req.URL.Query() for k, v := range params { q.Set(k, v) } req.URL.RawQuery = q.Encode() } if r.Body != nil { req.Header[headerContentType] = headerContentTypeJSON } if len(r.Header) > 0 { if len(req.Header) == 0 { req.Header = r.Header } else { for k, vv := range r.Header { for _, v := range vv { req.Header.Add(k, v) } } } } if ctx != nil { req = req.WithContext(ctx) } res, err := transport.Perform(req) if err != nil { return nil, err } response := Response{ StatusCode: res.StatusCode, Body: res.Body, Header: res.Header, } return &response, nil } // WithContext sets the request context. // func (f AutoscalingPutAutoscalingPolicy) WithContext(v context.Context) func(*AutoscalingPutAutoscalingPolicyRequest) { return func(r *AutoscalingPutAutoscalingPolicyRequest) { r.ctx = v } } // WithPretty makes the response body pretty-printed. // func (f AutoscalingPutAutoscalingPolicy) WithPretty() func(*AutoscalingPutAutoscalingPolicyRequest) { return func(r *AutoscalingPutAutoscalingPolicyRequest) { r.Pretty = true } } // WithHuman makes statistical values human-readable. // func (f AutoscalingPutAutoscalingPolicy) WithHuman() func(*AutoscalingPutAutoscalingPolicyRequest) { return func(r *AutoscalingPutAutoscalingPolicyRequest) { r.Human = true } } // WithErrorTrace includes the stack trace for errors in the response body. // func (f AutoscalingPutAutoscalingPolicy) WithErrorTrace() func(*AutoscalingPutAutoscalingPolicyRequest) { return func(r *AutoscalingPutAutoscalingPolicyRequest) { r.ErrorTrace = true } } // WithFilterPath filters the properties of the response body. // func (f AutoscalingPutAutoscalingPolicy) WithFilterPath(v ...string) func(*AutoscalingPutAutoscalingPolicyRequest) { return func(r *AutoscalingPutAutoscalingPolicyRequest) { r.FilterPath = v } } // WithHeader adds the headers to the HTTP request. // func (f AutoscalingPutAutoscalingPolicy) WithHeader(h map[string]string) func(*AutoscalingPutAutoscalingPolicyRequest) { return func(r *AutoscalingPutAutoscalingPolicyRequest) { if r.Header == nil { r.Header = make(http.Header) } for k, v := range h { r.Header.Add(k, v) } } } // WithOpaqueID adds the X-Opaque-Id header to the HTTP request. // func (f AutoscalingPutAutoscalingPolicy) WithOpaqueID(s string) func(*AutoscalingPutAutoscalingPolicyRequest) { return func(r *AutoscalingPutAutoscalingPolicyRequest) { if r.Header == nil { r.Header = make(http.Header) } r.Header.Set("X-Opaque-Id", s) } }
control-center/serviced
vendor/github.com/elastic/go-elasticsearch/v7/esapi/api.xpack.autoscaling.put_autoscaling_policy.go
GO
apache-2.0
4,902
""" Copyright 2015-2018 IBM 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. Licensed Materials - Property of IBM © Copyright IBM Corp. 2015-2018 """ import asyncio from confluent_kafka import Producer class ProducerTask(object): def __init__(self, conf, topic_name): self.topic_name = topic_name self.producer = Producer(conf) self.counter = 0 self.running = True def stop(self): self.running = False def on_delivery(self, err, msg): if err: print('Delivery report: Failed sending message {0}'.format(msg.value())) print(err) # We could retry sending the message else: print('Message produced, offset: {0}'.format(msg.offset())) @asyncio.coroutine def run(self): print('The producer has started') while self.running: message = 'This is a test message #{0}'.format(self.counter) key = 'key' sleep = 2 # Short sleep for flow control try: self.producer.produce(self.topic_name, message, key, -1, self.on_delivery) self.producer.poll(0) self.counter += 1 except Exception as err: print('Failed sending message {0}'.format(message)) print(err) sleep = 5 # Longer sleep before retrying yield from asyncio.sleep(sleep) self.producer.flush()
ibm-messaging/message-hub-samples
kafka-python-console-sample/producertask.py
Python
apache-2.0
1,944
/* * Copyright 2012 International Business Machines Corp. * * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. Licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.jbatch.jsl.util; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; public class JSLValidationEventHandler implements ValidationEventHandler { private boolean eventOccurred = false; public boolean handleEvent(ValidationEvent event) { System.out.println("\nMESSAGE: " + event.getMessage()); System.out.println("\nSEVERITY: " + event.getSeverity()); System.out.println("\nLINKED EXC: " + event.getLinkedException()); System.out.println("\nLOCATOR INFO:\n------------"); System.out.println("\n COLUMN NUMBER: " + event.getLocator().getColumnNumber()); System.out.println("\n LINE NUMBER: " + event.getLocator().getLineNumber()); System.out.println("\n OFFSET: " + event.getLocator().getOffset()); System.out.println("\n CLASS: " + event.getLocator().getClass()); System.out.println("\n NODE: " + event.getLocator().getNode()); System.out.println("\n OBJECT: " + event.getLocator().getObject()); System.out.println("\n URL: " + event.getLocator().getURL()); eventOccurred = true; // Allow more parsing feedback return true; } public boolean eventOccurred() { return eventOccurred; } }
papegaaij/jsr-352
JSR352.JobXML.Model/src/main/java/com/ibm/jbatch/jsl/util/JSLValidationEventHandler.java
Java
apache-2.0
2,107
# -*- coding: utf-8 -*- import unittest import pykintone from pykintone.model import kintoneModel import tests.envs as envs class TestAppModelSimple(kintoneModel): def __init__(self): super(TestAppModelSimple, self).__init__() self.my_key = "" self.stringField = "" class TestComment(unittest.TestCase): def test_comment(self): app = pykintone.load(envs.FILE_PATH).app() model = TestAppModelSimple() model.my_key = "comment_test" model.stringField = "comment_test_now" result = app.create(model) self.assertTrue(result.ok) # confirm create the record to test comment _record_id = result.record_id # create comment r_created = app.comment(_record_id).create("コメントのテスト") self.assertTrue(r_created.ok) # it requires Administrator user is registered in kintone r_created_m = app.comment(_record_id).create("メンションのテスト", [("Administrator", "USER")]) self.assertTrue(r_created_m.ok) # select comment r_selected = app.comment(_record_id).select(True, 0, 10) self.assertTrue(r_selected.ok) self.assertTrue(2, len(r_selected.raw_comments)) comments = r_selected.comments() self.assertTrue(1, len(comments[-1].mentions)) # delete comment for c in comments: r_deleted = app.comment(_record_id).delete(c.comment_id) self.assertTrue(r_deleted.ok) r_selected = app.comment(_record_id).select() self.assertEqual(0, len(r_selected.raw_comments)) # done test app.delete(_record_id)
icoxfog417/pykintone
tests/test_comment.py
Python
apache-2.0
1,667
/* Copyright 2017 The Kubernetes Authors. 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. */ // buildifier defines a Prow plugin that runs buildifier over modified BUILD, // WORKSPACE, and skylark (.bzl) files in pull requests. package buildifier import ( "bytes" "fmt" "io/ioutil" "path/filepath" "regexp" "sort" "strings" "time" "github.com/bazelbuild/buildtools/build" "github.com/sirupsen/logrus" "k8s.io/test-infra/prow/genfiles" "k8s.io/test-infra/prow/git" "k8s.io/test-infra/prow/github" "k8s.io/test-infra/prow/pluginhelp" "k8s.io/test-infra/prow/plugins" ) const ( pluginName = "buildifier" maxComments = 20 ) var buildifyRe = regexp.MustCompile(`(?mi)^/buildif(y|ier)\s*$`) func init() { plugins.RegisterGenericCommentHandler(pluginName, handleGenericComment, nil) } func helpProvider(config *plugins.Configuration, enabledRepos []string) (*pluginhelp.PluginHelp, error) { // The Config field is omitted because this plugin is not configurable. pluginHelp := &pluginhelp.PluginHelp{ Description: "The buildifier plugin runs buildifier on changes made to Bazel files in a PR. It then creates a new review on the pull request and leaves warnings at the appropriate lines of code.", } pluginHelp.AddCommand(pluginhelp.Command{ Usage: "/buildif(y|ier)", Featured: false, Description: "Runs buildifier on changes made to Bazel files in a PR", WhoCanUse: "Anyone can trigger this command on a PR.", Examples: []string{"/buildify", "/buildifier"}, }) return pluginHelp, nil } type githubClient interface { GetFile(org, repo, filepath, commit string) ([]byte, error) GetPullRequest(org, repo string, number int) (*github.PullRequest, error) GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error) CreateReview(org, repo string, number int, r github.DraftReview) error ListPullRequestComments(org, repo string, number int) ([]github.ReviewComment, error) } func handleGenericComment(pc plugins.Agent, e github.GenericCommentEvent) error { return handle(pc.GitHubClient, pc.GitClient, pc.Logger, &e) } // modifiedBazelFiles returns a map from filename to patch string for all Bazel files // that are modified in the PR. func modifiedBazelFiles(ghc githubClient, org, repo string, number int, sha string) (map[string]string, error) { changes, err := ghc.GetPullRequestChanges(org, repo, number) if err != nil { return nil, err } gfg, err := genfiles.NewGroup(ghc, org, repo, sha) if err != nil { return nil, err } modifiedFiles := make(map[string]string) for _, change := range changes { switch { case gfg.Match(change.Filename): continue case change.Status == github.PullRequestFileRemoved || change.Status == github.PullRequestFileRenamed: continue // This also happens to match BUILD.bazel. case strings.Contains(change.Filename, "BUILD"): break case strings.Contains(change.Filename, "WORKSPACE"): break case filepath.Ext(change.Filename) != ".bzl": continue } modifiedFiles[change.Filename] = change.Patch } return modifiedFiles, nil } func uniqProblems(problems []string) []string { sort.Strings(problems) var uniq []string last := "" for _, s := range problems { if s != last { last = s uniq = append(uniq, s) } } return uniq } // problemsInFiles runs buildifier on the files. It returns a map from the file to // a list of problems with that file. func problemsInFiles(r *git.Repo, files map[string]string) (map[string][]string, error) { problems := make(map[string][]string) for f := range files { src, err := ioutil.ReadFile(filepath.Join(r.Dir, f)) if err != nil { return nil, err } // This is modeled after the logic from buildifier: // https://github.com/bazelbuild/buildtools/blob/8818289/buildifier/buildifier.go#L261 content, err := build.Parse(f, src) if err != nil { return nil, fmt.Errorf("parsing as Bazel file %v", err) } beforeRewrite := build.Format(content) var info build.RewriteInfo build.Rewrite(content, &info) ndata := build.Format(content) if !bytes.Equal(src, ndata) && !bytes.Equal(src, beforeRewrite) { // TODO(mattmoor): This always seems to be empty? problems[f] = uniqProblems(info.Log) } } return problems, nil } func handle(ghc githubClient, gc *git.Client, log *logrus.Entry, e *github.GenericCommentEvent) error { // Only handle open PRs and new requests. if e.IssueState != "open" || !e.IsPR || e.Action != github.GenericCommentActionCreated { return nil } if !buildifyRe.MatchString(e.Body) { return nil } org := e.Repo.Owner.Login repo := e.Repo.Name pr, err := ghc.GetPullRequest(org, repo, e.Number) if err != nil { return err } // List modified files. modifiedFiles, err := modifiedBazelFiles(ghc, org, repo, pr.Number, pr.Head.SHA) if err != nil { return err } if len(modifiedFiles) == 0 { return nil } log.Infof("Will buildify %d modified Bazel files.", len(modifiedFiles)) // Clone the repo, checkout the PR. startClone := time.Now() r, err := gc.Clone(e.Repo.FullName) if err != nil { return err } defer func() { if err := r.Clean(); err != nil { log.WithError(err).Error("Error cleaning up repo.") } }() if err := r.CheckoutPullRequest(e.Number); err != nil { return err } finishClone := time.Now() log.WithField("duration", time.Since(startClone)).Info("Cloned and checked out PR.") // Compute buildifier errors. problems, err := problemsInFiles(r, modifiedFiles) if err != nil { return err } log.WithField("duration", time.Since(finishClone)).Info("Buildified.") // Make the list of comments. var comments []github.DraftReviewComment for f := range problems { comments = append(comments, github.DraftReviewComment{ Path: f, // TODO(mattmoor): Include the messages if they are ever non-empty. Body: strings.Join([]string{ "This Bazel file needs formatting, run:", "```shell", fmt.Sprintf("buildifier -mode=fix %q", f), "```"}, "\n"), Position: 1, }) } // Trim down the number of comments if necessary. totalProblems := len(problems) // Make the review body. s := "s" if totalProblems == 1 { s = "" } response := fmt.Sprintf("%d warning%s.", totalProblems, s) return ghc.CreateReview(org, repo, e.Number, github.DraftReview{ Body: plugins.FormatResponseRaw(e.Body, e.HTMLURL, e.User.Login, response), Action: github.Comment, Comments: comments, }) }
kargakis/test-infra
prow/plugins/buildifier/buildifier.go
GO
apache-2.0
6,914
package com.scicrop.se.commons.utils; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.RollingFileAppender; public class LogHelper { private LogHelper(){} private static LogHelper INSTANCE = null; public static LogHelper getInstance(){ if(INSTANCE == null) INSTANCE = new LogHelper(); return INSTANCE; } public void setLogger(String logNamePattern, String logFolder){ String logPath = logFolder + Constants.APP_NAME+"_"+logNamePattern+".log"; Logger rootLogger = Logger.getRootLogger(); rootLogger.setLevel(Level.INFO); PatternLayout layout = new PatternLayout("%d{ISO8601} [%t] %-5p %c %x - %m%n"); rootLogger.addAppender(new ConsoleAppender(layout)); try { RollingFileAppender fileAppender = new RollingFileAppender(layout, logPath); rootLogger.addAppender(fileAppender); } catch (IOException e) { System.err.println("Failed to find/access "+logPath+" !"); System.exit(1); } } public void handleVerboseLog(boolean isVerbose, boolean isLog, Log log, char type, String data){ if(isLog){ logData(data, type, log); } if(isVerbose){ verbose(data, type); } } public void logData(String data, char type, Log log){ switch (type) { case 'i': log.info(data); break; case 'w': log.warn(data); break; case 'e': log.error(data); break; default: log.info(data); break; } } public void verbose(String data, char type){ switch (type) { case 'e': System.err.println(data); break; default: System.out.println(data); break; } } }
Scicrop/sentinel-extractor
source-code/sentinel-extractor-commons/src/com/scicrop/se/commons/utils/LogHelper.java
Java
apache-2.0
1,743
# -*- coding: utf-8 -*- ''' The Salt Key backend API and interface used by the CLI. The Key class can be used to manage salt keys directly without interfacing with the CLI. ''' # Import python libs from __future__ import absolute_import, print_function import os import copy import json import stat import shutil import fnmatch import hashlib import logging # Import salt libs import salt.crypt import salt.utils import salt.exceptions import salt.utils.event import salt.daemons.masterapi from salt.utils import kinds from salt.utils.event import tagify # Import third party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin import salt.ext.six as six from salt.ext.six.moves import input # pylint: enable=import-error,no-name-in-module,redefined-builtin try: import msgpack except ImportError: pass log = logging.getLogger(__name__) def get_key(opts): if opts['transport'] in ('zeromq', 'tcp'): return Key(opts) else: return RaetKey(opts) class KeyCLI(object): ''' Manage key CLI operations ''' def __init__(self, opts): self.opts = opts if self.opts['transport'] in ('zeromq', 'tcp'): self.key = Key(opts) else: self.key = RaetKey(opts) def list_status(self, status): ''' Print out the keys under a named status :param str status: A string indicating which set of keys to return ''' keys = self.key.list_keys() if status.startswith('acc'): salt.output.display_output( {self.key.ACC: keys[self.key.ACC]}, 'key', self.opts ) elif status.startswith(('pre', 'un')): salt.output.display_output( {self.key.PEND: keys[self.key.PEND]}, 'key', self.opts ) elif status.startswith('rej'): salt.output.display_output( {self.key.REJ: keys[self.key.REJ]}, 'key', self.opts ) elif status.startswith('den'): if self.key.DEN: salt.output.display_output( {self.key.DEN: keys[self.key.DEN]}, 'key', self.opts ) elif status.startswith('all'): self.list_all() def list_all(self): ''' Print out all keys ''' salt.output.display_output( self.key.list_keys(), 'key', self.opts) def accept(self, match, include_rejected=False): ''' Accept the keys matched :param str match: A string to match against. i.e. 'web*' :param bool include_rejected: Whether or not to accept a matched key that was formerly rejected ''' def _print_accepted(matches, after_match): if self.key.ACC in after_match: accepted = sorted( set(after_match[self.key.ACC]).difference( set(matches.get(self.key.ACC, [])) ) ) for key in accepted: print('Key for minion {0} accepted.'.format(key)) matches = self.key.name_match(match) keys = {} if self.key.PEND in matches: keys[self.key.PEND] = matches[self.key.PEND] if include_rejected and bool(matches.get(self.key.REJ)): keys[self.key.REJ] = matches[self.key.REJ] if not keys: msg = ( 'The key glob {0!r} does not match any unaccepted {1}keys.' .format(match, 'or rejected ' if include_rejected else '') ) print(msg) raise salt.exceptions.SaltSystemExit(code=1) if not self.opts.get('yes', False): print('The following keys are going to be accepted:') salt.output.display_output( keys, 'key', self.opts) try: veri = input('Proceed? [n/Y] ') except KeyboardInterrupt: raise SystemExit("\nExiting on CTRL-c") if not veri or veri.lower().startswith('y'): _print_accepted( matches, self.key.accept( match_dict=keys, include_rejected=include_rejected ) ) else: print('The following keys are going to be accepted:') salt.output.display_output( keys, 'key', self.opts) _print_accepted( matches, self.key.accept( match_dict=keys, include_rejected=include_rejected ) ) def accept_all(self, include_rejected=False): ''' Accept all keys :param bool include_rejected: Whether or not to accept a matched key that was formerly rejected ''' self.accept('*', include_rejected=include_rejected) def delete(self, match): ''' Delete the matched keys :param str match: A string to match against. i.e. 'web*' ''' def _print_deleted(matches, after_match): deleted = [] for keydir in (self.key.ACC, self.key.PEND, self.key.REJ): deleted.extend(list( set(matches.get(keydir, [])).difference( set(after_match.get(keydir, [])) ) )) for key in sorted(deleted): print('Key for minion {0} deleted.'.format(key)) matches = self.key.name_match(match) if not matches: print( 'The key glob {0!r} does not match any accepted, unaccepted ' 'or rejected keys.'.format(match) ) raise salt.exceptions.SaltSystemExit(code=1) if not self.opts.get('yes', False): print('The following keys are going to be deleted:') salt.output.display_output( matches, 'key', self.opts) try: veri = input('Proceed? [N/y] ') except KeyboardInterrupt: raise SystemExit("\nExiting on CTRL-c") if veri.lower().startswith('y'): _print_deleted( matches, self.key.delete_key(match_dict=matches) ) else: print('Deleting the following keys:') salt.output.display_output( matches, 'key', self.opts) _print_deleted( matches, self.key.delete_key(match_dict=matches) ) def delete_all(self): ''' Delete all keys ''' self.delete('*') def reject(self, match, include_accepted=False): ''' Reject the matched keys :param str match: A string to match against. i.e. 'web*' :param bool include_accepted: Whether or not to accept a matched key that was formerly accepted ''' def _print_rejected(matches, after_match): if self.key.REJ in after_match: rejected = sorted( set(after_match[self.key.REJ]).difference( set(matches.get(self.key.REJ, [])) ) ) for key in rejected: print('Key for minion {0} rejected.'.format(key)) matches = self.key.name_match(match) keys = {} if self.key.PEND in matches: keys[self.key.PEND] = matches[self.key.PEND] if include_accepted and bool(matches.get(self.key.ACC)): keys[self.key.ACC] = matches[self.key.ACC] if not keys: msg = 'The key glob {0!r} does not match any {1} keys.'.format( match, 'accepted or unaccepted' if include_accepted else 'unaccepted' ) print(msg) return if not self.opts.get('yes', False): print('The following keys are going to be rejected:') salt.output.display_output( keys, 'key', self.opts) veri = input('Proceed? [n/Y] ') if veri.lower().startswith('n'): return _print_rejected( matches, self.key.reject( match_dict=matches, include_accepted=include_accepted ) ) def reject_all(self, include_accepted=False): ''' Reject all keys :param bool include_accepted: Whether or not to accept a matched key that was formerly accepted ''' self.reject('*', include_accepted=include_accepted) def print_key(self, match): ''' Print out a single key :param str match: A string to match against. i.e. 'web*' ''' matches = self.key.key_str(match) salt.output.display_output( matches, 'key', self.opts) def print_all(self): ''' Print out all managed keys ''' self.print_key('*') def finger(self, match): ''' Print out the fingerprints for the matched keys :param str match: A string to match against. i.e. 'web*' ''' matches = self.key.finger(match) salt.output.display_output( matches, 'key', self.opts) def finger_all(self): ''' Print out all fingerprints ''' matches = self.key.finger('*') salt.output.display_output( matches, 'key', self.opts) def prep_signature(self): ''' Searches for usable keys to create the master public-key signature ''' self.privkey = None self.pubkey = None # check given pub-key if self.opts['pub']: if not os.path.isfile(self.opts['pub']): print('Public-key {0} does not exist'.format(self.opts['pub'])) return self.pubkey = self.opts['pub'] # default to master.pub else: mpub = self.opts['pki_dir'] + '/' + 'master.pub' if os.path.isfile(mpub): self.pubkey = mpub # check given priv-key if self.opts['priv']: if not os.path.isfile(self.opts['priv']): print('Private-key {0} does not exist'.format(self.opts['priv'])) return self.privkey = self.opts['priv'] # default to master_sign.pem else: mpriv = self.opts['pki_dir'] + '/' + 'master_sign.pem' if os.path.isfile(mpriv): self.privkey = mpriv if not self.privkey: if self.opts['auto_create']: print('Generating new signing key-pair {0}.* in {1}' ''.format(self.opts['master_sign_key_name'], self.opts['pki_dir'])) salt.crypt.gen_keys(self.opts['pki_dir'], self.opts['master_sign_key_name'], self.opts['keysize'], self.opts.get('user')) self.privkey = self.opts['pki_dir'] + '/' + self.opts['master_sign_key_name'] + '.pem' else: print('No usable private-key found') return if not self.pubkey: print('No usable public-key found') return print('Using public-key {0}'.format(self.pubkey)) print('Using private-key {0}'.format(self.privkey)) if self.opts['signature_path']: if not os.path.isdir(self.opts['signature_path']): print('target directory {0} does not exist' ''.format(self.opts['signature_path'])) else: self.opts['signature_path'] = self.opts['pki_dir'] sign_path = self.opts['signature_path'] + '/' + self.opts['master_pubkey_signature'] self.key.gen_signature(self.privkey, self.pubkey, sign_path) def run(self): ''' Run the logic for saltkey ''' if self.opts['gen_keys']: self.key.gen_keys() return elif self.opts['gen_signature']: self.prep_signature() return if self.opts['list']: self.list_status(self.opts['list']) elif self.opts['list_all']: self.list_all() elif self.opts['print']: self.print_key(self.opts['print']) elif self.opts['print_all']: self.print_all() elif self.opts['accept']: self.accept( self.opts['accept'], include_rejected=self.opts['include_all'] ) elif self.opts['accept_all']: self.accept_all(include_rejected=self.opts['include_all']) elif self.opts['reject']: self.reject( self.opts['reject'], include_accepted=self.opts['include_all'] ) elif self.opts['reject_all']: self.reject_all(include_accepted=self.opts['include_all']) elif self.opts['delete']: self.delete(self.opts['delete']) elif self.opts['delete_all']: self.delete_all() elif self.opts['finger']: self.finger(self.opts['finger']) elif self.opts['finger_all']: self.finger_all() else: self.list_all() class MultiKeyCLI(KeyCLI): ''' Manage multiple key backends from the CLI ''' def __init__(self, opts): opts['__multi_key'] = True super(MultiKeyCLI, self).__init__(opts) # Remove the key attribute set in KeyCLI.__init__ delattr(self, 'key') zopts = copy.copy(opts) ropts = copy.copy(opts) self.keys = {} zopts['transport'] = 'zeromq' self.keys['ZMQ Keys'] = KeyCLI(zopts) ropts['transport'] = 'raet' self.keys['RAET Keys'] = KeyCLI(ropts) def _call_all(self, fun, *args): ''' Call the given function on all backend keys ''' for kback in self.keys: print(kback) getattr(self.keys[kback], fun)(*args) def list_status(self, status): self._call_all('list_status', status) def list_all(self): self._call_all('list_all') def accept(self, match, include_rejected=False): self._call_all('accept', match, include_rejected) def accept_all(self, include_rejected=False): self._call_all('accept_all', include_rejected) def delete(self, match): self._call_all('delete', match) def delete_all(self): self._call_all('delete_all') def reject(self, match, include_accepted=False): self._call_all('reject', match, include_accepted) def reject_all(self, include_accepted=False): self._call_all('reject_all', include_accepted) def print_key(self, match): self._call_all('print_key', match) def print_all(self): self._call_all('print_all') def finger(self, match): self._call_all('finger', match) def finger_all(self): self._call_all('finger_all') def prep_signature(self): self._call_all('prep_signature') class Key(object): ''' The object that encapsulates saltkey actions ''' ACC = 'minions' PEND = 'minions_pre' REJ = 'minions_rejected' DEN = 'minions_denied' def __init__(self, opts): self.opts = opts kind = self.opts.get('__role', '') # application kind if kind not in kinds.APPL_KINDS: emsg = ("Invalid application kind = '{0}'.".format(kind)) log.error(emsg + '\n') raise ValueError(emsg) self.event = salt.utils.event.get_event( kind, opts['sock_dir'], opts['transport'], opts=opts, listen=False) def _check_minions_directories(self): ''' Return the minion keys directory paths ''' minions_accepted = os.path.join(self.opts['pki_dir'], self.ACC) minions_pre = os.path.join(self.opts['pki_dir'], self.PEND) minions_rejected = os.path.join(self.opts['pki_dir'], self.REJ) minions_denied = os.path.join(self.opts['pki_dir'], self.DEN) return minions_accepted, minions_pre, minions_rejected, minions_denied def gen_keys(self): ''' Generate minion RSA public keypair ''' salt.crypt.gen_keys( self.opts['gen_keys_dir'], self.opts['gen_keys'], self.opts['keysize']) return def gen_signature(self, privkey, pubkey, sig_path): ''' Generate master public-key-signature ''' return salt.crypt.gen_signature(privkey, pubkey, sig_path) def check_minion_cache(self, preserve_minions=None): ''' Check the minion cache to make sure that old minion data is cleared Optionally, pass in a list of minions which should have their caches preserved. To preserve all caches, set __opts__['preserve_minion_cache'] ''' if preserve_minions is None: preserve_minions = [] m_cache = os.path.join(self.opts['cachedir'], self.ACC) if not os.path.isdir(m_cache): return keys = self.list_keys() minions = [] for key, val in six.iteritems(keys): minions.extend(val) if not self.opts.get('preserve_minion_cache', False) or not preserve_minions: for minion in os.listdir(m_cache): if minion not in minions and minion not in preserve_minions: shutil.rmtree(os.path.join(m_cache, minion)) def check_master(self): ''' Log if the master is not running :rtype: bool :return: Whether or not the master is running ''' if not os.path.exists( os.path.join( self.opts['sock_dir'], 'publish_pull.ipc' ) ): return False return True def name_match(self, match, full=False): ''' Accept a glob which to match the of a key and return the key's location ''' if full: matches = self.all_keys() else: matches = self.list_keys() ret = {} if ',' in match and isinstance(match, str): match = match.split(',') for status, keys in six.iteritems(matches): for key in salt.utils.isorted(keys): if isinstance(match, list): for match_item in match: if fnmatch.fnmatch(key, match_item): if status not in ret: ret[status] = [] ret[status].append(key) else: if fnmatch.fnmatch(key, match): if status not in ret: ret[status] = [] ret[status].append(key) return ret def dict_match(self, match_dict): ''' Accept a dictionary of keys and return the current state of the specified keys ''' ret = {} cur_keys = self.list_keys() for status, keys in six.iteritems(match_dict): for key in salt.utils.isorted(keys): for keydir in (self.ACC, self.PEND, self.REJ, self.DEN): if keydir and fnmatch.filter(cur_keys.get(keydir, []), key): ret.setdefault(keydir, []).append(key) return ret def local_keys(self): ''' Return a dict of local keys ''' ret = {'local': []} for fn_ in salt.utils.isorted(os.listdir(self.opts['pki_dir'])): if fn_.endswith('.pub') or fn_.endswith('.pem'): path = os.path.join(self.opts['pki_dir'], fn_) if os.path.isfile(path): ret['local'].append(fn_) return ret def list_keys(self): ''' Return a dict of managed keys and what the key status are ''' key_dirs = [] # We have to differentiate between RaetKey._check_minions_directories # and Zeromq-Keys. Raet-Keys only have three states while ZeroMQ-keys # havd an additional 'denied' state. if self.opts['transport'] in ('zeromq', 'tcp'): key_dirs = self._check_minions_directories() else: key_dirs = self._check_minions_directories() ret = {} for dir_ in key_dirs: ret[os.path.basename(dir_)] = [] try: for fn_ in salt.utils.isorted(os.listdir(dir_)): if not fn_.startswith('.'): if os.path.isfile(os.path.join(dir_, fn_)): ret[os.path.basename(dir_)].append(fn_) except (OSError, IOError): # key dir kind is not created yet, just skip continue return ret def all_keys(self): ''' Merge managed keys with local keys ''' keys = self.list_keys() keys.update(self.local_keys()) return keys def list_status(self, match): ''' Return a dict of managed keys under a named status ''' acc, pre, rej, den = self._check_minions_directories() ret = {} if match.startswith('acc'): ret[os.path.basename(acc)] = [] for fn_ in salt.utils.isorted(os.listdir(acc)): if not fn_.startswith('.'): if os.path.isfile(os.path.join(acc, fn_)): ret[os.path.basename(acc)].append(fn_) elif match.startswith('pre') or match.startswith('un'): ret[os.path.basename(pre)] = [] for fn_ in salt.utils.isorted(os.listdir(pre)): if not fn_.startswith('.'): if os.path.isfile(os.path.join(pre, fn_)): ret[os.path.basename(pre)].append(fn_) elif match.startswith('rej'): ret[os.path.basename(rej)] = [] for fn_ in salt.utils.isorted(os.listdir(rej)): if not fn_.startswith('.'): if os.path.isfile(os.path.join(rej, fn_)): ret[os.path.basename(rej)].append(fn_) elif match.startswith('den'): ret[os.path.basename(den)] = [] for fn_ in salt.utils.isorted(os.listdir(den)): if not fn_.startswith('.'): if os.path.isfile(os.path.join(den, fn_)): ret[os.path.basename(den)].append(fn_) elif match.startswith('all'): return self.all_keys() return ret def key_str(self, match): ''' Return the specified public key or keys based on a glob ''' ret = {} for status, keys in six.iteritems(self.name_match(match)): ret[status] = {} for key in salt.utils.isorted(keys): path = os.path.join(self.opts['pki_dir'], status, key) with salt.utils.fopen(path, 'r') as fp_: ret[status][key] = fp_.read() return ret def key_str_all(self): ''' Return all managed key strings ''' ret = {} for status, keys in six.iteritems(self.list_keys()): ret[status] = {} for key in salt.utils.isorted(keys): path = os.path.join(self.opts['pki_dir'], status, key) with salt.utils.fopen(path, 'r') as fp_: ret[status][key] = fp_.read() return ret def accept(self, match=None, match_dict=None, include_rejected=False): ''' Accept public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_rejected: keydirs.append(self.REJ) for keydir in keydirs: for key in matches.get(keydir, []): try: shutil.move( os.path.join( self.opts['pki_dir'], keydir, key), os.path.join( self.opts['pki_dir'], self.ACC, key) ) eload = {'result': True, 'act': 'accept', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (IOError, OSError): pass return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def accept_all(self): ''' Accept all keys in pre ''' keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move( os.path.join( self.opts['pki_dir'], self.PEND, key), os.path.join( self.opts['pki_dir'], self.ACC, key) ) eload = {'result': True, 'act': 'accept', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (IOError, OSError): pass return self.list_keys() def delete_key(self, match=None, match_dict=None, preserve_minions=False): ''' Delete public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". To preserve the master caches of minions who are matched, set preserve_minions ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} for status, keys in six.iteritems(matches): for key in keys: try: os.remove(os.path.join(self.opts['pki_dir'], status, key)) eload = {'result': True, 'act': 'delete', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (OSError, IOError): pass self.check_minion_cache(preserve_minions=matches.get('minions', [])) if self.opts.get('rotate_aes_key'): salt.crypt.dropfile(self.opts['cachedir'], self.opts['user']) return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def delete_all(self): ''' Delete all keys ''' for status, keys in six.iteritems(self.list_keys()): for key in keys: try: os.remove(os.path.join(self.opts['pki_dir'], status, key)) eload = {'result': True, 'act': 'delete', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (OSError, IOError): pass self.check_minion_cache() if self.opts.get('rotate_aes_key'): salt.crypt.dropfile(self.opts['cachedir'], self.opts['user']) return self.list_keys() def reject(self, match=None, match_dict=None, include_accepted=False): ''' Reject public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_accepted: keydirs.append(self.ACC) for keydir in keydirs: for key in matches.get(keydir, []): try: shutil.move( os.path.join( self.opts['pki_dir'], keydir, key), os.path.join( self.opts['pki_dir'], self.REJ, key) ) eload = {'result': True, 'act': 'reject', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (IOError, OSError): pass self.check_minion_cache() if self.opts.get('rotate_aes_key'): salt.crypt.dropfile(self.opts['cachedir'], self.opts['user']) return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def reject_all(self): ''' Reject all keys in pre ''' keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move( os.path.join( self.opts['pki_dir'], self.PEND, key), os.path.join( self.opts['pki_dir'], self.REJ, key) ) eload = {'result': True, 'act': 'reject', 'id': key} self.event.fire_event(eload, tagify(prefix='key')) except (IOError, OSError): pass self.check_minion_cache() if self.opts.get('rotate_aes_key'): salt.crypt.dropfile(self.opts['cachedir'], self.opts['user']) return self.list_keys() def finger(self, match): ''' Return the fingerprint for a specified key ''' matches = self.name_match(match, True) ret = {} for status, keys in six.iteritems(matches): ret[status] = {} for key in keys: if status == 'local': path = os.path.join(self.opts['pki_dir'], key) else: path = os.path.join(self.opts['pki_dir'], status, key) ret[status][key] = salt.utils.pem_finger(path, sum_type=self.opts['hash_type']) return ret def finger_all(self): ''' Return fingerprins for all keys ''' ret = {} for status, keys in six.iteritems(self.list_keys()): ret[status] = {} for key in keys: if status == 'local': path = os.path.join(self.opts['pki_dir'], key) else: path = os.path.join(self.opts['pki_dir'], status, key) ret[status][key] = salt.utils.pem_finger(path, sum_type=self.opts['hash_type']) return ret class RaetKey(Key): ''' Manage keys from the raet backend ''' ACC = 'accepted' PEND = 'pending' REJ = 'rejected' DEN = None def __init__(self, opts): Key.__init__(self, opts) self.auto_key = salt.daemons.masterapi.AutoKey(self.opts) self.serial = salt.payload.Serial(self.opts) def _check_minions_directories(self): ''' Return the minion keys directory paths ''' accepted = os.path.join(self.opts['pki_dir'], self.ACC) pre = os.path.join(self.opts['pki_dir'], self.PEND) rejected = os.path.join(self.opts['pki_dir'], self.REJ) return accepted, pre, rejected def check_minion_cache(self, preserve_minions=False): ''' Check the minion cache to make sure that old minion data is cleared ''' keys = self.list_keys() minions = [] for key, val in six.iteritems(keys): minions.extend(val) m_cache = os.path.join(self.opts['cachedir'], 'minions') if os.path.isdir(m_cache): for minion in os.listdir(m_cache): if minion not in minions: shutil.rmtree(os.path.join(m_cache, minion)) kind = self.opts.get('__role', '') # application kind if kind not in kinds.APPL_KINDS: emsg = ("Invalid application kind = '{0}'.".format(kind)) log.error(emsg + '\n') raise ValueError(emsg) role = self.opts.get('id', '') if not role: emsg = ("Invalid id.") log.error(emsg + "\n") raise ValueError(emsg) name = "{0}_{1}".format(role, kind) road_cache = os.path.join(self.opts['cachedir'], 'raet', name, 'remote') if os.path.isdir(road_cache): for road in os.listdir(road_cache): root, ext = os.path.splitext(road) if ext not in ['.json', '.msgpack']: continue prefix, sep, name = root.partition('.') if not name or prefix != 'estate': continue path = os.path.join(road_cache, road) with salt.utils.fopen(path, 'rb') as fp_: if ext == '.json': data = json.load(fp_) elif ext == '.msgpack': data = msgpack.load(fp_) if data['role'] not in minions: os.remove(path) def gen_keys(self): ''' Use libnacl to generate and safely save a private key ''' import libnacl.public d_key = libnacl.dual.DualSecret() path = '{0}.key'.format(os.path.join( self.opts['gen_keys_dir'], self.opts['gen_keys'])) d_key.save(path, 'msgpack') def check_master(self): ''' Log if the master is not running NOT YET IMPLEMENTED ''' return True def local_keys(self): ''' Return a dict of local keys ''' ret = {'local': []} fn_ = os.path.join(self.opts['pki_dir'], 'local.key') if os.path.isfile(fn_): ret['local'].append(fn_) return ret def status(self, minion_id, pub, verify): ''' Accepts the minion id, device id, curve public and verify keys. If the key is not present, put it in pending and return "pending", If the key has been accepted return "accepted" if the key should be rejected, return "rejected" ''' acc, pre, rej = self._check_minions_directories() # pylint: disable=W0632 acc_path = os.path.join(acc, minion_id) pre_path = os.path.join(pre, minion_id) rej_path = os.path.join(rej, minion_id) # open mode is turned on, force accept the key keydata = { 'minion_id': minion_id, 'pub': pub, 'verify': verify} if self.opts['open_mode']: # always accept and overwrite with salt.utils.fopen(acc_path, 'w+b') as fp_: fp_.write(self.serial.dumps(keydata)) return self.ACC if os.path.isfile(rej_path): log.debug("Rejection Reason: Keys already rejected.\n") return self.REJ elif os.path.isfile(acc_path): # The minion id has been accepted, verify the key strings with salt.utils.fopen(acc_path, 'rb') as fp_: keydata = self.serial.loads(fp_.read()) if keydata['pub'] == pub and keydata['verify'] == verify: return self.ACC else: log.debug("Rejection Reason: Keys not match prior accepted.\n") return self.REJ elif os.path.isfile(pre_path): auto_reject = self.auto_key.check_autoreject(minion_id) auto_sign = self.auto_key.check_autosign(minion_id) with salt.utils.fopen(pre_path, 'rb') as fp_: keydata = self.serial.loads(fp_.read()) if keydata['pub'] == pub and keydata['verify'] == verify: if auto_reject: self.reject(minion_id) log.debug("Rejection Reason: Auto reject pended.\n") return self.REJ elif auto_sign: self.accept(minion_id) return self.ACC return self.PEND else: log.debug("Rejection Reason: Keys not match prior pended.\n") return self.REJ # This is a new key, evaluate auto accept/reject files and place # accordingly auto_reject = self.auto_key.check_autoreject(minion_id) auto_sign = self.auto_key.check_autosign(minion_id) if self.opts['auto_accept']: w_path = acc_path ret = self.ACC elif auto_sign: w_path = acc_path ret = self.ACC elif auto_reject: w_path = rej_path log.debug("Rejection Reason: Auto reject new.\n") ret = self.REJ else: w_path = pre_path ret = self.PEND with salt.utils.fopen(w_path, 'w+b') as fp_: fp_.write(self.serial.dumps(keydata)) return ret def _get_key_str(self, minion_id, status): ''' Return the key string in the form of: pub: <pub> verify: <verify> ''' path = os.path.join(self.opts['pki_dir'], status, minion_id) with salt.utils.fopen(path, 'r') as fp_: keydata = self.serial.loads(fp_.read()) return 'pub: {0}\nverify: {1}'.format( keydata['pub'], keydata['verify']) def _get_key_finger(self, path): ''' Return a sha256 kingerprint for the key ''' with salt.utils.fopen(path, 'r') as fp_: keydata = self.serial.loads(fp_.read()) key = 'pub: {0}\nverify: {1}'.format( keydata['pub'], keydata['verify']) return hashlib.sha256(key).hexdigest() def key_str(self, match): ''' Return the specified public key or keys based on a glob ''' ret = {} for status, keys in six.iteritems(self.name_match(match)): ret[status] = {} for key in salt.utils.isorted(keys): ret[status][key] = self._get_key_str(key, status) return ret def key_str_all(self): ''' Return all managed key strings ''' ret = {} for status, keys in six.iteritems(self.list_keys()): ret[status] = {} for key in salt.utils.isorted(keys): ret[status][key] = self._get_key_str(key, status) return ret def accept(self, match=None, match_dict=None, include_rejected=False): ''' Accept public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_rejected: keydirs.append(self.REJ) for keydir in keydirs: for key in matches.get(keydir, []): try: shutil.move( os.path.join( self.opts['pki_dir'], keydir, key), os.path.join( self.opts['pki_dir'], self.ACC, key) ) except (IOError, OSError): pass return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def accept_all(self): ''' Accept all keys in pre ''' keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move( os.path.join( self.opts['pki_dir'], self.PEND, key), os.path.join( self.opts['pki_dir'], self.ACC, key) ) except (IOError, OSError): pass return self.list_keys() def delete_key(self, match=None, match_dict=None, preserve_minions=False): ''' Delete public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} for status, keys in six.iteritems(matches): for key in keys: try: os.remove(os.path.join(self.opts['pki_dir'], status, key)) except (OSError, IOError): pass self.check_minion_cache(preserve_minions=matches.get('minions', [])) return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def delete_all(self): ''' Delete all keys ''' for status, keys in six.iteritems(self.list_keys()): for key in keys: try: os.remove(os.path.join(self.opts['pki_dir'], status, key)) except (OSError, IOError): pass self.check_minion_cache() return self.list_keys() def reject(self, match=None, match_dict=None, include_accepted=False): ''' Reject public keys. If "match" is passed, it is evaluated as a glob. Pre-gathered matches can also be passed via "match_dict". ''' if match is not None: matches = self.name_match(match) elif match_dict is not None and isinstance(match_dict, dict): matches = match_dict else: matches = {} keydirs = [self.PEND] if include_accepted: keydirs.append(self.ACC) for keydir in keydirs: for key in matches.get(keydir, []): try: shutil.move( os.path.join( self.opts['pki_dir'], keydir, key), os.path.join( self.opts['pki_dir'], self.REJ, key) ) except (IOError, OSError): pass self.check_minion_cache() return ( self.name_match(match) if match is not None else self.dict_match(matches) ) def reject_all(self): ''' Reject all keys in pre ''' keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move( os.path.join( self.opts['pki_dir'], self.PEND, key), os.path.join( self.opts['pki_dir'], self.REJ, key) ) except (IOError, OSError): pass self.check_minion_cache() return self.list_keys() def finger(self, match): ''' Return the fingerprint for a specified key ''' matches = self.name_match(match, True) ret = {} for status, keys in six.iteritems(matches): ret[status] = {} for key in keys: if status == 'local': path = os.path.join(self.opts['pki_dir'], key) else: path = os.path.join(self.opts['pki_dir'], status, key) ret[status][key] = self._get_key_finger(path) return ret def finger_all(self): ''' Return fingerprints for all keys ''' ret = {} for status, keys in six.iteritems(self.list_keys()): ret[status] = {} for key in keys: if status == 'local': path = os.path.join(self.opts['pki_dir'], key) else: path = os.path.join(self.opts['pki_dir'], status, key) ret[status][key] = self._get_key_finger(path) return ret def read_all_remote(self): ''' Return a dict of all remote key data ''' data = {} for status, mids in six.iteritems(self.list_keys()): for mid in mids: keydata = self.read_remote(mid, status) if keydata: keydata['acceptance'] = status data[mid] = keydata return data def read_remote(self, minion_id, status=ACC): ''' Read in a remote key of status ''' path = os.path.join(self.opts['pki_dir'], status, minion_id) if not os.path.isfile(path): return {} with salt.utils.fopen(path, 'rb') as fp_: return self.serial.loads(fp_.read()) def read_local(self): ''' Read in the local private keys, return an empy dict if the keys do not exist ''' path = os.path.join(self.opts['pki_dir'], 'local.key') if not os.path.isfile(path): return {} with salt.utils.fopen(path, 'rb') as fp_: return self.serial.loads(fp_.read()) def write_local(self, priv, sign): ''' Write the private key and the signing key to a file on disk ''' keydata = {'priv': priv, 'sign': sign} path = os.path.join(self.opts['pki_dir'], 'local.key') c_umask = os.umask(191) if os.path.exists(path): #mode = os.stat(path).st_mode os.chmod(path, stat.S_IWUSR | stat.S_IRUSR) with salt.utils.fopen(path, 'w+') as fp_: fp_.write(self.serial.dumps(keydata)) os.chmod(path, stat.S_IRUSR) os.umask(c_umask) def delete_local(self): ''' Delete the local private key file ''' path = os.path.join(self.opts['pki_dir'], 'local.key') if os.path.isfile(path): os.remove(path) def delete_pki_dir(self): ''' Delete the private key directory ''' path = self.opts['pki_dir'] if os.path.exists(path): shutil.rmtree(path)
smallyear/linuxLearn
salt/salt/key.py
Python
apache-2.0
48,988
require_relative '../lib/rails_stub' require_relative 'lib/pb_core_ingester' require_relative '../lib/has_logger' require 'rake' require_relative '../app/models/collection' require_relative '../app/models/exhibit' class Exception def short message + "\n" + backtrace[0..2].join("\n") end end class ParamsError < StandardError end class Ingest include HasLogger def const_init(name) const_name = name.upcase.tr('-', '_') flag_name = "--#{name}" begin # to avoid "warning: already initialized constant" in tests. Ingest.const_get(const_name) rescue NameError Ingest.const_set(const_name, flag_name) end end def initialize(argv) orig_argv = argv.dup %w(files dirs grep-files grep-dirs).each do |name| const_init(name) end %w(batch-commit stdout-log).each do |name| flag_name = const_init(name) variable_name = "@is_#{name.tr('-', '_')}" instance_variable_set(variable_name, argv.include?(flag_name)) argv.delete(flag_name) end # The code above sets fields which log_init needs, # but it also modifies argv in place, so we need the dup. log_init!(orig_argv) mode = argv.shift args = argv @flags = { is_just_reindex: @is_just_reindex } begin case mode when DIRS fail ParamsError.new if args.empty? || args.map { |dir| !File.directory?(dir) }.any? target_dirs = args when FILES fail ParamsError.new if args.empty? @files = args when GREP_DIRS fail ParamsError.new if args.empty? @regex = argv.shift fail ParamsError.new if args.empty? || args.map { |dir| !File.directory?(dir) }.any? target_dirs = args when GREP_FILES fail ParamsError.new if args.empty? @regex = argv.shift fail ParamsError.new if args.empty? @files = args else fail ParamsError.new end rescue ParamsError abort usage_message end @files ||= target_dirs.map do |target_dir| Dir.entries(target_dir) .reject { |file_name| ['.', '..'].include?(file_name) } .map { |file_name| "#{target_dir}/#{file_name}" } end.flatten.sort end def log_init!(argv) # Specify a log file unless we are logging to stdout unless @is_stdout_log self.logger = Logger.new(log_file_name) # Print to stdout where the logfile is puts "logging to #{log_file_name}" end logger.formatter = proc do |severity, datetime, _progname, msg| "#{severity} [#{datetime.strftime('%Y-%m-%d %H:%M:%S')}]: #{msg}\n" end # Log how the script was invoked logger.info("START: Process ##{Process.pid}: #{__FILE__} #{argv.join(' ')}") end def usage_message <<-EOF.gsub(/^ {4}/, '') USAGE: #{File.basename(__FILE__)} [#{BATCH_COMMIT}] [#{STDOUT_LOG}] #{FILES} FILE ... | #{DIRS} DIR ... | #{GREP_FILES} REGEX FILE ... | #{GREP_DIRS} REGEX DIR ... boolean flags: #{BATCH_COMMIT}: Optionally, make just one commit at the end, rather than one commit per file. #{STDOUT_LOG}: Optionally, log to stdout, rather than a log file. mutually exclusive modes: #{DIRS}: Clean and ingest the given directories. #{FILES}: Clean and ingest the given files (either xml or zip). #{GREP_DIRS} and #{GREP_FILES}: Same as above, except a regex is also provided. Only PBCore which matches the regexp is ingested. EOF end def process ingester = PBCoreIngester.new(regex: @regex) # set the PBCoreIngester's logger to the same as this object's logger ingester.logger = logger @files.each do |path| begin success_count_before = ingester.success_count error_count_before = ingester.errors.values.flatten.count ingester.ingest(path: path, is_batch_commit: @is_batch_commit) success_count_after = ingester.success_count error_count_after = ingester.errors.values.flatten.count logger.info("Processed '#{path}' #{'but not committed' if @is_batch_commit}") logger.info("success: #{success_count_after - success_count_before}; " \ "error: #{error_count_after - error_count_before}") end end if @is_batch_commit logger.info('Starting one big commit...') ingester.commit logger.info('Finished one big commit.') end # TODO: Investigate whether optimization is worth it. Requires a lot of disk and time. # puts 'Ingest complete; Begin optimization...' # ingester.optimize errors = ingester.errors.sort # So related errors are together error_count = errors.map { |pair| pair[1] }.flatten.count success_count = ingester.success_count total_count = error_count + success_count logger.info('SUMMARY: DETAIL') errors.each do |type, list| logger.warn("#{list.count} #{type} errors:\n#{list.join("\n")}") end logger.info('SUMMARY: STATS') logger.info('(Look just above for details on each error.)') errors.each do |type, list| logger.warn("#{list.count} (#{percent(list.count, total_count)}%) #{type}") end logger.info("#{success_count} (#{percent(success_count, total_count)}%) succeeded") logger.info('DONE') end def percent(part, whole) (100.0 * part / whole).round(1) end def log_file_name @log_file_name ||= "#{Rails.root}/log/ingest.#{Time.now.strftime('%Y-%m-%d_%H%M%S')}.log" end end Ingest.new(ARGV).process if __FILE__ == $PROGRAM_NAME
WGBH/openvault3
scripts/ingest.rb
Ruby
apache-2.0
5,618
/* * 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. */ package javax.mail.search; import javax.mail.Address; /** * Term that compares two addresses. * * @version $Rev: 920714 $ $Date: 2010-03-09 07:55:49 +0100 (Di, 09. Mär 2010) $ */ public abstract class AddressTerm extends SearchTerm { private static final long serialVersionUID = 2005405551929769980L; /** * The address. */ protected Address address; /** * Constructor taking the address for this term. * @param address the address */ protected AddressTerm(Address address) { this.address = address; } /** * Return the address of this term. * * @return the addre4ss */ public Address getAddress() { return address; } /** * Match to the supplied address. * * @param address the address to match with * @return true if the addresses match */ protected boolean match(Address address) { return this.address.equals(address); } public boolean equals(Object other) { if (this == other) return true; if (other instanceof AddressTerm == false) return false; return address.equals(((AddressTerm) other).address); } public int hashCode() { return address.hashCode(); } }
salyh/jm14specsvn
src/main/java/javax/mail/search/AddressTerm.java
Java
apache-2.0
2,071
// (c) Jean Fabre, 2011-2013 All rights reserved. // http://www.fabrejean.net // contact: http://www.fabrejean.net/contact.htm // // Version Alpha 0.92 // INSTRUCTIONS // Drop a PlayMakerArrayList script onto a GameObject, and define a unique name for reference if several PlayMakerArrayList coexists on that GameObject. // In this Action interface, link that GameObject in "arrayListObject" and input the reference name if defined. // Note: You can directly reference that GameObject or store it in an Fsm variable or global Fsm variable using UnityEngine; namespace HutongGames.PlayMaker.Actions { [ActionCategory("ArrayMaker/ArrayList")] [Tooltip("Set an item at a specified index to a PlayMaker array List component")] public class ArrayListSet : ArrayListActions { [ActionSection("Set up")] [RequiredField] [Tooltip("The gameObject with the PlayMaker ArrayList Proxy component")] [CheckForComponent(typeof(PlayMakerArrayListProxy))] public FsmOwnerDefault gameObject; [Tooltip("Author defined Reference of the PlayMaker ArrayList Proxy component (necessary if several component coexists on the same GameObject)")] [UIHint(UIHint.FsmString)] public FsmString reference; [Tooltip("The index of the Data in the ArrayList")] [UIHint(UIHint.FsmString)] public FsmInt atIndex; public bool everyFrame; [ActionSection("Data")] [Tooltip("The variable to add.")] public FsmVar variable; public override void Reset() { gameObject = null; reference = null; variable = null; everyFrame = false; } public override void OnEnter() { if ( SetUpArrayListProxyPointer(Fsm.GetOwnerDefaultTarget(gameObject),reference.Value) ) SetToArrayList(); if (!everyFrame){ Finish(); } } public override void OnUpdate() { SetToArrayList(); } public void SetToArrayList() { if (! isProxyValid() ) return; proxy.Set(atIndex.Value,PlayMakerUtils.GetValueFromFsmVar(Fsm,variable),variable.Type.ToString()); } } }
maxbottega/wheelie
Assets/PlayMaker ArrayMaker/Actions/ArrayList/ArrayListSet.cs
C#
artistic-2.0
2,041
// Convert DMD CodeView debug information to PDB files // Copyright (c) 2009-2010 by Rainer Schuetze, All Rights Reserved // // License for redistribution is given by the Artistic License 2.0 // see file LICENSE for further details #include "mspdb.h" #include <windows.h> #pragma comment(lib, "rpcrt4.lib") HMODULE modMsPdb; mspdb::fnPDBOpen2W *pPDBOpen2W; char* mspdb80_dll = "mspdb80.dll"; char* mspdb100_dll = "mspdb100.dll"; bool mspdb::DBI::isVS10 = false; bool getInstallDir(const char* version, char* installDir, DWORD size) { char key[260] = "SOFTWARE\\Microsoft\\"; strcat(key, version); HKEY hkey; if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE, &hkey) != ERROR_SUCCESS) return false; bool rc = RegQueryValueExA(hkey, "InstallDir", 0, 0, (LPBYTE)installDir, &size) == ERROR_SUCCESS; RegCloseKey(hkey); return rc; } bool tryLoadMsPdb(const char* version, const char* mspdb) { char installDir[260]; if (!getInstallDir(version, installDir, sizeof(installDir))) return false; char* p = installDir + strlen(installDir); if (p[-1] != '\\' && p[-1] != '/') *p++ = '\\'; strcpy(p, mspdb); modMsPdb = LoadLibraryA(installDir); return modMsPdb != 0; } bool initMsPdb() { if (!modMsPdb) modMsPdb = LoadLibraryA(mspdb80_dll); if (!modMsPdb) tryLoadMsPdb("VisualStudio\\9.0", mspdb80_dll); if (!modMsPdb) tryLoadMsPdb("VisualStudio\\8.0", mspdb80_dll); if (!modMsPdb) tryLoadMsPdb("VCExpress\\9.0", mspdb80_dll); if (!modMsPdb) tryLoadMsPdb("VCExpress\\8.0", mspdb80_dll); #if 1 if (!modMsPdb) { modMsPdb = LoadLibraryA(mspdb100_dll); if (!modMsPdb) tryLoadMsPdb("VisualStudio\\10.0", mspdb100_dll); if (!modMsPdb) tryLoadMsPdb("VCExpress\\10.0", mspdb100_dll); if (modMsPdb) mspdb::DBI::isVS10 = true; } #endif if (!modMsPdb) return false; if (!pPDBOpen2W) pPDBOpen2W = (mspdb::fnPDBOpen2W*) GetProcAddress(modMsPdb, "PDBOpen2W"); if (!pPDBOpen2W) return false; return true; } bool exitMsPdb() { pPDBOpen2W = 0; if (modMsPdb) FreeLibrary(modMsPdb); modMsPdb = 0; return true; } mspdb::PDB* CreatePDB(const wchar_t* pdbname) { if (!initMsPdb ()) return 0; mspdb::PDB* pdb = 0; long data[194] = { 193, 0 }; wchar_t ext[256] = L".exe"; if (!(*pPDBOpen2W) (pdbname, "wf", data, ext, 0x400, &pdb)) return 0; return pdb; }
MartinNowak/cv2pdb
src/mspdb.cpp
C++
artistic-2.0
2,441
public class Lab4_2 { public static void main(String[] arg) { System.out.print(" * |"); for(int x=1;x<=12;x++) { if (x<10) System.out.print(' '); if (x<100) System.out.print(' '); System.out.print(x+" "); } System.out.println(); for(int x=1;x<=21;x++) { if (x<10) System.out.print('-'); System.out.print("--"); } System.out.println(); for(int i=1;i<=12;i++) { if (i<10) System.out.print(' '); System.out.print(i+" |"); for(int j=1;j<=12;j++) { if (i*j<10) System.out.print(' '); if (j*i<100) System.out.print(' '); System.out.print(j*i+" "); } System.out.println(); } System.out.println(); System.out.println(); System.out.print(" + |"); for(int x=1;x<=12;x++) { if (x<10) System.out.print(' '); if (x<100) System.out.print(' '); System.out.print(x+" "); } System.out.println(); for(int x=1;x<=21;x++) { if (x<10) System.out.print('-'); System.out.print("--"); } System.out.println(); for(int i=1;i<=12;i++) { if (i<10) System.out.print(' '); System.out.print(i+" |"); for(int j=1;j<=12;j++) { if (i+j<10) System.out.print(' '); if (j+i<100) System.out.print(' '); System.out.print(j+i+" "); } System.out.println(); } } }
Seven-and-Nine/example-code-for-nine
Java/normal code/Java I/Lab4/Lab4_2.java
Java
artistic-2.0
1,401
var HLSP = { /* set squareness to 0 for a flat land */ // intensità colore land audioreattivab più bassa mizu: { cameraPositionY: 10, seaLevel: 0, displayText: '<b>CHAPTER ONE, MIZU</b><br/><i>TO BE TRAPPED INTO THE MORNING UNDERTOW</i>', speed: 10, modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0], tiles: 62, repeatUV: 1, bFactor: 0.5, cFactor: 0.07594379703811609, buildFreq: 10, natural: 0.6834941733430447, rainbow: 0.5641539208545766, squareness: 0.022450016948639295, map: 'white', landRGB: 1966335, horizonRGB: 0, skyMap: 'sky4', }, // fft1 più speedup moveSpeed solar_valley: { cameraPositionY: -180, seaLevel: -450, fogDensity: 0.00054, displayText: '<b>CHAPTER TWO, SOLAR VALLEY</b><br><i>FIRE EXECUTION STOPPED BY CLOUDS</i>', speed: 10, modelsParams: ['stones', function(){return 1+Math.random()*5}, 40, true, false, -750], tiles: 200, repeatUV: 7, bFactor: 0.6617959456178687, cFactor: 0.3471716436028164, buildFreq: 10, natural: 0.18443493566399619, rainbow: 0.03254734158776403, squareness: 0.00001, map: 'land3', landRGB: 9675935, horizonRGB: 3231404, skyMap: 'sky4', }, // camera underwater escher_surfers: { cameraPositionY: 40, seaLevel: 50, displayText: '<b>CHAPTER THREE, ESCHER SURFERS</b><br><i>TAKING REST ON K 11</i>', speed: 15, modelsParams: ['cube', 3, 1, true, true, 0 ], tiles: 73, repeatUV: 112, bFactor: 1.001, cFactor: 0, buildFreq: 10, natural: 0, rainbow: 0.16273670793882017, squareness: 0.08945796327125173, map: 'pattern1', landRGB: 16727705, horizonRGB: 7935, skyMap: 'sky1', }, // sea level più basso // modelli: cubid currybox: { cameraPositionY: 100,//HLE.WORLD_HEIGHT*.5, seaLevel: -100, displayText: '<b>CHAPTER FOUR, CURRYBOX</b><br><i>A FLAKE ON THE ROAD AND A KING AND HIS BONES</i>', speed: 5, modelsParams: [['cube'], function(){return 1+Math.random()*5}, 1, true, false,-100], tiles: 145, repeatUV: 1, bFactor: 0.751, cFactor: 0.054245569312940056, buildFreq: 10, natural: 0.176420247632921, rainbow: 0.21934025248846812, squareness: 0.01, map: 'white', landRGB: 13766158, horizonRGB: 2665099, skyMap: 'sky1', }, // sealevel basso galaxy_glacier: { cameraPositionY: 50, seaLevel: -100, displayText: '<b>CHAPTER FIVE, GALAXY GLACIER</b><br><i>HITTING ICEBERGS BLAMES</i>', speed: 2, modelsParams: [null, 1, true, true], tiles: 160, repeatUV: 1, bFactor: 0.287989180087759, cFactor: 0.6148319562024518, buildFreq: 61.5837970429, natural: 0.4861551769529205, rainbow: 0.099628324585666777, squareness: 0.01198280149135716, map: 'pattern5', //% landRGB: 11187452, horizonRGB: 6705, skyMap: 'sky1', }, firefly: { cameraPositionY: 50, displayText: '<b>CHAPTER SIX, FIREFLY</b>', speed: 10, modelsParams: ['sea', 1, true, true], tiles: 100, repeatUV: 1, bFactor: 1, cFactor: 1, buildFreq: 1, natural: 1, rainbow: 0, squareness: 0, map: 'white', landRGB: 2763306, horizonRGB: 0, skyMap: 'sky1', }, //camera position.y -400 // partire sopra acqua, e poi gradualmente finire sott'acqua //G drift: { cameraPositionY: -450, seaLevel: 0, displayText: '<b>CHAPTER SEVEN, DRIFT</b><br><i>LEAVING THE BOAT</i>', speed: 3, modelsParams: [['ducky'], function(){return 1+Math.random()*2}, 2, true, true, 0], tiles: 128, repeatUV: 0, bFactor: 0.24952961883952426, cFactor: 0.31, buildFreq: 15.188759407623216, natural: 0.3471716436028164, rainbow: 1.001, squareness: 0.00001, map: 'land1', landRGB: 16777215, horizonRGB: 6039170, skyMap: 'sky2', }, //H hyperocean: { cameraPositionY: 50, displayText: '<b>CHAPTER EIGHT, HYPEROCEAN</b><br><i>CRAVING FOR LOVE LASTS FOR LIFE</i>', speed: 8,//18, modelsParams: ['space', 2, 40, true, false, 200], tiles: 200, repeatUV: 12, bFactor: 1.001, cFactor: 0.21934025248846812, buildFreq: 15.188759407623216, natural: 0.7051924010682208, rainbow: 0.1952840495265842, squareness: 0.00001, map: 'land5', landRGB: 14798516, horizonRGB: 7173242, skyMap: 'sky2', }, // balene // capovolgere di conseguenza modelli balene //I twin_horizon: { cameraPositionY: 100, displayText: '<b>CHAPTER NINE, TWIN HORIZON</b><br><i>ON THE RIGHT VISION TO THE RIGHT SEASON</i>', speed: 10, modelsParams: ['sea', function(){return 20+Math.random()*20}, 20, false, false, 550], tiles: 99, repeatUV: 1, bFactor: 0.20445411338494512, cFactor: 0.33632252974022836, buildFreq: 45.50809304437684, natural: 0.4448136683661085, rainbow: 0, squareness: 0.0013619887944460984, map: 'white', landRGB: 0x000fff, horizonRGB: 16728899, skyMap: 'sky1', }, // da un certo punto random colors (quando il pezzo aumenta) // da stesso punto aumenta velocità // sea level basso // modelli elettrodomestici / elettronica //J else: { cameraPositionY: 50, displayText: '<b>CHAPTER TEN, ELSE</b><br><i>DIE LIKE AN ELECTRIC MACHINE</i>', speed: 10, modelsParams: [['ducky'], function(){return 2+Math.random()*20}, 3, true, true, 0], tiles: 104, repeatUV: 128, bFactor: 0.5641539208545766, cFactor: 0, buildFreq: 30.804098302357595, natural: 0.0, rainbow: 0.6458797021572349, squareness: 0.013562721707765414, map: 'pattern2', landRGB: 65399, horizonRGB: 0x000000, skyMap: 'sky3', }, // quando iniziano i kick randomizza landscape // odissea nello spazio // cielo stellato (via lattea) //K roger_water: { cameraPositionY: 50, displayText: '<b>CHAPTER ELEVEN, ROGER WATER</b><br><i>PROTECT WATER</i>', speed: 10, modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0], tiles: 80, repeatUV: 1, bFactor: 0, cFactor: 0.20613316338917223, buildFreq: 10, natural: 1.001, rainbow: 0.1735858218014082, squareness: 0.00001, map: 'white', landRGB: 2105376, horizonRGB: 0, skyMap: 'sky1', }, //L alpha_11: { cameraPositionY: 50, displayText: '<b>CHAPTER TWELVE, ALPHA 11</b><br><i>A MASSIVE WAVE IS DRIVING ME HOME</i>', speed: 1, modelsParams: ['stones', function(){return 1+Math.random()*40}, 3, true, true, 0], tiles: 6, repeatUV: 1, bFactor: 0, cFactor: 0, buildFreq: 44.48136683661085, natural: 0, rainbow: 0, squareness: 0.00001, map: 'white', landRGB: 0, horizonRGB: 3980219, skyMap: 'sky1', }, //M blackpool: { displayText: 'BLACKPOOL', speed: -10, modelsParams: ['space', 2, 400, true, false, 200], cameraPositionY: 110, seaLevel: 10, // speed: 4, // modelsParams: ['sea', 1, true, true], tiles: 182, repeatUV: 16.555478741450983, bFactor: 0.6048772396441062, cFactor: 0.016358953883098624, buildFreq: 73.3797815423632, natural: 0.9833741906510363, rainbow: 0.10821609644148733, squareness: 0.00599663055740593, map: 'land3', landRGB: 12105440, horizonRGB: 2571781, skyMap: 'sky1', }, intro: { cameraPositionY: 650, seaLevel:0, displayText: 'INTRO', speed: 0, modelsParams: ['sea', 1, true, true], tiles: 100, repeatUV: 1, bFactor: 0, cFactor: 0, buildFreq: 10, natural: 1, rainbow: 0, squareness: 0, map: 'sky1', landRGB: 0x111111, horizonRGB: 0x6f6f6f, skyMap: 'sky3' } }
stmaccarelli/HYPERLAND
src/sceneParams_0.js
JavaScript
artistic-2.0
9,148
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package uk.co.senab.photoview; import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.widget.ImageView; public class PhotoView extends ImageView implements IPhotoView { private final PhotoViewAttacher mAttacher; private ScaleType mPendingScaleType; public PhotoView(Context context) { this(context, null); } public PhotoView(Context context, AttributeSet attr) { this(context, attr, 0); } public PhotoView(Context context, AttributeSet attr, int defStyle) { super(context, attr, defStyle); super.setScaleType(ScaleType.MATRIX); mAttacher = new PhotoViewAttacher(this); if (null != mPendingScaleType) { setScaleType(mPendingScaleType); mPendingScaleType = null; } } @Override public void setPhotoViewRotation(float rotationDegree) { mAttacher.setPhotoViewRotation(rotationDegree); } @Override public boolean canZoom() { return mAttacher.canZoom(); } @Override public RectF getDisplayRect() { return mAttacher.getDisplayRect(); } @Override public Matrix getDisplayMatrix() { return mAttacher.getDrawMatrix(); } @Override public boolean setDisplayMatrix(Matrix finalRectangle) { return mAttacher.setDisplayMatrix(finalRectangle); } @Override @Deprecated public float getMinScale() { return getMinimumScale(); } @Override public float getMinimumScale() { return mAttacher.getMinimumScale(); } @Override @Deprecated public float getMidScale() { return getMediumScale(); } @Override public float getMediumScale() { return mAttacher.getMediumScale(); } @Override @Deprecated public float getMaxScale() { return getMaximumScale(); } @Override public float getMaximumScale() { return mAttacher.getMaximumScale(); } @Override public float getScale() { return mAttacher.getScale(); } @Override public ScaleType getScaleType() { return mAttacher.getScaleType(); } @Override public void setAllowParentInterceptOnEdge(boolean allow) { mAttacher.setAllowParentInterceptOnEdge(allow); } @Override @Deprecated public void setMinScale(float minScale) { setMinimumScale(minScale); } @Override public void setMinimumScale(float minimumScale) { mAttacher.setMinimumScale(minimumScale); } @Override @Deprecated public void setMidScale(float midScale) { setMediumScale(midScale); } @Override public void setMediumScale(float mediumScale) { mAttacher.setMediumScale(mediumScale); } @Override @Deprecated public void setMaxScale(float maxScale) { setMaximumScale(maxScale); } @Override public void setMaximumScale(float maximumScale) { mAttacher.setMaximumScale(maximumScale); } @Override // setImageBitmap calls through to this method public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); if (null != mAttacher) { mAttacher.update(); } } @Override public void setImageResource(int resId) { super.setImageResource(resId); if (null != mAttacher) { mAttacher.update(); } } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); if (null != mAttacher) { mAttacher.update(); } } @Override public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { mAttacher.setOnMatrixChangeListener(listener); } @Override public void setOnLongClickListener(OnLongClickListener l) { mAttacher.setOnLongClickListener(l); } @Override public void setOnPhotoTapListener(OnPhotoTapListener listener) { mAttacher.setOnPhotoTapListener(listener); } @Override public OnPhotoTapListener getOnPhotoTapListener() { return mAttacher.getOnPhotoTapListener(); } @Override public void setOnViewTapListener(OnViewTapListener listener) { mAttacher.setOnViewTapListener(listener); } @Override public OnViewTapListener getOnViewTapListener() { return mAttacher.getOnViewTapListener(); } @Override public void setScale(float scale) { mAttacher.setScale(scale); } @Override public void setScale(float scale, boolean animate) { mAttacher.setScale(scale, animate); } @Override public void setScale(float scale, float focalX, float focalY, boolean animate) { mAttacher.setScale(scale, focalX, focalY, animate); } @Override public void setScaleType(ScaleType scaleType) { if (null != mAttacher) { mAttacher.setScaleType(scaleType); } else { mPendingScaleType = scaleType; } } @Override public void setZoomable(boolean zoomable) { mAttacher.setZoomable(zoomable); } @Override public Bitmap getVisibleRectangleBitmap() { return mAttacher.getVisibleRectangleBitmap(); } @Override public void setZoomTransitionDuration(int milliseconds) { mAttacher.setZoomTransitionDuration(milliseconds); } @Override protected void onDetachedFromWindow() { mAttacher.cleanup(); super.onDetachedFromWindow(); } }
cocolove2/LISDemo
library-lis/src/main/java/uk/co/senab/photoview/PhotoView.java
Java
artistic-2.0
6,686
""" WSGI config for brp project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from dj_static import Cling from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "brp.settings") os.environ.setdefault('DJANGO_CONFIGURATION', 'Dev') application = Cling(get_wsgi_application())
chop-dbhi/biorepo-portal
brp/wsgi.py
Python
bsd-2-clause
471
class Imagemagick < Formula desc "Tools and libraries to manipulate images in many formats" homepage "https://www.imagemagick.org/" # Please always keep the Homebrew mirror as the primary URL as the # ImageMagick site removes tarballs regularly which means we get issues # unnecessarily and older versions of the formula are broken. url "https://dl.bintray.com/homebrew/mirror/imagemagick-7.0.7-7.tar.xz" mirror "https://www.imagemagick.org/download/ImageMagick-7.0.7-7.tar.xz" sha256 "01b7171b784fdc689697fa35fbfa70e716a9e1608d45f81015ba78f6583f1dcf" head "https://github.com/ImageMagick/ImageMagick.git" bottle do sha256 "7ba7870bae8a8b3236240cbbb6f9fde5598d78dd567c936857dd1470f7e3c7af" => :high_sierra sha256 "7fe3ef5dc80215fb9050f441d1d00191233b90da646b3eb60f0295f00cf38169" => :sierra sha256 "3da2ca31353e9139acd51037696a4b0bd5e2ebecdcd9f06cef1d889836e99277" => :el_capitan end option "with-fftw", "Compile with FFTW support" option "with-hdri", "Compile with HDRI support" option "with-opencl", "Compile with OpenCL support" option "with-openmp", "Compile with OpenMP support" option "with-perl", "Compile with PerlMagick" option "without-magick-plus-plus", "disable build/install of Magick++" option "without-modules", "Disable support for dynamically loadable modules" option "without-threads", "Disable threads support" option "with-zero-configuration", "Disables depending on XML configuration files" deprecated_option "enable-hdri" => "with-hdri" deprecated_option "with-jp2" => "with-openjpeg" depends_on "pkg-config" => :build depends_on "libtool" => :run depends_on "xz" depends_on "jpeg" => :recommended depends_on "libpng" => :recommended depends_on "libtiff" => :recommended depends_on "freetype" => :recommended depends_on :x11 => :optional depends_on "fontconfig" => :optional depends_on "little-cms" => :optional depends_on "little-cms2" => :optional depends_on "libwmf" => :optional depends_on "librsvg" => :optional depends_on "liblqr" => :optional depends_on "openexr" => :optional depends_on "ghostscript" => :optional depends_on "webp" => :optional depends_on "openjpeg" => :optional depends_on "fftw" => :optional depends_on "pango" => :optional depends_on :perl => ["5.5", :optional] needs :openmp if build.with? "openmp" skip_clean :la def install args = %W[ --disable-osx-universal-binary --prefix=#{prefix} --disable-dependency-tracking --disable-silent-rules --enable-shared --enable-static ] if build.without? "modules" args << "--without-modules" else args << "--with-modules" end if build.with? "opencl" args << "--enable-opencl" else args << "--disable-opencl" end if build.with? "openmp" args << "--enable-openmp" else args << "--disable-openmp" end if build.with? "webp" args << "--with-webp=yes" else args << "--without-webp" end if build.with? "openjpeg" args << "--with-openjp2" else args << "--without-openjp2" end args << "--without-gslib" if build.without? "ghostscript" args << "--with-perl" << "--with-perl-options='PREFIX=#{prefix}'" if build.with? "perl" args << "--with-gs-font-dir=#{HOMEBREW_PREFIX}/share/ghostscript/fonts" if build.without? "ghostscript" args << "--without-magick-plus-plus" if build.without? "magick-plus-plus" args << "--enable-hdri=yes" if build.with? "hdri" args << "--without-fftw" if build.without? "fftw" args << "--without-pango" if build.without? "pango" args << "--without-threads" if build.without? "threads" args << "--with-rsvg" if build.with? "librsvg" args << "--without-x" if build.without? "x11" args << "--with-fontconfig=yes" if build.with? "fontconfig" args << "--with-freetype=yes" if build.with? "freetype" args << "--enable-zero-configuration" if build.with? "zero-configuration" args << "--without-wmf" if build.without? "libwmf" # versioned stuff in main tree is pointless for us inreplace "configure", "${PACKAGE_NAME}-${PACKAGE_VERSION}", "${PACKAGE_NAME}" system "./configure", *args system "make", "install" end def caveats s = <<-EOS.undent For full Perl support you may need to adjust your PERL5LIB variable: export PERL5LIB="#{HOMEBREW_PREFIX}/lib/perl5/site_perl":$PERL5LIB EOS s if build.with? "perl" end test do assert_match "PNG", shell_output("#{bin}/identify #{test_fixtures("test.png")}") # Check support for recommended features and delegates. features = shell_output("#{bin}/convert -version") %w[Modules freetype jpeg png tiff].each do |feature| assert_match feature, features end end end
bfontaine/homebrew-core
Formula/imagemagick.rb
Ruby
bsd-2-clause
4,820
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Reflection; using CSScriptLibrary; using System.Windows.Controls; using Mono.CSharp; namespace RobinhoodDesktop.Script { /// <summary> /// Specifies the options for keeping processed data in memory. Ideally all processed data would be kept, /// but if there is not enough memory for that then some may be discarded once processing has completed. /// </summary> public enum MemoryScheme { MEM_KEEP_NONE, MEM_KEEP_SOURCE, MEM_KEEP_DERIVED } [Serializable] public class StockSession { #region Constants /// <summary> /// The designator for the stock data source (the data read from the file/live interface) /// </summary> public const string SOURCE_CLASS = "StockDataSource"; /// <summary> /// The designator for the stock data sink (the analyzed data) /// </summary> public const string SINK_CLASS = "StockDataSink"; #endregion #region Variables /// <summary> /// Stores a reference to the most recent session that was created (probably the only session) /// </summary> public static StockSession Instance; /// <summary> /// The path to the source data file /// </summary> public string SourceFilePath; /// <summary> /// The list of scripts that should be loaded to process the stock data /// </summary> public List<string> DataScriptPaths = new List<string>(); /// <summary> /// The data file the source stock data is being pulled from /// </summary> [NonSerialized] public StockDataFile SourceFile; /// <summary> /// The data file representing the analyzed stock data /// </summary> [NonSerialized] public StockDataFile SinkFile; /// <summary> /// The stock data associated with the session /// </summary> [NonSerialized] public Dictionary<string, List<StockDataInterface>> Data; /// <summary> /// List of action scripts that have been executed /// </summary> public Dictionary<object, Assembly> Scripts = new Dictionary<object, Assembly>(); /// <summary> /// Callback that can be used to add an element to the GUI /// </summary> [NonSerialized] public static AddGuiFunc AddToGui = null; public delegate void AddGuiFunc(System.Windows.Forms.Control c); /// <summary> /// The container object that other GUI elements should be added to /// </summary> [NonSerialized] public static System.Windows.Forms.Control GuiContainer = null; /// <summary> /// Callback that can be executed when the session is reloaded /// </summary> /// [NonSerialized] public Action OnReload; /// <summary> /// A list of charts associated with this session /// </summary> public List<DataChartGui> Charts = new List<DataChartGui>(); #endregion /// <summary> /// Creates a session based on the specified source data an analysis scripts /// </summary> /// <param name="sources">The source data files</param> /// <param name="sinkScripts">The data analysis scripts</param> /// <returns>The session instance</returns> public static StockSession LoadData(List<string> sources, List<string> sinkScripts) { StockSession session = new StockSession(); session.DataScriptPaths.Clear(); Directory.CreateDirectory("tmp"); // Convert any legacy files before further processing var legacyFiles = sources.Where((s) => { return s.EndsWith(".csv"); }).ToList(); if(legacyFiles.Count() > 0) { System.Windows.Forms.SaveFileDialog saveDiag = new System.Windows.Forms.SaveFileDialog(); saveDiag.Title = "Save converted data file as..."; saveDiag.CheckFileExists = false; if (saveDiag.ShowDialog() == System.Windows.Forms.DialogResult.OK) { List<string> convertedFileNames; var convertedFiles = StockDataFile.ConvertByMonth(legacyFiles, Path.GetDirectoryName(saveDiag.FileName), out convertedFileNames); foreach (var cf in convertedFileNames) sources.Add(cf); } else { // Cancel running the script return null; } foreach(var l in legacyFiles) sources.Remove(l); } session.SourceFile = StockDataFile.Open(sources.ConvertAll<Stream>((s) => { return System.IO.Stream.Synchronized(new FileStream(s, FileMode.Open)); })); session.DataScriptPaths.Add("tmp/" + SOURCE_CLASS + ".cs"); using(var file = new StreamWriter(new FileStream(session.DataScriptPaths.Last(), FileMode.Create))) file.Write(session.SourceFile.GetSourceCode(SOURCE_CLASS)); // Put the data set reference script first List<string> totalSinkScripts = sinkScripts.ToList(); totalSinkScripts.Insert(0, "Script\\Data\\DataSetReference.cs"); session.SinkFile = new StockDataFile(totalSinkScripts.ConvertAll<string>((f) => { return Path.GetFileNameWithoutExtension(f); }), totalSinkScripts.ConvertAll<string>((f) => { return File.ReadAllText(f); })); session.SinkFile.Interval = session.SourceFile.Interval; session.DataScriptPaths.Add("tmp/" + SINK_CLASS + ".cs"); using(var file = new StreamWriter(new FileStream(session.DataScriptPaths.Last(), FileMode.Create))) file.Write(session.SinkFile.GenStockDataSink()); session.DataScriptPaths.AddRange(totalSinkScripts); // Create the evaluator file (needs to be compiled in the script since it references StockDataSource) string[] embeddedFiles = new string[] { "RobinhoodDesktop.Script.StockEvaluator.cs", "RobinhoodDesktop.Script.StockProcessor.cs" }; foreach(var f in embeddedFiles) { session.DataScriptPaths.Add(string.Format("tmp/{0}.cs", f.Substring(24, f.Length - 27))); StringBuilder analyzerCode = new StringBuilder(); analyzerCode.Append(new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(f)).ReadToEnd()); using(var file = new StreamWriter(new FileStream(session.DataScriptPaths.Last(), FileMode.Create))) file.Write(StockDataFile.FormatSource(analyzerCode.ToString())); } // Add the user defined analyzers foreach(string path in Directory.GetFiles(@"Script/Decision", "*.cs", SearchOption.AllDirectories)) session.DataScriptPaths.Add(path); foreach(string path in Directory.GetFiles(@"Script/Action", "*.cs", SearchOption.AllDirectories)) session.DataScriptPaths.Add(path); // Build the data session.Reload(); if(session.Data != null) { StockSession.Instance = session; } else { session.SourceFile.Close(); } return StockSession.Instance; } /// <summary> /// Creates a chart instance within a data script /// </summary> /// <param name="sources">The data sources to load</param> /// <param name="sinkScripts">The data processors to apply</param> public static DataChartGui AddChart(List<string> sources, List<string> sinkScripts) { var session = (Instance != null) ? Instance : LoadData(sources, sinkScripts); DataChartGui chart = null; if(session != null) chart = session.AddChart(); return chart; } /// <summary> /// Creates a new chart and adds it to the session /// </summary> /// <returns>The created chart</returns> public DataChartGui AddChart() { DataChartGui chart = null; if(this.Data != null) { try { chart = new DataChartGui(this.Data, this); this.Charts.Add(chart); var ctrl = (System.Windows.Forms.Control)(chart.GuiPanel); if((ctrl != null) && (AddToGui != null)) { AddToGui(ctrl); } } catch(Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); } } return chart; } /// <summary> /// Reloads the scripts and executes them /// </summary> public void Reload() { Data = null; SourceFile.Reload(); SinkFile.Reload(); // Re-load the data scripts, pulling in any recent changes Run(this, DataScriptPaths); // Create and get the StockProcessor instance, which also populates the Data field in the session Assembly dataScript; if(Scripts.TryGetValue(this, out dataScript)) { var getProcessor = dataScript.GetStaticMethod("RobinhoodDesktop.Script.StockProcessor.GetInstance", this); var processor = getProcessor(this); // Execute the reload callback if(OnReload != null) OnReload(); } } /// <summary> /// Loads a script instance /// </summary> public void Run(object owner, List<string> scripts) { #if DEBUG var isDebug = true; #else var isDebug = false; #endif Assembly oldScript; if(Scripts.TryGetValue(owner, out oldScript)) { oldScript.UnloadOwnerDomain(); Scripts.Remove(owner); } try { CSScript.EvaluatorConfig.Engine = EvaluatorEngine.Mono; CSScript.MonoEvaluator.CompilerSettings.Platform = Mono.CSharp.Platform.X64; List<string> references = new List<string>() { "TensorFlow.NET.dll", "Google.Protobuf.dll", "Newtonsoft.Json", "NumSharp.Lite", "netstandard", "System.Memory", "System.Numerics" }; foreach(var s in Scripts.Values) references.Add(s.Location); Scripts[owner] = CSScript.LoadFiles(scripts.ToArray(), null, isDebug, references.ToArray()); // Check if a "Run" method should be executed MethodDelegate runFunc = null; try { runFunc = Scripts[owner].GetStaticMethod("*.Run", this); } catch(Exception ex) { }; if(runFunc != null) { System.Threading.Tasks.Task.Run(() => { runFunc(this); }); } } catch(Exception ex) { string err = ex.ToString(); System.Text.RegularExpressions.Regex.Replace(err, "\r\n.*?warning.*?\r\n", "\r\n"); Console.WriteLine(err); System.Windows.Forms.MessageBox.Show(err); } } } }
Terohnon/RobinhoodDesktop
RobinhoodDesktop/RobinhoodDesktop/Script/StockSession.cs
C#
bsd-2-clause
12,086
<?php $bbcode["code"] = array( 'callback' => 'bbcodeCodeHighlight', 'pre' => TRUE, ); $bbcode["source"] = array( 'callback' => 'bbcodeCodeHighlight', 'pre' => TRUE, ); function bbcodeCodeHighlight($dom, $contents, $arg) { // in <pre> style $contents = preg_replace('/^\n|\n$/', "", $contents); include_once("geshi.php"); if(!$arg) { $div = $dom->createElement('div'); $div->setAttribute('class', 'codeblock'); $div->appendChild($dom->createTextNode($contents)); return $div; } else { $language = $arg; $geshi = new GeSHi($contents, $language); $geshi->set_header_type(GESHI_HEADER_NONE); $geshi->enable_classes(); $geshi->enable_keyword_links(false); $code = str_replace("\n", "", $geshi->parse_code()); return markupToMarkup($dom, "<div class=\"codeblock geshi\">$code</div>"); } }
RoseyDreamy/ABXD-Omega
plugins/sourcetag/bbcode.php
PHP
bsd-2-clause
834
/* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez <andres@phalconphp.com> | | Eduar Carvajal <eduar@phalconphp.com> | +------------------------------------------------------------------------+ */ #include "mvc/view/engine.h" #include "mvc/view/engineinterface.h" #include "di/injectable.h" #include "kernel/main.h" #include "kernel/memory.h" #include "kernel/object.h" #include "kernel/fcall.h" /** * Phalcon\Mvc\View\Engine * * All the template engine adapters must inherit this class. This provides * basic interfacing between the engine and the Phalcon\Mvc\View component. */ zend_class_entry *phalcon_mvc_view_engine_ce; PHP_METHOD(Phalcon_Mvc_View_Engine, __construct); PHP_METHOD(Phalcon_Mvc_View_Engine, getContent); PHP_METHOD(Phalcon_Mvc_View_Engine, partial); PHP_METHOD(Phalcon_Mvc_View_Engine, getView); ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_view_engine___construct, 0, 0, 1) ZEND_ARG_INFO(0, view) ZEND_ARG_INFO(0, dependencyInjector) ZEND_END_ARG_INFO() static const zend_function_entry phalcon_mvc_view_engine_method_entry[] = { PHP_ME(Phalcon_Mvc_View_Engine, __construct, arginfo_phalcon_mvc_view_engine___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR) PHP_ME(Phalcon_Mvc_View_Engine, getContent, NULL, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine, partial, arginfo_phalcon_mvc_view_engineinterface_partial, ZEND_ACC_PUBLIC) PHP_ME(Phalcon_Mvc_View_Engine, getView, NULL, ZEND_ACC_PUBLIC) PHP_FE_END }; /** * Phalcon\Mvc\View\Engine initializer */ PHALCON_INIT_CLASS(Phalcon_Mvc_View_Engine){ PHALCON_REGISTER_CLASS_EX(Phalcon\\Mvc\\View, Engine, mvc_view_engine, phalcon_di_injectable_ce, phalcon_mvc_view_engine_method_entry, ZEND_ACC_EXPLICIT_ABSTRACT_CLASS); zend_declare_property_null(phalcon_mvc_view_engine_ce, SL("_view"), ZEND_ACC_PROTECTED TSRMLS_CC); zend_class_implements(phalcon_mvc_view_engine_ce TSRMLS_CC, 1, phalcon_mvc_view_engineinterface_ce); return SUCCESS; } /** * Phalcon\Mvc\View\Engine constructor * * @param Phalcon\Mvc\ViewInterface $view * @param Phalcon\DiInterface $dependencyInjector */ PHP_METHOD(Phalcon_Mvc_View_Engine, __construct){ zval *view, *dependency_injector = NULL; phalcon_fetch_params(0, 1, 1, &view, &dependency_injector); if (!dependency_injector) { dependency_injector = PHALCON_GLOBAL(z_null); } phalcon_update_property_this(this_ptr, SL("_view"), view TSRMLS_CC); phalcon_update_property_this(this_ptr, SL("_dependencyInjector"), dependency_injector TSRMLS_CC); } /** * Returns cached ouput on another view stage * * @return array */ PHP_METHOD(Phalcon_Mvc_View_Engine, getContent) { zval *view = phalcon_fetch_nproperty_this(this_ptr, SL("_view"), PH_NOISY TSRMLS_CC); PHALCON_RETURN_CALL_METHODW(view, "getcontent"); } /** * Renders a partial inside another view * * @param string $partialPath * @param array $params * @return string */ PHP_METHOD(Phalcon_Mvc_View_Engine, partial){ zval *partial_path, *params = NULL, *view; phalcon_fetch_params(0, 1, 1, &partial_path, &params); if (!params) { params = PHALCON_GLOBAL(z_null); } view = phalcon_fetch_nproperty_this(this_ptr, SL("_view"), PH_NOISY TSRMLS_CC); PHALCON_RETURN_CALL_METHODW(view, "partial", partial_path, params); } /** * Returns the view component related to the adapter * * @return Phalcon\Mvc\ViewInterface */ PHP_METHOD(Phalcon_Mvc_View_Engine, getView){ RETURN_MEMBER(this_ptr, "_view"); }
unisys12/phalcon-hhvm
ext/mvc/view/engine.cpp
C++
bsd-2-clause
4,384
""" recursely """ __version__ = "0.1" __description__ = "Recursive importer for Python submodules" __author__ = "Karol Kuczmarski" __license__ = "Simplified BSD" import sys from recursely._compat import IS_PY3 from recursely.importer import RecursiveImporter from recursely.utils import SentinelList __all__ = ['install'] def install(retroactive=True): """Install the recursive import hook in ``sys.meta_path``, enabling the use of ``__recursive__`` directive. :param retroactive: Whether the hook should be retroactively applied to module's that have been imported before it was installed. """ if RecursiveImporter.is_installed(): return importer = RecursiveImporter() # because the hook is a catch-all one, we ensure that it's always # at the very end of ``sys.meta_path``, so that it's tried only if # no other (more specific) hook has been chosen by Python if IS_PY3: for i in reversed(range(len(sys.meta_path))): ih_module = getattr(sys.meta_path[i], '__module__', '') is_builtin = ih_module == '_frozen_importlib' if not is_builtin: break sys.meta_path = SentinelList( sys.meta_path[:i], sentinels=[importer] + sys.meta_path[i:]) else: sys.meta_path = SentinelList(sys.meta_path, sentinel=importer) # look through already imported packages and recursively import # their submodules, if they contain the ``__recursive__`` directive if retroactive: for module in list(sys.modules.values()): importer.recurse(module)
Xion/recursely
recursely/__init__.py
Python
bsd-2-clause
1,663
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-id-init-unresolvable.case // - src/dstr-binding/error/for-of-let.template /*--- description: Destructuring initializer is an unresolvable reference (for-of statement) esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation es6id: 13.7.5.11 features: [destructuring-binding] flags: [generated] info: | IterationStatement : for ( ForDeclaration of AssignmentExpression ) Statement [...] 3. Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult, lexicalBinding, labelSet). 13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation [...] 3. Let destructuring be IsDestructuring of lhs. [...] 5. Repeat [...] h. If destructuring is false, then [...] i. Else i. If lhsKind is assignment, then [...] ii. Else if lhsKind is varBinding, then [...] iii. Else, 1. Assert: lhsKind is lexicalBinding. 2. Assert: lhs is a ForDeclaration. 3. Let status be the result of performing BindingInitialization for lhs passing nextValue and iterationEnv as arguments. [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 6. If Initializer is present and v is undefined, then a. Let defaultValue be the result of evaluating Initializer. b. Let v be GetValue(defaultValue). c. ReturnIfAbrupt(v). 6.2.3.1 GetValue (V) 1. ReturnIfAbrupt(V). 2. If Type(V) is not Reference, return V. 3. Let base be GetBase(V). 4. If IsUnresolvableReference(V), throw a ReferenceError exception. ---*/ assert.throws(ReferenceError, function() { for (let { x = unresolvableReference } of [{}]) { return; } });
sebastienros/jint
Jint.Tests.Test262/test/language/statements/for-of/dstr-let-obj-ptrn-id-init-unresolvable.js
JavaScript
bsd-2-clause
1,939
import {Component, OnInit} from '@angular/core'; import {MarketCard} from '../market-card'; import {MarketCardType} from '../market-card-type'; import {MarketService} from '../market.service'; import {Expansion} from '../expansion'; import { GameModeService } from '../game-mode.service'; import { GameMode } from '../game-mode'; @Component({ selector: 'app-market-selection', templateUrl: './market-selection.component.html', styleUrls: ['./market-selection.component.css'] }) export class MarketSelectionComponent implements OnInit { constructor(private marketService: MarketService, private gameModeService: GameModeService) { } cards: MarketCard[]; expeditionMode: boolean; ngOnInit() { this.marketService.marketCards$.subscribe((cards: MarketCard[]) => { this.cards = cards; }); this.cards = this.marketService.marketCards; this.gameModeService.selectedGameMode$.subscribe((newGameMode: GameMode) => { this.updateExpeditionMode(newGameMode); }); this.updateExpeditionMode(this.gameModeService.selectedGameMode); } getCardCssClass(type: MarketCardType): string { switch (type) { case MarketCardType.Gem: return 'gem-card'; case MarketCardType.Relic: return 'relic-card'; case MarketCardType.Spell: return 'spell-card'; } } getCardTypeLabel(type: MarketCardType): string { switch (type) { case MarketCardType.Gem: return 'Gem'; case MarketCardType.Relic: return 'Relic'; case MarketCardType.Spell: return 'Spell'; } } private updateExpeditionMode(gameMode: GameMode): void { this.expeditionMode = (gameMode !== GameMode.SingleGame); } }
kbarnes3/AeonsEnd
aeons-end/src/app/market-selection/market-selection.component.ts
TypeScript
bsd-2-clause
1,716
/** * Copyright (c) 2013, Jens Hohmuth * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package com.lessvoid.coregl; import com.lessvoid.coregl.spi.CoreGL; /** * Simple helper methods to render vertex arrays. * * @author void */ public class CoreRender { private final CoreGL gl; CoreRender(final CoreGL gl) { this.gl = gl; } public static CoreRender createCoreRender(final CoreGL gl) { return new CoreRender(gl); } // Lines /** * Render lines. * * @param count * number of vertices */ public void renderLines(final int count) { gl.glDrawArrays(gl.GL_LINE_STRIP(), 0, count); gl.checkGLError("glDrawArrays"); } /** * Render adjacent lines. * * @param count * number of vertices */ public void renderLinesAdjacent(final int count) { gl.glDrawArrays(gl.GL_LINE_STRIP_ADJACENCY(), 0, count); gl.checkGLError("glDrawArrays"); } // Triangle Strip /** * Render the currently active VAO using triangle strips with the given number * of vertices. * * @param count * number of vertices to render as triangle strips */ public void renderTriangleStrip(final int count) { gl.glDrawArrays(gl.GL_TRIANGLE_STRIP(), 0, count); gl.checkGLError("glDrawArrays"); } /** * Render the currently active VAO using triangle strips, sending the given * number of indizes. * * @param count * number of indizes to render as triangle strips */ public void renderTriangleStripIndexed(final int count) { gl.glDrawElements(gl.GL_TRIANGLE_STRIP(), count, gl.GL_UNSIGNED_INT(), 0); gl.checkGLError("glDrawElements(GL_TRIANGLE_STRIP)"); } /** * Render the currently active VAO using triangle strips with the given number * of vertices AND do that primCount times. * * @param count * number of vertices to render as triangle strips per primitve * @param primCount * number of primitives to render */ public void renderTriangleStripInstances(final int count, final int primCount) { gl.glDrawArraysInstanced(gl.GL_TRIANGLE_STRIP(), 0, count, primCount); gl.checkGLError("glDrawArraysInstanced(GL_TRIANGLE_STRIP)"); } // Triangle Fan /** * Render the currently active VAO using triangle fan with the given number of * vertices. * * @param count * number of vertices to render as triangle fan */ public void renderTriangleFan(final int count) { gl.glDrawArrays(gl.GL_TRIANGLE_FAN(), 0, count); gl.checkGLError("glDrawArrays"); } /** * Render the currently active VAO using triangle fans, sending the given * number of indizes. * * @param count * number of indizes to render as triangle fans. */ public void renderTriangleFanIndexed(final int count) { gl.glDrawElements(gl.GL_TRIANGLE_FAN(), count, gl.GL_UNSIGNED_INT(), 0); gl.checkGLError("glDrawElements(GL_TRIANGLE_FAN)"); } // Individual Triangles /** * Render the currently active VAO using triangles with the given number of * vertices. * * @param vertexCount * number of vertices to render as triangle strips */ public void renderTriangles(final int vertexCount) { gl.glDrawArrays(gl.GL_TRIANGLES(), 0, vertexCount); gl.checkGLError("glDrawArrays"); } /** * Render the currently active VAO using triangles with the given number of * vertices starting at the given offset. * * @param offset * offset to start sending vertices * @param vertexCount * number of vertices to render as triangle strips */ public void renderTrianglesOffset(final int offset, final int vertexCount) { gl.glDrawArrays(gl.GL_TRIANGLES(), offset, vertexCount); gl.checkGLError("glDrawArrays"); } /** * Render the currently active VAO using triangles with the given number of * vertices. * * @param count * number of vertices to render as triangles */ public void renderTrianglesIndexed(final int count) { gl.glDrawElements(gl.GL_TRIANGLES(), count, gl.GL_UNSIGNED_INT(), 0); gl.checkGLError("glDrawElements"); } /** * Render the currently active VAO using triangles with the given number of * vertices AND do that primCount times. * * @param count * number of vertices to render as triangles per primitve * @param primCount * number of primitives to render */ public void renderTrianglesInstances(final int count, final int primCount) { gl.glDrawArraysInstanced(gl.GL_TRIANGLES(), 0, count, primCount); gl.checkGLError("glDrawArraysInstanced(GL_TRIANGLES)"); } // Points /** * Render the currently active VAO using points with the given number of * vertices. * * @param count * number of vertices to render as points */ public void renderPoints(final int count) { gl.glDrawArrays(gl.GL_POINTS(), 0, count); gl.checkGLError("glDrawArrays(GL_POINTS)"); } /** * Render the currently active VAO using points with the given number of * vertices AND do that primCount times. * * @param count * number of vertices to render as points per primitive * @param primCount * number of primitives to render */ public void renderPointsInstances(final int count, final int primCount) { gl.glDrawArraysInstanced(gl.GL_POINTS(), 0, count, primCount); gl.checkGLError("glDrawArraysInstanced(GL_POINTS)"); } // Utils /** * Set the clear color. * * @param r * red * @param g * green * @param b * blue * @param a * alpha */ public void clearColor(final float r, final float g, final float b, final float a) { gl.glClearColor(r, g, b, a); } /** * Clear the color buffer. */ public void clearColorBuffer() { gl.glClear(gl.GL_COLOR_BUFFER_BIT()); } }
bgroenks96/coregl
coregl-utils/src/main/java/com/lessvoid/coregl/CoreRender.java
Java
bsd-2-clause
7,233
# coding: utf-8 import sys from setuptools import setup, find_packages NAME = "pollster" VERSION = "2.0.2" # To install the library, run the following # # python setup.py install # # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil", "pandas >= 0.19.1"] setup( name=NAME, version=VERSION, description="Pollster API", author_email="Adam Hooper <adam.hooper@huffingtonpost.com>", url="https://github.com/huffpostdata/python-pollster", keywords=["Pollster API"], install_requires=REQUIRES, packages=find_packages(), include_package_data=True, long_description="""Download election-related polling data from Pollster.""" )
huffpostdata/python-pollster
setup.py
Python
bsd-2-clause
756
import requests import logging import redis from requests.packages.urllib3.exceptions import ConnectionError from core.serialisers import json from dss import localsettings # TODO(fergal.moran@gmail.com): refactor these out to # classes to avoid duplicating constants below HEADERS = { 'content-type': 'application/json' } logger = logging.getLogger('spa') def post_notification(session_id, image, message): try: payload = { 'sessionid': session_id, 'image': image, 'message': message } data = json.dumps(payload) r = requests.post( localsettings.REALTIME_HOST + 'notification', data=data, headers=HEADERS ) if r.status_code == 200: return "" else: return r.text except ConnectionError: #should probably implement some sort of retry in here pass
fergalmoran/dss
core/realtime/notification.py
Python
bsd-2-clause
928
unless ENV["HOMEBREW_BREW_FILE"] raise "HOMEBREW_BREW_FILE was not exported! Please call bin/brew directly!" end require "constants" require "tmpdir" require "pathname" HOMEBREW_BREW_FILE = Pathname.new(ENV["HOMEBREW_BREW_FILE"]) TEST_TMPDIR = ENV.fetch("HOMEBREW_TEST_TMPDIR") do |k| dir = Dir.mktmpdir("homebrew-tests-", ENV["HOMEBREW_TEMP"] || "/tmp") at_exit { FileUtils.remove_entry(dir) } ENV[k] = dir end # Paths pointing into the Homebrew code base that persist across test runs HOMEBREW_LIBRARY_PATH = Pathname.new(File.expand_path("../../../..", __FILE__)) HOMEBREW_SHIMS_PATH = HOMEBREW_LIBRARY_PATH.parent+"Homebrew/shims" HOMEBREW_LOAD_PATH = [File.expand_path("..", __FILE__), HOMEBREW_LIBRARY_PATH].join(":") # Paths redirected to a temporary directory and wiped at the end of the test run HOMEBREW_PREFIX = Pathname.new(TEST_TMPDIR).join("prefix") HOMEBREW_REPOSITORY = HOMEBREW_PREFIX HOMEBREW_LIBRARY = HOMEBREW_REPOSITORY+"Library" HOMEBREW_CACHE = HOMEBREW_PREFIX.parent+"cache" HOMEBREW_CACHE_FORMULA = HOMEBREW_PREFIX.parent+"formula_cache" HOMEBREW_LINKED_KEGS = HOMEBREW_PREFIX.parent+"linked" HOMEBREW_PINNED_KEGS = HOMEBREW_PREFIX.parent+"pinned" HOMEBREW_LOCK_DIR = HOMEBREW_PREFIX.parent+"locks" HOMEBREW_CELLAR = HOMEBREW_PREFIX.parent+"cellar" HOMEBREW_LOGS = HOMEBREW_PREFIX.parent+"logs" HOMEBREW_TEMP = HOMEBREW_PREFIX.parent+"temp" TEST_FIXTURE_DIR = HOMEBREW_LIBRARY_PATH.join("test", "support", "fixtures") TESTBALL_SHA1 = "be478fd8a80fe7f29196d6400326ac91dad68c37".freeze TESTBALL_SHA256 = "91e3f7930c98d7ccfb288e115ed52d06b0e5bc16fec7dce8bdda86530027067b".freeze TESTBALL_PATCHES_SHA256 = "799c2d551ac5c3a5759bea7796631a7906a6a24435b52261a317133a0bfb34d9".freeze PATCH_A_SHA256 = "83404f4936d3257e65f176c4ffb5a5b8d6edd644a21c8d8dcc73e22a6d28fcfa".freeze PATCH_B_SHA256 = "57958271bb802a59452d0816e0670d16c8b70bdf6530bcf6f78726489ad89b90".freeze LINUX_TESTBALL_SHA256 = "fa7fac451a7c37e74f02e2a425a76aff89106098a55707832a02be5af5071cf8".freeze TEST_SHA1 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef".freeze TEST_SHA256 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".freeze
rwhogg/brew
Library/Homebrew/test/support/lib/config.rb
Ruby
bsd-2-clause
2,216
# Copyright (c) 2021, DjaoDjin Inc. # 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. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. __version__ = '0.6.4-dev'
djaodjin/djaodjin-deployutils
deployutils/__init__.py
Python
bsd-2-clause
1,370
// -------------------------------------------------------------------------------- // SharpDisasm (File: SharpDisasm\ud_operand_code.cs) // Copyright (c) 2014-2015 Justin Stenning // http://spazzarama.com // https://github.com/spazzarama/SharpDisasm // https://sharpdisasm.codeplex.com/ // // SharpDisasm is distributed under the 2-clause "Simplified BSD License". // // Portions of SharpDisasm are ported to C# from udis86 a C disassembler project // also distributed under the terms of the 2-clause "Simplified BSD License" and // Copyright (c) 2002-2012, Vivek Thampi <vivek.mt@gmail.com> // All rights reserved. // UDIS86: https://github.com/vmt/udis86 // // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // -------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SharpDisasm.Udis86 { #pragma warning disable 1591 /* operand type constants -- order is important! */ /// <summary> /// Operand codes /// </summary> public enum ud_operand_code { OP_NONE, OP_A, OP_E, OP_M, OP_G, OP_I, OP_F, OP_R0, OP_R1, OP_R2, OP_R3, OP_R4, OP_R5, OP_R6, OP_R7, OP_AL, OP_CL, OP_DL, OP_AX, OP_CX, OP_DX, OP_eAX, OP_eCX, OP_eDX, OP_rAX, OP_rCX, OP_rDX, OP_ES, OP_CS, OP_SS, OP_DS, OP_FS, OP_GS, OP_ST0, OP_ST1, OP_ST2, OP_ST3, OP_ST4, OP_ST5, OP_ST6, OP_ST7, OP_J, OP_S, OP_O, OP_I1, OP_I3, OP_sI, OP_V, OP_W, OP_Q, OP_P, OP_U, OP_N, OP_MU, OP_H, OP_L, OP_R, OP_C, OP_D, OP_MR } #pragma warning restore 1591 }
Raptur/SharpDisasmGUI
SharpDisasm/Udis86/ud_operand_code.cs
C#
bsd-2-clause
3,187
# Copyright 2014 Dev in Cachu authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. from django.conf import settings from django.conf.urls import include, patterns, url from django.views.decorators import csrf from django.views.generic import base from django.contrib import admin admin.autodiscover() from devincachu.destaques import views as dviews from devincachu.inscricao import views as iviews from devincachu.palestras import views as pviews p = patterns urlpatterns = p("", url(r"^admin/", include(admin.site.urls)), url(r"^palestrantes/$", pviews.PalestrantesView.as_view(), name="palestrantes"), url(r"^programacao/$", pviews.ProgramacaoView.as_view(), name="programacao"), url(r"^programacao/(?P<palestrantes>.*)/(?P<slug>[\w-]+)/$", pviews.PalestraView.as_view(), name="palestra"), url(r"^inscricao/$", iviews.Inscricao.as_view(), name="inscricao"), url(r"^notificacao/$", csrf.csrf_exempt(iviews.Notificacao.as_view()), name="notificacao"), url(r"^certificado/validar/$", iviews.ValidacaoCertificado.as_view(), name="validacao_certificado"), url(r"^certificado/$", iviews.BuscarCertificado.as_view(), name="busca_certificado"), url(r"^certificado/(?P<slug>[0-9a-f]+)/$", iviews.Certificado.as_view(), name="certificado"), url(r"^sobre/$", base.TemplateView.as_view( template_name="sobre.html", ), name="sobre-o-evento"), url(r"^quando-e-onde/$", base.TemplateView.as_view( template_name="quando-e-onde.html", ), name="quando-e-onde"), url(r"^$", dviews.IndexView.as_view(), name="index"), ) if settings.DEBUG: urlpatterns += patterns("", url(r"^media/(?P<path>.*)$", "django.views.static.serve", {"document_root": settings.MEDIA_ROOT}), )
devincachu/devincachu-2014
devincachu/urls.py
Python
bsd-2-clause
2,555
# -*- coding: utf-8 -*- class Pkg @pkgDir @jailDir def self.init() @pkgDir = System.getConf("pkgDir") @jailDir = System.getConf("jailDir") end def self.main(data) if (data["control"] == "search") then search(data["name"]).each_line do |pname| pname = pname.chomp SendMsg.machine("pkg","search",pname) end elsif(data["control"] == "list") then pkg = list("all") pkg.each do |pname| SendMsg.machine("pkg","list",pname[0]) end elsif(data["control"] == "install") then cmdLog,cause = install(data["name"]) if(cmdLog == false) SendMsg.status(MACHINE,"failed",cause) return else SendMsg.status(MACHINE,"success","完了しました。") end end end def self.add(jname,pname) puts "pkg-static -j #{jname} add /pkg/#{pname}.txz" s,e = Open3.capture3("pkg-static -j #{jname} add /pkg/#{pname}.txz") end def self.search(pname) #host側でやらせる s,e = Open3.capture3("pkg-static search #{pname}") return s end def self.download(pname) flag = false pkgVal = 0 now = 1 IO.popen("echo y|pkg-static fetch -d #{pname}") do |pipe| pipe.each do | line | # puts line if(line.include?("New packages to be FETCHED:")) then #ダウンロードするパッケージの数を計算(NEw packages〜からThe process〜までの行数) flag = true end if(line.include?("The process will require")) then pkgVal -= 2 flag = false end if(flag == true) then pkgVal += 1 end if(line.include?("Fetching")) then if(line.include?("Proceed with fetching packages? [y/N]: ")) then line.gsub!("Proceed with fetching packages? [y/N]: ","") end SendMsg.status(MACHINE,"log","#{line}(#{now}/#{pkgVal})") now += 1 end end end cmdLog,e = Open3.capture3("ls #{@jailDir}/sharedfs/pkg") s,e = Open3.capture3("cp -pn #{@pkgDir}/* #{@jailDir}/sharedfs/pkg/") #sharedfsにコピー(qjail) cmdLog2,e = Open3.capture3("ls #{@jailDir}/sharedfs/pkg") =begin if(cmdLog == cmdLog2) #ダウンロード前後にlsの結果を取って、要素が同じならばダウンロードに失敗しているとわかる(ファイルが増えていない) puts ("pkgcopyerror") return false,"pkgcopy" end =end end def self.install(pname) #host側でやらせる cmdLog, cause = download(pname) SendMsg.status(MACHINE,"report","pkgdownload") cmdLog,e = Open3.capture3("ls #{@jailDir}/sharedfs/pkg/#{pname}.txz") cmdLog = cmdLog.chomp #改行削除 if(cmdLog != "#{@jailDir}/sharedfs/pkg/#{pname}.txz") return false,"copy" end SendMsg.status(MACHINE,"report","pkgcopy") nextid = SQL.select("pkg","maxid") + 1 SQL.insert("pkg",pname) sqlid = SQL.select("pkg",nextid)[0] #作成したpkgのIDを取得 if (sqlid != nextid ) then #sqlidがnextidではない(恐らくnextid-1)場合は、データベースが正常に作成されていない return false,"database" end return true end def self.list(mode) if (mode == "all") then return SQL.sql("select name from pkg") end end end
shutingrz/gvitocha
bin/pkg.rb
Ruby
bsd-2-clause
3,178
#!/usr/bin/env python #********************************************************************* # Software License Agreement (BSD License) # # Copyright (c) 2011 andrewtron3000 # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of the Willow Garage nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. #********************************************************************/ import roslib; roslib.load_manifest('face_detection') import rospy import sys import cv from cv_bridge import CvBridge from sensor_msgs.msg import Image from geometry_msgs.msg import Point from geometry_msgs.msg import PointStamped # # Instantiate a new opencv to ROS bridge adaptor # cv_bridge = CvBridge() # # Define the callback that will be called when a new image is received. # def callback(publisher, coord_publisher, cascade, imagemsg): # # Convert the ROS imagemsg to an opencv image. # image = cv_bridge.imgmsg_to_cv(imagemsg, 'mono8') # # Blur the image. # cv.Smooth(image, image, cv.CV_GAUSSIAN) # # Allocate some storage for the haar detect operation. # storage = cv.CreateMemStorage(0) # # Call the face detector function. # faces = cv.HaarDetectObjects(image, cascade, storage, 1.2, 2, cv.CV_HAAR_DO_CANNY_PRUNING, (100,100)) # # If faces are detected, compute the centroid of all the faces # combined. # face_centroid_x = 0.0 face_centroid_y = 0.0 if len(faces) > 0: # # For each face, draw a rectangle around it in the image, # and also add the position of the face to the centroid # of all faces combined. # for (i, n) in faces: x = int(i[0]) y = int(i[1]) width = int(i[2]) height = int(i[3]) cv.Rectangle(image, (x, y), (x + width, y + height), cv.CV_RGB(0,255,0), 3, 8, 0) face_centroid_x += float(x) + (float(width) / 2.0) face_centroid_y += float(y) + (float(height) / 2.0) # # Finish computing the face_centroid by dividing by the # number of faces found above. # face_centroid_x /= float(len(faces)) face_centroid_y /= float(len(faces)) # # Lastly, if faces were detected, publish a PointStamped # message that contains the centroid values. # pt = Point(x = face_centroid_x, y = face_centroid_y, z = 0.0) pt_stamped = PointStamped(point = pt) coord_publisher.publish(pt_stamped) # # Convert the opencv image back to a ROS image using the # cv_bridge. # newmsg = cv_bridge.cv_to_imgmsg(image, 'mono8') # # Republish the image. Note this image has boxes around # faces if faces were found. # publisher.publish(newmsg) def listener(publisher, coord_publisher): rospy.init_node('face_detector', anonymous=True) # # Load the haar cascade. Note we get the # filename from the "classifier" parameter # that is configured in the launch script. # cascadeFileName = rospy.get_param("~classifier") cascade = cv.Load(cascadeFileName) rospy.Subscriber("/stereo/left/image_rect", Image, lambda image: callback(publisher, coord_publisher, cascade, image)) rospy.spin() # This is called first. if __name__ == '__main__': publisher = rospy.Publisher('face_view', Image) coord_publisher = rospy.Publisher('face_coords', PointStamped) listener(publisher, coord_publisher)
andrewtron3000/hacdc-ros-pkg
face_detection/src/detector.py
Python
bsd-2-clause
5,077
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import urllib from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from jp.ac.kyoto_su.aokilab.dragon.mvc.model import OpenGLModel from jp.ac.kyoto_su.aokilab.dragon.mvc.view import * from jp.ac.kyoto_su.aokilab.dragon.opengl.triangle import OpenGLTriangle from jp.ac.kyoto_su.aokilab.dragon.opengl.polygon import OpenGLPolygon TRACE = True DEBUG = False class DragonModel(OpenGLModel): """ドラゴンのモデル。""" def __init__(self): """ドラゴンのモデルのコンストラクタ。""" if TRACE: print(__name__), self.__init__.__doc__ super(DragonModel, self).__init__() self._eye_point = [-5.5852450791872 , 3.07847342734 , 15.794105252496] self._sight_point = [0.27455347776413 , 0.20096999406815 , -0.11261999607086] self._up_vector = [0.1018574904194 , 0.98480906061847 , -0.14062775604137] self._fovy = self._default_fovy = 12.642721790235 filename = os.path.join(os.getcwd(), 'dragon.txt') if os.path.exists(filename) and os.path.isfile(filename): pass else: url = 'http://www.cc.kyoto-su.ac.jp/~atsushi/Programs/Dragon/dragon.txt' urllib.urlretrieve(url, filename) with open(filename, "rU") as a_file: while True: a_string = a_file.readline() if len(a_string) == 0: break a_list = a_string.split() if len(a_list) == 0: continue first_string = a_list[0] if first_string == "number_of_vertexes": number_of_vertexes = int(a_list[1]) if first_string == "number_of_triangles": number_of_triangles = int(a_list[1]) if first_string == "end_header": get_tokens = (lambda file: file.readline().split()) collection_of_vertexes = [] for n_th in range(number_of_vertexes): a_list = get_tokens(a_file) a_vertex = map(float, a_list[0:3]) collection_of_vertexes.append(a_vertex) index_to_vertex = (lambda index: collection_of_vertexes[index-1]) for n_th in range(number_of_triangles): a_list = get_tokens(a_file) indexes = map(int, a_list[0:3]) vertexes = map(index_to_vertex, indexes) a_tringle = OpenGLTriangle(*vertexes) self._display_object.append(a_tringle) return def default_window_title(self): """ドラゴンのウィンドウのタイトル(ラベル)を応答する。""" if TRACE: print(__name__), self.default_window_title.__doc__ return "Dragon" class WaspModel(OpenGLModel): """スズメバチのモデル。""" def __init__(self): """スズメバチのモデルのコンストラクタ。""" if TRACE: print(__name__), self.__init__.__doc__ super(WaspModel, self).__init__() self._eye_point = [-5.5852450791872 , 3.07847342734 , 15.794105252496] self._sight_point = [0.19825005531311 , 1.8530999422073 , -0.63795006275177] self._up_vector = [0.070077999093727 , 0.99630606032682 , -0.049631725731267] self._fovy = self._default_fovy = 41.480099231656 filename = os.path.join(os.getcwd(), 'wasp.txt') if os.path.exists(filename) and os.path.isfile(filename): pass else: url = 'http://www.cc.kyoto-su.ac.jp/~atsushi/Programs/Wasp/wasp.txt' urllib.urlretrieve(url, filename) with open(filename, "rU") as a_file: while True: a_string = a_file.readline() if len(a_string) == 0: break a_list = a_string.split() if len(a_list) == 0: continue first_string = a_list[0] if first_string == "number_of_vertexes": number_of_vertexes = int(a_list[1]) if first_string == "number_of_polygons": number_of_polygons = int(a_list[1]) if first_string == "end_header": get_tokens = (lambda file: file.readline().split()) collection_of_vertexes = [] for n_th in range(number_of_vertexes): a_list = get_tokens(a_file) a_vertex = map(float, a_list[0:3]) collection_of_vertexes.append(a_vertex) index_to_vertex = (lambda index: collection_of_vertexes[index-1]) for n_th in range(number_of_polygons): a_list = get_tokens(a_file) number_of_indexes = int(a_list[0]) index = number_of_indexes + 1 indexes = map(int, a_list[1:index]) vertexes = map(index_to_vertex, indexes) rgb_color = map(float, a_list[index:index+3]) a_polygon = OpenGLPolygon(vertexes, rgb_color) self._display_object.append(a_polygon) return def default_view_class(self): """スズメバチのモデルを表示するデフォルトのビューのクラスを応答する。""" if TRACE: print(__name__), self.default_view_class.__doc__ return WaspView def default_window_title(self): """スズメバチのウィンドウのタイトル(ラベル)を応答する。""" if TRACE: print(__name__), self.default_window_title.__doc__ return "Wasp" class BunnyModel(OpenGLModel): """うさぎのモデル。""" def __init__(self): """うさぎのモデルのコンストラクタ。""" if TRACE: print(__name__), self.__init__.__doc__ super(BunnyModel, self).__init__() filename = os.path.join(os.getcwd(), 'bunny.ply') if os.path.exists(filename) and os.path.isfile(filename): pass else: url = 'http://www.cc.kyoto-su.ac.jp/~atsushi/Programs/Bunny/bunny.ply' urllib.urlretrieve(url, filename) with open(filename, "rU") as a_file: while True: a_string = a_file.readline() if len(a_string) == 0: break a_list = a_string.split() if len(a_list) == 0: continue first_string = a_list[0] if first_string == "element": second_string = a_list[1] if second_string == "vertex": number_of_vertexes = int(a_list[2]) if second_string == "face": number_of_faces = int(a_list[2]) if first_string == "end_header": get_tokens = (lambda file: file.readline().split()) collection_of_vertexes = [] for n_th in range(number_of_vertexes): a_list = get_tokens(a_file) a_vertex = map(float, a_list[0:3]) collection_of_vertexes.append(a_vertex) index_to_vertex = (lambda index: collection_of_vertexes[index]) for n_th in range(number_of_faces): a_list = get_tokens(a_file) indexes = map(int, a_list[1:4]) vertexes = map(index_to_vertex, indexes) a_tringle = OpenGLTriangle(*vertexes) self._display_object.append(a_tringle) if first_string == "comment": second_string = a_list[1] if second_string == "eye_point_xyz": self._eye_point = map(float, a_list[2:5]) if second_string == "sight_point_xyz": self._sight_point = map(float, a_list[2:5]) if second_string == "up_vector_xyz": self._up_vector = map(float, a_list[2:5]) if second_string == "zoom_height" and a_list[3] == "fovy": self._fovy = self._default_fovy = float(a_list[4]) return def default_view_class(self): """うさぎのモデルを表示するデフォルトのビューのクラスを応答する。""" if TRACE: print(__name__), self.default_view_class.__doc__ return BunnyView def default_window_title(self): """うさぎのウィンドウのタイトル(ラベル)を応答する。""" if TRACE: print(__name__), self.default_window_title.__doc__ return "Stanford Bunny" # end of file
frederica07/Dragon_Programming_Process
jp/ac/kyoto_su/aokilab/dragon/example_model/example.py
Python
bsd-2-clause
7,196
# Copyright 2015-2017 Rumma & Ko Ltd # License: BSD (see file COPYING for details) from lino.core.roles import UserRole class SimpleContactsUser(UserRole): pass class ContactsUser(SimpleContactsUser): pass class ContactsStaff(ContactsUser): pass
khchine5/xl
lino_xl/lib/contacts/roles.py
Python
bsd-2-clause
269
from django.db.models import Transform from django.db.models import DateTimeField, TimeField from django.utils.functional import cached_property class TimeValue(Transform): lookup_name = 'time' function = 'time' def as_sql(self, compiler, connection): lhs, params = compiler.compile(self.lhs) return 'TIME({})'.format(lhs), params @cached_property def output_field(self): return TimeField() DateTimeField.register_lookup(TimeValue)
mivanov-utwente/t4proj
t4proj/apps/stats/models.py
Python
bsd-2-clause
481
<?php header('Content-Type: text/html; charset=utf-8'); require_once 'Akna.php'; $user = ''; $pass = ''; $akna = new Akna( $user, $pass ); $contacts = $akna->emailMarketing->contacts; $messages = $akna->emailMarketing->messages; $campaigns = $akna->emailMarketing->campaigns; try { // $result_1 = $contacts->get('daniel@apiki.com', 'Apiki 1'); // var_dump($result_1); // $result_2 = $contacts->getLists(); // var_dump($result_2); // $result_3 = $messages->create( array( // 'nome' => 'Teste', // 'html' => htmlspecialchars( '<h1>Curso à distância</h1>' ) // ) ); // var_dump($result_3); // $result_4 = $messages->test( array( // 'titulo' => 'Teste', // 'email_remetente' => 'daniel.antunes.rocha@gmail.com', // 'assunto' => 'Teste de envio 15.07', // 'email' => 'daniel@apiki.com' // ) ); // var_dump($result_4); // $result_5 = $campaigns->addAction( array( // 'nome' => 'Itaú 6', // 'mensagem' => 'Teste', // 'data_encerramento' => '2013-07-30', // 'nome_remetente' => 'CESP - Relações com Investidores', // 'email_remetente' => 'firb.cesp@firb.com', // 'email_retorno' => 'firb.cesp@firb.com', // 'assunto' => 'Assunto 1', // 'lista' => array( 'Apiki 1', 'Apiki 2' ), // 'agendar' => array( 'datahora' => date( 'Y-m-d H:i:s' ) ) // ) ); // var_dump($result_5); } catch( Akna_Exception $e ){ echo $e->getmessage(); }
danielantunes/php-akna
index.php
PHP
bsd-2-clause
1,452
/* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.initialization; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.gradle.api.internal.project.ProjectIdentifier; import org.gradle.api.internal.project.ProjectRegistry; import org.gradle.api.InvalidUserDataException; import java.io.File; import java.io.Serializable; public class ProjectDirectoryProjectSpec extends AbstractProjectSpec implements Serializable { private final File dir; public ProjectDirectoryProjectSpec(File dir) { this.dir = dir; } public String getDisplayName() { return String.format("with project directory '%s'", dir); } public boolean isCorresponding(File file) { return dir.equals(file); } protected String formatNoMatchesMessage() { return String.format("No projects in this build have project directory '%s'.", dir); } protected String formatMultipleMatchesMessage(Iterable<? extends ProjectIdentifier> matches) { return String.format("Multiple projects in this build have project directory '%s': %s", dir, matches); } protected boolean select(ProjectIdentifier project) { return project.getProjectDir().equals(dir); } @Override protected void checkPreconditions(ProjectRegistry<?> registry) { if (!dir.exists()) { throw new InvalidUserDataException(String.format("Project directory '%s' does not exist.", dir)); } if (!dir.isDirectory()) { throw new InvalidUserDataException(String.format("Project directory '%s' is not a directory.", dir)); } } public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } }
tkmnet/RCRS-ADF
gradle/gradle-2.1/src/core/org/gradle/initialization/ProjectDirectoryProjectSpec.java
Java
bsd-2-clause
2,457
// Copyright 2014 David Miller. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sequtil import ( "errors" "github.com/dmiller/go-seq/iseq" "github.com/dmiller/go-seq/murmur3" //"fmt" "math" "reflect" ) // Hash returns a hash code for an object. // Uses iseq.Hashable.Hash if the interface is implemented. // Otherwise, special cases Go numbers and strings. // Returns a default value if not covered by these cases. // Returning a default value is really not good for hashing performance. // But it is one way not to have an error code and to avoid a panic. // Use IsHashable to determine if Hash is supported. // Or call HashE which has an error return. func Hash(v interface{}) uint32 { h, err := HashE(v) if err != nil { return 0 } return h } // HashE returns a hash code for an object. // Uses iseq.Hashable.Hash if the interface is implemented. // It special cases Go numbers and strings. // Returns an error if the object is not covered by these cases. func HashE(v interface{}) (uint32, error) { if h, ok := v.(iseq.Hashable); ok { return h.Hash(), nil } switch v := v.(type) { case bool, int, int8, int32, int64: return murmur3.HashUInt64(uint64(reflect.ValueOf(v).Int())), nil case uint, uint8, uint32, uint64: return murmur3.HashUInt64(uint64(reflect.ValueOf(v).Uint())), nil case float32, float64: return murmur3.HashUInt64(math.Float64bits(reflect.ValueOf(v).Float())), nil case nil: return murmur3.HashUInt64(0), nil case string: return murmur3.HashString(v), nil case complex64, complex128: return HashComplex128(v.(complex128)), nil } return 0, errors.New("don't know how to hash") } // IsHashable returns true if Hash/HashE can compute a hash for this object. func IsHashable(v interface{}) bool { if _, ok := v.(iseq.Hashable); ok { return true } switch v.(type) { case bool, int, int8, int32, int64, uint, uint8, uint32, uint64, float32, float64, nil, string, complex64, complex128: return true } return false } // HashSeq computes a hash for an iseq.Seq func HashSeq(s iseq.Seq) uint32 { return HashOrdered(s) } // HashMap computes a hash for an iseq.PMap func HashMap(m iseq.PMap) uint32 { return HashUnordered(m.Seq()) } // HashOrdered computes a hash for an iseq.Seq, where order is important func HashOrdered(s iseq.Seq) uint32 { n := int32(0) hash := uint32(1) for ; s != nil; s = s.Next() { hash = 31*hash + Hash(s.First) n++ } return murmur3.FinalizeCollHash(hash, n) } // HashUnordered computes a hash for an iseq.Seq, independent of order of elements func HashUnordered(s iseq.Seq) uint32 { n := int32(0) hash := uint32(0) for ; s != nil; s = s.Next() { hash += Hash(s.First) n++ } return murmur3.FinalizeCollHash(hash, n) } // HashComplex128 computes a hash for a complex128 func HashComplex128(c complex128) uint32 { hash := murmur3.MixHash( murmur3.HashUInt64(math.Float64bits(real(c))), murmur3.HashUInt64(math.Float64bits(imag(c)))) return murmur3.Finalize(hash, 2) }
dmiller/go-seq
sequtil/hash.go
GO
bsd-2-clause
3,082