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
package io.ray.streaming.runtime.core.processor; import io.ray.streaming.message.Record; import io.ray.streaming.operator.SourceOperator; /** * The processor for the stream sources, containing a SourceOperator. * * @param <T> The type of source data. */ public class SourceProcessor<T> extends StreamProcessor<Record, SourceOperator<T>> { public SourceProcessor(SourceOperator<T> operator) { super(operator); } @Override public void process(Record record) { throw new UnsupportedOperationException("SourceProcessor should not process record"); } public void fetch() { operator.fetch(); } @Override public void close() {} }
pcmoritz/ray-1
streaming/java/streaming-runtime/src/main/java/io/ray/streaming/runtime/core/processor/SourceProcessor.java
Java
apache-2.0
663
<div class="row"> <div class="col-md-12 no-padding"> <div class="col-lg-4 col-md-12"> <?php $this->renderPartial('pod/description',array( "project" => $project, "tags" => $tags, "countries" => $countries,"isAdmin"=> $admin)); ?> </div> <div class ="col-lg-4 col-md-12"> <?php $this->renderPartial('../pod/sliderPhoto', array("itemId" => (string)$project["_id"], "type" => PHType::TYPE_PROJECTS, "isAdmin"=> $admin)); ?> </div> <div class ="col-lg-4 col-md-12"> <?php $this->renderPartial('pod/contributors',array( "contributors" => $contributors, "organizationTypes" => $organizationTypes, "project" => $project, "admin" => $admin)); ?> </div> </div> <?php if (!empty($tasks) OR $admin==true){ ?> <div class ="col-lg-8 col-md-8 timesheetphp"> </div> <?php } if (!empty($properties) OR $admin==true){ ?> <div class ="col-lg-4 col-md-12"> <?php $this->renderPartial('pod/projectChart',array("itemId" => (string)$project["_id"], "properties" => $properties, "admin" =>$admin)); ?> </div> <?php } ?> <div class="col-sm-6 col-xs-12 roomsPod"> <div class="panel panel-white pulsate"> <div class="panel-heading border-light "> <h4 class="panel-title"> <i class='fa fa-cog fa-spin fa-2x icon-big text-center'></i> Loading Rooms Section</h4> <div class="space5"></div> </div> </div> </div> <div class="col-sm-6 col-xs-12 needsPod"> <!--<div class="panel panel-white pulsate"> <div class="panel-heading border-light "> <h4 class="panel-title"> <i class='fa fa-cog fa-spin fa-2x icon-big text-center'></i> Loading Something Section</h4> <div class="space5"></div> </div> </div>--> </div> <div class="col-sm-6 col-xs-12"> <?php $this->renderPartial('../pod/eventsList',array( "events" => $events, "contextId" => (String) $project["_id"], "contextType" => Project::CONTROLLER, "authorised" => $admin )); ?> </div> </div> <?php $this->renderPartial('/sig/generic/mapLibs'); ?> <script type="text/javascript"> var contextMap = {}; contextMap["project"] = <?php echo json_encode($project)?>; //contextMap["events"] = <?php //echo json_encode($events) ?>; var idToSend = contextMap["project"]["_id"]["$id"] contextMap["people"] = <?php echo json_encode($people) ?>; contextMap["organizations"] = <?php echo json_encode($organizations) ?>; var images = <?php echo json_encode($images) ?>; var contentKeyBase = "<?php echo $contentKeyBase ?>"; jQuery(document).ready(function() { bindBtnFollow(); getAjax(".roomsPod",baseUrl+"/"+moduleId+"/rooms/index/type/<?php echo Project::COLLECTION ?>/id/<?php echo $_GET["id"]?>",null,"html"); getAjax(".timesheetphp",baseUrl+"/"+moduleId+"/gantt/index/type/<?php echo Project::COLLECTION ?>/id/<?php echo $_GET["id"]?>/isAdmin/<?php echo $admin?>",null,"html"); getAjax(".needsPod",baseUrl+"/"+moduleId+"/needs/index/type/<?php echo Project::COLLECTION ?>/id/<?php echo $_GET["id"]?>/isAdmin/<?php echo $admin?>",null,"html"); }) function bindBtnFollow(){ $(".disconnectBtn").off().on("click",function () { $(this).empty(); $(this).html('<i class=" disconnectBtnIcon fa fa-spinner fa-spin"></i>'); var btnClick = $(this); var idToDisconnect = $(this).data("id"); var typeToDisconnect = $(this).data("type"); var ownerLink = $(this).data("ownerlink"); var urlToSend = baseUrl+"/"+moduleId+"/person/disconnect/id/"+idToDisconnect+"/type/"+typeToDisconnect+"/ownerLink/"+ownerLink; if("undefined" != typeof $(this).data("targetlink")){ var targetLink = $(this).data("targetlink"); urlToSend += "/targetLink/"+targetLink; } bootbox.confirm("Are you sure you want to delete <span class='text-red'>"+$(this).data("name")+"</span> connection ?", function(result) { if (!result) { btnClick.empty(); btnClick.html('<i class=" disconnectBtnIcon fa fa-unlink"></i>'); return; } $.ajax({ type: "POST", url: urlToSend, dataType : "json" }) .done(function (data) { if ( data && data.result ) { toastr.info("LINK DIVORCED SUCCESFULLY!!"); $("#"+typeToDisconnect+idToDisconnect).remove(); $("#linkBtns").empty(); $("#linkBtns").html("<a href='javascript:;' class='connectBtn tooltips ' id='addAttendingRelation' data-placement='top' data-ownerlink='"+ownerLink+"' data-original-title='I contribute to this event' ><i class=' connectBtnIcon fa fa-link '></i>CONTRIBUTE</a></li>"); bindBtnFollow(); } else { toastr.info("something went wrong!! please try again."); $(".disconnectBtn").removeClass("fa-spinner fa-spin").addClass("fa-link"); } }); }); }); $(".connectBtn").off().on("click",function () { $(".connectBtnIcon").removeClass("fa-link").addClass("fa-spinner fa-spin"); var idConnect = "<?php echo (string)$project['_id'] ?>"; var ownerLink = $(this).data("ownerlink"); var urlToSend = baseUrl+"/"+moduleId+"/person/follows/id/"+idConnect+"/type/<?php echo Project::COLLECTION ?>/ownerLink/"+ownerLink; if("undefined" != typeof $(this).data("targetlink")){ var targetLink = $(this).data("targetlink"); urlToSend += "/targetLink/"+targetLink; } $.ajax({ type: "POST", url: urlToSend, dataType : "json" }) .done(function (data) { if ( data && data.result ) { toastr.info("REALTION APPLIED SUCCESFULLY!! "); $(".connectBtn").fadeOut(); $("#linkBtns").empty(); $("#linkBtns").html("<a href='javascript:;' class='disconnectBtn text-red tooltips' data-name='"+contextMap["project"]["name"]+" 'data-id='"+contextMap["project"]["_id"]["$id"]+"' data-type='<?php echo Project::COLLECTION ?>' data-ownerlink='"+ownerLink+"' data-placement='top' data-original-title='I no more contributing' ><i class='disconnectBtnIcon fa fa-unlink'></i>UNCONTRIBUTE</a>") bindBtnFollow(); } else { toastr.info("something went wrong!! please try again."); $(".connectBtnIcon").removeClass("fa-spinner fa-spin").addClass("fa-link"); } }); }); } </script>
pixelhumain/network
views/project/dashboard.php
PHP
apache-2.0
6,465
/* * Copyright (c) 2010-2013 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.common.policy; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.apache.commons.lang.Validate; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.LimitationsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordLifeTimeType; import com.evolveum.midpoint.xml.ns._public.common.common_3.StringLimitType; import com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; /** * * @author mamut * */ public class PasswordPolicyUtils { private static final transient Trace LOGGER = TraceManager.getTrace(PasswordPolicyUtils.class); private static final String DOT_CLASS = PasswordPolicyUtils.class.getName() + "."; private static final String OPERATION_PASSWORD_VALIDATION = DOT_CLASS + "passwordValidation"; /** * add defined default values * * @param pp * @return */ public static void normalize(ValuePolicyType pp) { if (null == pp) { throw new IllegalArgumentException("Password policy cannot be null"); } if (null == pp.getStringPolicy()) { StringPolicyType sp = new StringPolicyType(); pp.setStringPolicy(StringPolicyUtils.normalize(sp)); } else { pp.setStringPolicy(StringPolicyUtils.normalize(pp.getStringPolicy())); } if (null == pp.getLifetime()) { PasswordLifeTimeType lt = new PasswordLifeTimeType(); lt.setExpiration(-1); lt.setWarnBeforeExpiration(0); lt.setLockAfterExpiration(0); lt.setMinPasswordAge(0); lt.setPasswordHistoryLength(0); } return; } /** * Check provided password against provided policy * * @param password * - password to check * @param policies * - Password List of policies used to check * @param result * - Operation result of password validator. * @return true if password meet all criteria , false if any criteria is not * met */ public static boolean validatePassword(String password, List <ValuePolicyType> policies, OperationResult result) { boolean ret=true; //iterate through policies for (ValuePolicyType pp: policies) { OperationResult op = validatePassword(password, pp); result.addSubresult(op); //if one fail then result is failure if (ret == true && ! op.isSuccess()) { ret = false; } } return ret; } public static boolean validatePassword(String password, List<PrismObject<ValuePolicyType>> policies) { boolean ret=true; //iterate through policies for (PrismObject<ValuePolicyType> pp: policies) { OperationResult op = validatePassword(password, pp.asObjectable()); // result.addSubresult(op); //if one fail then result is failure if (ret == true && ! op.isSuccess()) { ret = false; } } return ret; } public static boolean validatePassword(ProtectedStringType password, List<PrismObject<ValuePolicyType>> policies) { boolean ret=true; //iterate through policies for (PrismObject<ValuePolicyType> pp: policies) { OperationResult op = validatePassword(password.getClearValue(), pp.asObjectable()); // result.addSubresult(op); //if one fail then result is failure if (ret == true && ! op.isSuccess()) { ret = false; } } return ret; } /** * Check provided password against provided policy * * @param password * - password to check * @param pp * - Password policy used to check * @param result * - Operation result of password validator. * @return true if password meet all criteria , false if any criteria is not * met */ public static boolean validatePassword(String password, ValuePolicyType pp, OperationResult result) { OperationResult op = validatePassword(password, pp); result.addSubresult(op); return op.isSuccess(); } /** * Check provided password against provided policy * * @param password * - password to check * @param pp * - Password policy used * @return - Operation result of this validation */ public static OperationResult validatePassword(String password, ValuePolicyType pp) { // check input params // if (null == pp) { // throw new IllegalArgumentException("No policy provided: NULL"); // } // // if (null == password) { // throw new IllegalArgumentException("Password for validaiton is null."); // } Validate.notNull(pp, "Password policy must not be null."); Validate.notNull(password, "Password to validate must not be null."); OperationResult ret = new OperationResult(OPERATION_PASSWORD_VALIDATION); ret.addParam("policyName", pp.getName()); normalize(pp); LimitationsType lims = pp.getStringPolicy().getLimitations(); StringBuilder message = new StringBuilder(); // Test minimal length if (lims.getMinLength() == null){ lims.setMinLength(0); } if (lims.getMinLength() > password.length()) { String msg = "Required minimal size (" + lims.getMinLength() + ") of password is not met (password length: " + password.length() + ")"; ret.addSubresult(new OperationResult("Check global minimal length", OperationResultStatus.FATAL_ERROR, msg)); message.append(msg); message.append("\n"); } // else { // ret.addSubresult(new OperationResult("Check global minimal length. Minimal length of password OK.", // OperationResultStatus.SUCCESS, "PASSED")); // } // Test maximal length if (lims.getMaxLength() != null) { if (lims.getMaxLength() < password.length()) { String msg = "Required maximal size (" + lims.getMaxLength() + ") of password was exceeded (password length: " + password.length() + ")."; ret.addSubresult(new OperationResult("Check global maximal length", OperationResultStatus.FATAL_ERROR, msg)); message.append(msg); message.append("\n"); } // else { // ret.addSubresult(new OperationResult("Check global maximal length. Maximal length of password OK.", // OperationResultStatus.SUCCESS, "PASSED")); // } } // Test uniqueness criteria HashSet<String> tmp = new HashSet<String>(StringPolicyUtils.stringTokenizer(password)); if (lims.getMinUniqueChars() != null) { if (lims.getMinUniqueChars() > tmp.size()) { String msg = "Required minimal count of unique characters (" + lims.getMinUniqueChars() + ") in password are not met (unique characters in password " + tmp.size() + ")"; ret.addSubresult(new OperationResult("Check minimal count of unique chars", OperationResultStatus.FATAL_ERROR, msg)); message.append(msg); message.append("\n"); } // else { // ret.addSubresult(new OperationResult( // "Check minimal count of unique chars. Password satisfies minimal required unique characters.", // OperationResultStatus.SUCCESS, "PASSED")); // } } // check limitation HashSet<String> allValidChars = new HashSet<String>(128); ArrayList<String> validChars = null; ArrayList<String> passwd = StringPolicyUtils.stringTokenizer(password); if (lims.getLimit() == null || lims.getLimit().isEmpty()){ if (message.toString() == null || message.toString().isEmpty()){ ret.computeStatus(); } else { ret.computeStatus(message.toString()); } return ret; } for (StringLimitType l : lims.getLimit()) { OperationResult limitResult = new OperationResult("Tested limitation: " + l.getDescription()); if (null != l.getCharacterClass().getValue()) { validChars = StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue()); } else { validChars = StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass(pp .getStringPolicy().getCharacterClass(), l.getCharacterClass().getRef())); } // memorize validChars allValidChars.addAll(validChars); // Count how many character for this limitation are there int count = 0; for (String s : passwd) { if (validChars.contains(s)) { count++; } } // Test minimal occurrence if (l.getMinOccurs() == null){ l.setMinOccurs(0); } if (l.getMinOccurs() > count) { String msg = "Required minimal occurrence (" + l.getMinOccurs() + ") of characters ("+l.getDescription()+") in password is not met (occurrence of characters in password " + count + ")."; limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters", OperationResultStatus.FATAL_ERROR, msg)); message.append(msg); message.append("\n"); } // else { // limitResult.addSubresult(new OperationResult("Check minimal occurrence of characters in password OK.", // OperationResultStatus.SUCCESS, "PASSED")); // } // Test maximal occurrence if (l.getMaxOccurs() != null) { if (l.getMaxOccurs() < count) { String msg = "Required maximal occurrence (" + l.getMaxOccurs() + ") of characters ("+l.getDescription()+") in password was exceeded (occurrence of characters in password " + count + ")."; limitResult.addSubresult(new OperationResult("Check maximal occurrence of characters", OperationResultStatus.FATAL_ERROR, msg)); message.append(msg); message.append("\n"); } // else { // limitResult.addSubresult(new OperationResult( // "Check maximal occurrence of characters in password OK.", OperationResultStatus.SUCCESS, // "PASSED")); // } } // test if first character is valid if (l.isMustBeFirst() == null){ l.setMustBeFirst(false); } if (l.isMustBeFirst() && !validChars.contains(password.substring(0, 1))) { String msg = "First character is not from allowed set. Allowed set: " + validChars.toString(); limitResult.addSubresult(new OperationResult("Check valid first char", OperationResultStatus.FATAL_ERROR, msg)); message.append(msg); message.append("\n"); } // else { // limitResult.addSubresult(new OperationResult("Check valid first char in password OK.", // OperationResultStatus.SUCCESS, "PASSED")); // } limitResult.computeStatus(); ret.addSubresult(limitResult); } // Check if there is no invalid character StringBuilder sb = new StringBuilder(); for (String s : passwd) { if (!allValidChars.contains(s)) { // memorize all invalid characters sb.append(s); } } if (sb.length() > 0) { String msg = "Characters [ " + sb + " ] are not allowed to be use in password"; ret.addSubresult(new OperationResult("Check if password does not contain invalid characters", OperationResultStatus.FATAL_ERROR, msg)); message.append(msg); message.append("\n"); } // else { // ret.addSubresult(new OperationResult("Check if password does not contain invalid characters OK.", // OperationResultStatus.SUCCESS, "PASSED")); // } if (message.toString() == null || message.toString().isEmpty()){ ret.computeStatus(); } else { ret.computeStatus(message.toString()); } return ret; } }
sabriarabacioglu/engerek
infra/common/src/main/java/com/evolveum/midpoint/common/policy/PasswordPolicyUtils.java
Java
apache-2.0
12,321
# frozen_string_literal: true require 'rails_helper' RSpec.describe Manifest, type: :model do let(:monograph) do create(:public_monograph) do |m| m.ordered_members << file_set m.save! m end end let(:file_set) do create(:public_file_set) do |f| f.original_file = original_file f.save! f end end let(:original_file) do Hydra::PCDM::File.new do |f| f.content = File.open(File.join(fixture_path, 'kitty.tif')) f.original_name = 'kitty.tif' f.mime_type = 'image/tiff' f.file_size = File.size(File.join(fixture_path, 'kitty.tif')) f.width = 200 f.height = 150 end end let(:current_user) { create(:platform_admin) } # NOTE: #create is dependent on Carrierwave and was not tested. before do allow($stdout).to receive(:puts) # Don't print status messages during specs end it 'no csv file' do implicit = described_class.from_monograph(monograph.id) expect(implicit.id).to eq monograph.id expect(implicit.persisted?).to be false expect(implicit.filename).to be nil explicit = described_class.from_monograph_manifest(monograph.id) expect(explicit.id).to eq monograph.id expect(explicit.persisted?).to be false expect(explicit.filename).to be nil expect(implicit == explicit).to be false end it 'csv file' do implicit = described_class.from_monograph(monograph.id) file_dir = implicit.csv.store_dir FileUtils.mkdir_p(file_dir) unless Dir.exist?(file_dir) FileUtils.rm_rf(Dir.glob("#{file_dir}/*")) file_name = "#{monograph.id}.csv" file_path = File.join(file_dir, file_name) file = File.new(file_path, "w") exporter = Export::Exporter.new(monograph.id) file.write(exporter.export) file.close expect(implicit.persisted?).to be true expect(implicit.filename).to eq file_name explicit = described_class.from_monograph_manifest(monograph.id) expect(explicit.persisted?).to be true expect(explicit.filename).to eq file_name expect(implicit == explicit).to be true expect(explicit.table_rows.count).to eq 2 expect(explicit.table_rows[0].count).to eq 4 expect(explicit.table_rows[0][3]["title"].first).to eq monograph.title.first explicit.table_rows[0][3]["title"] = ["NEW TITLE"] expect(implicit == explicit).to be false explicit.destroy(current_user) expect(implicit.id).to eq monograph.id expect(implicit.persisted?).to be false expect(implicit.filename).to be nil expect(explicit.id).to eq monograph.id expect(explicit.persisted?).to be false expect(explicit.filename).to be nil end end
mlibrary/heliotrope
spec/models/manifest_spec.rb
Ruby
apache-2.0
2,666
/* Copyright 2018 The TensorFlow Authors. 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. =======================================================================*/ // This class has been generated, DO NOT EDIT! package org.tensorflow.op.linalg; import java.util.Arrays; import org.tensorflow.GraphOperation; import org.tensorflow.Operand; import org.tensorflow.Operation; import org.tensorflow.OperationBuilder; import org.tensorflow.Output; import org.tensorflow.op.RawOp; import org.tensorflow.op.RawOpInputs; import org.tensorflow.op.Scope; import org.tensorflow.op.annotation.Endpoint; import org.tensorflow.op.annotation.OpInputsMetadata; import org.tensorflow.op.annotation.OpMetadata; import org.tensorflow.op.annotation.Operator; import org.tensorflow.proto.framework.DataType; import org.tensorflow.types.TInt32; import org.tensorflow.types.family.TType; /** * Returns the batched diagonal part of a batched tensor. * Returns a tensor with the {@code k[0]}-th to {@code k[1]}-th diagonals of the batched * {@code input}. * <p>Assume {@code input} has {@code r} dimensions {@code [I, J, ..., L, M, N]}. * Let {@code max_diag_len} be the maximum length among all diagonals to be extracted, * {@code max_diag_len = min(M + min(k[1], 0), N + min(-k[0], 0))} * Let {@code num_diags} be the number of diagonals to extract, * {@code num_diags = k[1] - k[0] + 1}. * <p>If {@code num_diags == 1}, the output tensor is of rank {@code r - 1} with shape * {@code [I, J, ..., L, max_diag_len]} and values: * <pre> * diagonal[i, j, ..., l, n] * = input[i, j, ..., l, n+y, n+x] ; if 0 &lt;= n+y &lt; M and 0 &lt;= n+x &lt; N, * padding_value ; otherwise. * </pre> * <p>where {@code y = max(-k[1], 0)}, {@code x = max(k[1], 0)}. * <p>Otherwise, the output tensor has rank {@code r} with dimensions * {@code [I, J, ..., L, num_diags, max_diag_len]} with values: * <pre> * diagonal[i, j, ..., l, m, n] * = input[i, j, ..., l, n+y, n+x] ; if 0 &lt;= n+y &lt; M and 0 &lt;= n+x &lt; N, * padding_value ; otherwise. * </pre> * <p>where {@code d = k[1] - m}, {@code y = max(-d, 0)}, and {@code x = max(d, 0)}. * <p>The input must be at least a matrix. * <p>For example: * <pre> * input = np.array([[[1, 2, 3, 4], # Input shape: (2, 3, 4) * [5, 6, 7, 8], * [9, 8, 7, 6]], * [[5, 4, 3, 2], * [1, 2, 3, 4], * [5, 6, 7, 8]]]) * * # A main diagonal from each batch. * tf.matrix_diag_part(input) ==&gt; [[1, 6, 7], # Output shape: (2, 3) * [5, 2, 7]] * * # A superdiagonal from each batch. * tf.matrix_diag_part(input, k = 1) * ==&gt; [[2, 7, 6], # Output shape: (2, 3) * [4, 3, 8]] * * # A tridiagonal band from each batch. * tf.matrix_diag_part(input, k = (-1, 1)) * ==&gt; [[[2, 7, 6], # Output shape: (2, 3, 3) * [1, 6, 7], * [5, 8, 0]], * [[4, 3, 8], * [5, 2, 7], * [1, 6, 0]]] * * # Padding value = 9 * tf.matrix_diag_part(input, k = (1, 3), padding_value = 9) * ==&gt; [[[4, 9, 9], # Output shape: (2, 3, 3) * [3, 8, 9], * [2, 7, 6]], * [[2, 9, 9], * [3, 4, 9], * [4, 3, 8]]] * </pre> * * @param <T> data type for {@code diagonal} output */ @OpMetadata( opType = MatrixDiagPart.OP_NAME, inputsClass = MatrixDiagPart.Inputs.class ) @Operator( group = "linalg" ) public final class MatrixDiagPart<T extends TType> extends RawOp implements Operand<T> { /** * The name of this op, as known by TensorFlow core engine */ public static final String OP_NAME = "MatrixDiagPartV2"; private Output<T> diagonal; public MatrixDiagPart(Operation operation) { super(operation, OP_NAME); int outputIdx = 0; diagonal = operation.output(outputIdx++); } /** * Factory method to create a class wrapping a new MatrixDiagPartV2 operation. * * @param scope current scope * @param input Rank {@code r} tensor where {@code r >= 2}. * @param k Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main * diagonal, and negative value means subdiagonals. {@code k} can be a single integer * (for a single diagonal) or a pair of integers specifying the low and high ends * of a matrix band. {@code k[0]} must not be larger than {@code k[1]}. * @param paddingValue The value to fill the area outside the specified diagonal band with. * Default is 0. * @param <T> data type for {@code MatrixDiagPartV2} output and operands * @return a new instance of MatrixDiagPart */ @Endpoint( describeByClass = true ) public static <T extends TType> MatrixDiagPart<T> create(Scope scope, Operand<T> input, Operand<TInt32> k, Operand<T> paddingValue) { OperationBuilder opBuilder = scope.opBuilder(OP_NAME, "MatrixDiagPart"); opBuilder.addInput(input.asOutput()); opBuilder.addInput(k.asOutput()); opBuilder.addInput(paddingValue.asOutput()); return new MatrixDiagPart<>(opBuilder.build()); } /** * Gets diagonal. * The extracted diagonal(s). * @return diagonal. */ public Output<T> diagonal() { return diagonal; } @Override public Output<T> asOutput() { return diagonal; } @OpInputsMetadata( outputsClass = MatrixDiagPart.class ) public static class Inputs<T extends TType> extends RawOpInputs<MatrixDiagPart<T>> { /** * Rank {@code r} tensor where {@code r >= 2}. */ public final Operand<T> input; /** * Diagonal offset(s). Positive value means superdiagonal, 0 refers to the main * diagonal, and negative value means subdiagonals. {@code k} can be a single integer * (for a single diagonal) or a pair of integers specifying the low and high ends * of a matrix band. {@code k[0]} must not be larger than {@code k[1]}. */ public final Operand<TInt32> k; /** * The value to fill the area outside the specified diagonal band with. * Default is 0. */ public final Operand<T> paddingValue; /** * The T attribute */ public final DataType T; public Inputs(GraphOperation op) { super(new MatrixDiagPart<>(op), op, Arrays.asList("T")); int inputIndex = 0; input = (Operand<T>) op.input(inputIndex++); k = (Operand<TInt32>) op.input(inputIndex++); paddingValue = (Operand<T>) op.input(inputIndex++); T = op.attributes().getAttrType("T"); } } }
tensorflow/java
tensorflow-core/tensorflow-core-api/src/gen/java/org/tensorflow/op/linalg/MatrixDiagPart.java
Java
apache-2.0
7,043
package com.qinyadan.monitor.network.util; import java.util.Map; import com.qinyadan.monitor.network.control.ControlMessageDecoder; import com.qinyadan.monitor.network.control.ControlMessageEncoder; import com.qinyadan.monitor.network.control.ProtocolException; public final class ControlMessageEncodingUtils { private static final ControlMessageEncoder encoder = new ControlMessageEncoder(); private static final ControlMessageDecoder decoder = new ControlMessageDecoder(); private ControlMessageEncodingUtils() { } public static byte[] encode(Map<String, Object> value) throws ProtocolException { return encoder.encode(value); } public static Object decode(byte[] in) throws ProtocolException { return decoder.decode(in); } }
O2O-Market/Market-monitor
market-network/src/main/java/com/qinyadan/monitor/network/util/ControlMessageEncodingUtils.java
Java
apache-2.0
809
var Alloy = require("alloy"), _ = Alloy._, Backbone = Alloy.Backbone; Alloy.Globals.steps = 0; Alloy.Globals.capacity = 0; Alloy.Globals.basketImage = ""; Alloy.Globals.fruitCount = 0; Alloy.createController("index");
jhenziz/Fruit-Basket
Resources/app.js
JavaScript
apache-2.0
222
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.refactoring.typeCook.deductive.util; import com.intellij.psi.*; import com.intellij.refactoring.typeCook.Settings; import com.intellij.refactoring.typeCook.Util; import java.util.HashSet; /** * @author db */ public class VictimCollector extends Visitor { final HashSet<PsiElement> myVictims = new HashSet<PsiElement>(); final PsiElement[] myElements; final Settings mySettings; public VictimCollector(final PsiElement[] elements, final Settings settings) { myElements = elements; mySettings = settings; } private void testNAdd(final PsiElement element, final PsiType t) { if (Util.isRaw(t, mySettings)) { if (element instanceof PsiNewExpression && t.getCanonicalText().equals("java.lang.Object")){ return; } myVictims.add(element); } } @Override public void visitLocalVariable(final PsiLocalVariable variable) { testNAdd(variable, variable.getType()); super.visitLocalVariable(variable); } @Override public void visitForeachStatement(final PsiForeachStatement statement) { super.visitForeachStatement(statement); final PsiParameter parameter = statement.getIterationParameter(); testNAdd(parameter, parameter.getType()); } @Override public void visitField(final PsiField field) { testNAdd(field, field.getType()); super.visitField(field); } @Override public void visitMethod(final PsiMethod method) { final PsiParameter[] parms = method.getParameterList().getParameters(); for (PsiParameter parm : parms) { testNAdd(parm, parm.getType()); } if (Util.isRaw(method.getReturnType(), mySettings)) { myVictims.add(method); } final PsiCodeBlock body = method.getBody(); if (body != null) { body.accept(this); } } @Override public void visitNewExpression(final PsiNewExpression expression) { if (expression.getClassReference() != null) { testNAdd(expression, expression.getType()); } super.visitNewExpression(expression); } @Override public void visitTypeCastExpression (final PsiTypeCastExpression cast){ final PsiTypeElement typeElement = cast.getCastType(); if (typeElement != null) { testNAdd(cast, typeElement.getType()); } super.visitTypeCastExpression(cast); } @Override public void visitReferenceExpression(final PsiReferenceExpression expression) { } @Override public void visitFile(PsiFile file) { if (file instanceof PsiJavaFile) { super.visitFile(file); } } public HashSet<PsiElement> getVictims() { for (PsiElement element : myElements) { element.accept(this); } return myVictims; } }
joewalnes/idea-community
java/java-impl/src/com/intellij/refactoring/typeCook/deductive/util/VictimCollector.java
Java
apache-2.0
3,283
// Generated from /POI/java/org/apache/poi/hssf/usermodel/HSSFName.java #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <org/apache/poi/hssf/record/fwd-POI.hpp> #include <org/apache/poi/hssf/usermodel/fwd-POI.hpp> #include <org/apache/poi/ss/formula/ptg/fwd-POI.hpp> #include <java/lang/Object.hpp> #include <org/apache/poi/ss/usermodel/Name.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace poi { namespace ss { namespace formula { namespace ptg { typedef ::SubArray< ::poi::ss::formula::ptg::Ptg, ::java::lang::ObjectArray > PtgArray; } // ptg } // formula } // ss } // poi struct default_init_tag; class poi::hssf::usermodel::HSSFName final : public virtual ::java::lang::Object , public ::poi::ss::usermodel::Name { public: typedef ::java::lang::Object super; private: HSSFWorkbook* _book { }; ::poi::hssf::record::NameRecord* _definedNameRec { }; ::poi::hssf::record::NameCommentRecord* _commentRec { }; protected: void ctor(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name); void ctor(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name, ::poi::hssf::record::NameCommentRecord* comment); public: ::java::lang::String* getSheetName() override; ::java::lang::String* getNameName() override; void setNameName(::java::lang::String* nameName) override; private: static void validateName(::java::lang::String* name); public: void setRefersToFormula(::java::lang::String* formulaText) override; ::java::lang::String* getRefersToFormula() override; public: /* package */ void setNameDefinition(::poi::ss::formula::ptg::PtgArray* ptgs); public: bool isDeleted() override; bool isFunctionName() override; ::java::lang::String* toString() override; void setSheetIndex(int32_t index) override; int32_t getSheetIndex() override; ::java::lang::String* getComment() override; void setComment(::java::lang::String* comment) override; void setFunction(bool value) override; // Generated public: /* package */ HSSFName(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name); HSSFName(HSSFWorkbook* book, ::poi::hssf::record::NameRecord* name, ::poi::hssf::record::NameCommentRecord* comment); protected: HSSFName(const ::default_init_tag&); public: static ::java::lang::Class *class_(); private: virtual ::java::lang::Class* getClass0(); };
pebble2015/cpoi
src/org/apache/poi/hssf/usermodel/HSSFName.hpp
C++
apache-2.0
2,520
Ext.namespace("Ext.haode"); Ext.haode.Control = function(args){ Ext.apply(this, args); this.init(); }; Ext.haode.Control.prototype = { userName : '', version : '', app_name : '', copyright : '', viewport : null, cn : 1, init : function() { this.viewport = this.getViewport(); }, getViewport : function() { var viewport; if (this.viewport) { viewport = this.viewport; } else { var centerPanel = this.getCenterPanel(); viewport = new Ext.Viewport({ layout: 'fit', items: [centerPanel] }); } return viewport; }, getCenterPanel : function() { var panel; if (this.viewport) { panel = this.getViewport().items[0]; } else { var n = new Ext.Button({ id : 'tsb', text : '发放任务', align : 'right', width : 80, menu : [{ text : '常规任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', timeout : 1000000, url : 'task.do?action=normal', method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } // }, { // text : '个别任务', // handler : function() { // if (!Ext.getCmp('form').getForm().isValid()) { // alert('请正确填写表单'); // return; // } // // var sm = new Ext.grid.CheckboxSelectionModel(); // var store1 = new Ext.data.Store({ // proxy : new Ext.data.HttpProxy({ // url : 'customerManager.do?action=queryAll' // }), // reader : new Ext.data.JsonReader({ // root : 'rows', // totalProperty : 'total', // id : 'id', // fields : ['id', 'name', 'username'] // }) // }); // // var paging = new Ext.PagingToolbar({ // pageSize : 20, // store : store1, // displayInfo : true, // displayMsg : '当前显示数据 {0} - {1} of {2}', // emptyMsg : '没有数据' // }); // // var win = new Ext.Window({ // title : '客户经理', // id : 'bind', // layout : 'fit', // border : false, // modal : true, // width : 500, // height : 400, // items : [new Ext.grid.GridPanel({ // id : 'grid1', // loadMask : true, //// tbar : [{ //// xtype : 'textfield', //// id : 'searchName', //// emptyText : '请输入客户经理名称...', //// width : 150 //// }, { //// text : '搜索', //// width : 45, //// xtype : 'button', //// handler : function() { //// //// } //// }], // store : store1, // sm : sm, // cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { // header : '客户经理名称', // width : 200, // dataIndex : 'name', // align : 'center' // }, { // header : '客户经理用户名', // width : 230, // dataIndex : 'username', // align : 'center' // }]), // bbar : paging // })], // buttons : [{ // text : '确定', // handler : function() { // var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); // if (mrecords.length < 1) { // alert('请选择要做任务的客户经理!'); // return; // } // var mids = ''; // for (var j = 0; j < mrecords.length; j++) { // mids += ',' + mrecords[j].get('id'); // } // // Ext.getCmp('bind').close(); // Ext.getCmp('form').getForm().submit({ // waitTitle : '提示', // waitMsg : '正在提交数据请稍后...', // url : 'task.do?action=indevi', // params : { // mids : mids // }, // method : 'post', // success : function(form, action) { // alert(action.result.myHashMap.msg); // }, // failure : function(form, action) { // alert(action.result.myHashMap.msg); // } // }); // // } // }, { // text : '取消', // handler : function() { // Ext.getCmp('bind').close(); // } // }] // }); // win.show(Ext.getBody()); // store1.load({ // params : { // start : 0, // limit : 20 // } // }); // // } }, { text : '分组任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var sm = new Ext.grid.CheckboxSelectionModel(); var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customerGroup.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var win = new Ext.Window({ title : '客户分组', id : 'bind', layout : 'fit', border : false, modal : true, width : 500, height : 400, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户分组名称', width : 200, dataIndex : 'name', align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var grecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (grecords.length < 1) { alert('请选择客户分组!'); return; } var gids = ''; for (var j = 0; j < grecords.length; j++) { gids += ',' + grecords[j].get('id'); } Ext.getCmp('bind').close(); Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=group', params : { gids : gids }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } }, { text : '取消', handler : function() { Ext.getCmp('bind').close(); } }] }); win.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20, all : 0 } }); } }, { text : '客户任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customer.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager', 'backup_number', 'address', 'order_type', 'gps', 'last_visit_time'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var sm = new Ext.grid.CheckboxSelectionModel(); var win1 = new Ext.Window({ title : '选择客户', id : 'chooseCustomer', layout : 'fit', border : false, modal : true, width : 800, height : 600, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户名称', width : 100, dataIndex : 'name', sortable : true, remoteSort : true, align : 'center' }, { header : '客户编号', width : 130, dataIndex : 'number', sortable : true, remoteSort : true, align : 'center' }, { header : '专卖证号', width : 130, dataIndex : 'sell_number', sortable : true, remoteSort : true, align : 'center' }, { header : '店铺名称', width : 200, dataIndex : 'store_name', sortable : true, remoteSort : true, align : 'left' }, { header : '客户级别', width : 90, dataIndex : 'level', sortable : true, remoteSort : true, align : 'center' }, { header : '电话号码', width : 100, dataIndex : 'phone_number', sortable : true, remoteSort : true, align : 'center' }, { header : '客户经理', width : 120, dataIndex : 'manager', sortable : true, remoteSort : true, align : 'center' }, { header : '备用号码', width : 100, dataIndex : 'backup_number', sortable : true, remoteSort : true, align : 'center' }, { header : '经营地址', width : 240, dataIndex : 'address', sortable : true, remoteSort : true, align : 'left', renderer : function(value, meta) { meta.attr = 'title="' + value + '"'; return value; } }, { header : '订货类型', width : 60, dataIndex : 'order_type', sortable : true, remoteSort : true, align : 'center' }, { header : 'GPS(经度,纬度)', width : 150, dataIndex : 'gps', sortable : true, remoteSort : true, align : 'center' }, { header : '最近一次拜访时间', width : 180, dataIndex : 'last_visit_time', sortable : true, remoteSort : true, align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (crecords.length < 1) { alert('请选择要拜访的客户!'); return; } var size = crecords.length; var cids = ""; for (var i = 0; i < size; i++) { cids += ',' + crecords[i].get('id'); } Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=customerTask', params : { cids : cids }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); Ext.getCmp('chooseCustomer').close(); } }, { text : '取消', handler : function() { Ext.getCmp('chooseCustomer').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }, { text : '自定义任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var cids = ''; var mid = ''; var win = new Ext.Window({ title : '自定义任务', id : 'editWin', layout : 'fit', border : false, modal : true, width : 500, height : 250, items : [new Ext.form.FormPanel({ id : 'editForm', frame : true, bodyStyle : 'padding : 30px; 20px;', defaults : { msgTarget : 'under' }, height : 'auto', labelWidth : 80, labelAlign : 'right', items : [{ xtype : 'compositefield', width : 500, items : [{ fieldLabel : '客户名称', xtype : 'textfield', id : 'customer', allowBlank : false, width : 300 }, { text : '浏览…', xtype : 'button', handler : function() { // 选择客户 var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customer.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager', 'backup_number', 'address', 'order_type', 'gps', 'last_visit_time'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var sm = new Ext.grid.CheckboxSelectionModel(); var win1 = new Ext.Window({ title : '选择客户', id : 'chooseCustomer', layout : 'fit', border : false, modal : true, width : 800, height : 600, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户名称', width : 100, dataIndex : 'name', sortable : true, remoteSort : true, align : 'center' }, { header : '客户编号', width : 130, dataIndex : 'number', sortable : true, remoteSort : true, align : 'center' }, { header : '专卖证号', width : 130, dataIndex : 'sell_number', sortable : true, remoteSort : true, align : 'center' }, { header : '店铺名称', width : 200, dataIndex : 'store_name', sortable : true, remoteSort : true, align : 'left' }, { header : '客户级别', width : 90, dataIndex : 'level', sortable : true, remoteSort : true, align : 'center' }, { header : '电话号码', width : 100, dataIndex : 'phone_number', sortable : true, remoteSort : true, align : 'center' }, { header : '客户经理', width : 120, dataIndex : 'manager', sortable : true, remoteSort : true, align : 'center' }, { header : '备用号码', width : 100, dataIndex : 'backup_number', sortable : true, remoteSort : true, align : 'center' }, { header : '经营地址', width : 240, dataIndex : 'address', sortable : true, remoteSort : true, align : 'left', renderer : function(value, meta) { meta.attr = 'title="' + value + '"'; return value; } }, { header : '订货类型', width : 60, dataIndex : 'order_type', sortable : true, remoteSort : true, align : 'center' }, { header : 'GPS(经度,纬度)', width : 150, dataIndex : 'gps', sortable : true, remoteSort : true, align : 'center' }, { header : '最近一次拜访时间', width : 180, dataIndex : 'last_visit_time', sortable : true, remoteSort : true, align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (crecords.length < 1) { alert('请选择要拜访的客户!'); return; } var size = crecords.length; var cnames = ''; for (var i = 0; i < size; i++) { cids += ',' + crecords[i].get('id'); cnames += ',' + crecords[i].get('name'); } Ext.getCmp('customer').setValue(cnames.substring(1)); Ext.getCmp('chooseCustomer').close(); } }, { text : '取消', handler : function() { Ext.getCmp('chooseCustomer').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }] }, { xtype : 'compositefield', width : 500, items : [{ fieldLabel : '客户经理', xtype : 'textfield', id : 'manager', allowBlank : false, width : 300 }, { text : '浏览…', xtype : 'button', handler : function() { // 选择客户经理 var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customerManager.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'username', 'department', 'area'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var win1 = new Ext.Window({ title : '选择客户经理', id : 'bind', layout : 'fit', border : false, modal : true, width : 600, height : 400, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), { header : '客户经理名称', width : 130, dataIndex : 'name', align : 'center' }, { header : '用户名', width : 130, dataIndex : 'username', align : 'center' }, { header : '部门', width : 130, dataIndex : 'department', align : 'center' }, { header : '片区', width : 130, dataIndex : 'area', align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (mrecords.length < 1) { alert('请选择客户经理!'); return; } mid = mrecords[0].get('id'); var manager = mrecords[0].get('name'); if (mrecords[0].get('department') != "") { manager = manager + "-" + mrecords[0].get('department'); } if (mrecords[0].get('area') != "") { manager = manager + "-" + mrecords[0].get('area'); } Ext.getCmp('manager').setValue(manager); Ext.getCmp('bind').close(); } }, { text : '取消', handler : function() { Ext.getCmp('bind').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }] }], buttons : [{ text : '确定', handler : function() { Ext.getCmp('editWin').close(); Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=newCustomerTask', params : { mid : mid, cids : cids, }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } }, { text : '取消', handler : function() { Ext.getCmp('editWin').close(); } }] })] }); win.show(Ext.getBody()); } }] }); panel = new Ext.form.FormPanel({ id : 'form', defaults : { width : 250, msgTarget : 'under' }, bodyStyle : 'padding : 50px; 150px;', labelWidth : 80, labelAlign : 'right', tbar : [{ xtype : 'button', id : 'ad', iconCls : 'add', text : '增加内容', align : 'right', width : 80, handler : function() { this.cn = this.cn + 1; var f = Ext.getCmp('form'); var a = Ext.getCmp('ad'); var t = Ext.getCmp('tsb'); var c = new Ext.form.TextField({ fieldLabel : '任务内容' + this.cn, allowBlank : false, name : 'content' + this.cn, id : 'content' + this.cn, xtype : 'textfield' }); f.remove(t); f.add(c); f.add(n); f.doLayout(); }, scope : this }], items : [{ fieldLabel : '任务起始时间', allowBlank : false, editable : false, name : 'start', id : 'start', xtype : 'datefield' }, { fieldLabel : '任务完成时间', allowBlank : false, editable : false, name : 'end', id : 'end', xtype : 'datefield' }, { fieldLabel : '任务标题', allowBlank : false, name : 'content', id : 'content', xtype : 'textfield' }, { fieldLabel : '任务内容' + this.cn, allowBlank : false, name : 'content' + this.cn, id : 'content' + this.cn, xtype : 'textfield' }, { xtype : 'button', id : 'tsb', text : '发放任务', align : 'right', width : 80, menu : [{ text : '常规任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=normal', method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } // }, { // text : '个别任务', // handler : function() { // if (!Ext.getCmp('form').getForm().isValid()) { // alert('请正确填写表单'); // return; // } // // // var sm = new Ext.grid.CheckboxSelectionModel(); // var store1 = new Ext.data.Store({ // proxy : new Ext.data.HttpProxy({ // url : 'customerManager.do?action=queryAll' // }), // reader : new Ext.data.JsonReader({ // root : 'rows', // totalProperty : 'total', // id : 'id', // fields : ['id', 'name', 'username'] // }) // }); // // var paging = new Ext.PagingToolbar({ // pageSize : 20, // store : store1, // displayInfo : true, // displayMsg : '当前显示数据 {0} - {1} of {2}', // emptyMsg : '没有数据' // }); // // var win = new Ext.Window({ // title : '客户经理', // id : 'bind', // layout : 'fit', // border : false, // modal : true, // width : 500, // height : 400, // items : [new Ext.grid.GridPanel({ // id : 'grid1', // loadMask : true, //// tbar : [{ //// xtype : 'textfield', //// id : 'searchName', //// emptyText : '请输入客户经理名称...', //// width : 150 //// }, { //// text : '搜索', //// width : 45, //// xtype : 'button', //// handler : function() { //// //// } //// }], // store : store1, // sm : sm, // cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { // header : '客户经理名称', // width : 200, // dataIndex : 'name', // align : 'center' // }, { // header : '客户经理用户名', // width : 230, // dataIndex : 'username', // align : 'center' // }]), // bbar : paging // })], // buttons : [{ // text : '确定', // handler : function() { // var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); // if (mrecords.length < 1) { // alert('请选择要做任务的客户经理!'); // return; // } // var mids = ''; // for (var j = 0; j < mrecords.length; j++) { // mids += ',' + mrecords[j].get('id'); // } // // Ext.getCmp('bind').close(); // Ext.getCmp('form').getForm().submit({ // waitTitle : '提示', // waitMsg : '正在提交数据请稍后...', // url : 'task.do?action=indevi', // params : { // mids : mids // }, // method : 'post', // success : function(form, action) { // alert(action.result.myHashMap.msg); // }, // failure : function(form, action) { // alert(action.result.myHashMap.msg); // } // }); // // } // }, { // text : '取消', // handler : function() { // Ext.getCmp('bind').close(); // } // }] // }); // win.show(Ext.getBody()); // store1.load({ // params : { // start : 0, // limit : 20 // } // }); // // } }, { text : '分组任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var sm = new Ext.grid.CheckboxSelectionModel(); var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customerGroup.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var win = new Ext.Window({ title : '客户分组', id : 'bind', layout : 'fit', border : false, modal : true, width : 500, height : 400, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户分组名称', width : 200, dataIndex : 'name', align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var grecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (grecords.length < 1) { alert('请选择客户分组!'); return; } var gids = ''; for (var j = 0; j < grecords.length; j++) { gids += ',' + grecords[j].get('id'); } Ext.getCmp('bind').close(); Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=group', params : { gids : gids }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } }, { text : '取消', handler : function() { Ext.getCmp('bind').close(); } }] }); win.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20, all : 0 } }); } }, { text : '客户任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customer.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager', 'backup_number', 'address', 'order_type', 'gps', 'last_visit_time'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var sm = new Ext.grid.CheckboxSelectionModel(); var win1 = new Ext.Window({ title : '选择客户', id : 'chooseCustomer', layout : 'fit', border : false, modal : true, width : 800, height : 600, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户名称', width : 100, dataIndex : 'name', sortable : true, remoteSort : true, align : 'center' }, { header : '客户编号', width : 130, dataIndex : 'number', sortable : true, remoteSort : true, align : 'center' }, { header : '专卖证号', width : 130, dataIndex : 'sell_number', sortable : true, remoteSort : true, align : 'center' }, { header : '店铺名称', width : 200, dataIndex : 'store_name', sortable : true, remoteSort : true, align : 'left' }, { header : '客户级别', width : 90, dataIndex : 'level', sortable : true, remoteSort : true, align : 'center' }, { header : '电话号码', width : 100, dataIndex : 'phone_number', sortable : true, remoteSort : true, align : 'center' }, { header : '客户经理', width : 120, dataIndex : 'manager', sortable : true, remoteSort : true, align : 'center' }, { header : '备用号码', width : 100, dataIndex : 'backup_number', sortable : true, remoteSort : true, align : 'center' }, { header : '经营地址', width : 240, dataIndex : 'address', sortable : true, remoteSort : true, align : 'left', renderer : function(value, meta) { meta.attr = 'title="' + value + '"'; return value; } }, { header : '订货类型', width : 60, dataIndex : 'order_type', sortable : true, remoteSort : true, align : 'center' }, { header : 'GPS(经度,纬度)', width : 150, dataIndex : 'gps', sortable : true, remoteSort : true, align : 'center' }, { header : '最近一次拜访时间', width : 180, dataIndex : 'last_visit_time', sortable : true, remoteSort : true, align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (crecords.length < 1) { alert('请选择要拜访的客户!'); return; } var size = crecords.length; var cids = ""; for (var i = 0; i < size; i++) { cids += ',' + crecords[i].get('id'); } Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=customerTask', params : { cids : cids }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); Ext.getCmp('chooseCustomer').close(); } }, { text : '取消', handler : function() { Ext.getCmp('chooseCustomer').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }, { text : '自定义任务', handler : function() { if (!Ext.getCmp('form').getForm().isValid()) { alert('请正确填写表单'); return; } var cids = ''; var mid = ''; var win = new Ext.Window({ title : '自定义任务', id : 'editWin', layout : 'fit', border : false, modal : true, width : 500, height : 250, items : [new Ext.form.FormPanel({ id : 'editForm', frame : true, bodyStyle : 'padding : 30px; 20px;', defaults : { msgTarget : 'under' }, height : 'auto', labelWidth : 80, labelAlign : 'right', items : [{ xtype : 'compositefield', width : 500, items : [{ fieldLabel : '客户名称', xtype : 'textfield', id : 'customer', allowBlank : false, width : 300 }, { text : '浏览…', xtype : 'button', handler : function() { // 选择客户 var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customer.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'number', 'sell_number', 'store_name', 'level', 'phone_number', 'manager', 'backup_number', 'address', 'order_type', 'gps', 'last_visit_time'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var sm = new Ext.grid.CheckboxSelectionModel(); var win1 = new Ext.Window({ title : '选择客户', id : 'chooseCustomer', layout : 'fit', border : false, modal : true, width : 800, height : 600, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, sm : sm, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), sm, { header : '客户名称', width : 100, dataIndex : 'name', sortable : true, remoteSort : true, align : 'center' }, { header : '客户编号', width : 130, dataIndex : 'number', sortable : true, remoteSort : true, align : 'center' }, { header : '专卖证号', width : 130, dataIndex : 'sell_number', sortable : true, remoteSort : true, align : 'center' }, { header : '店铺名称', width : 200, dataIndex : 'store_name', sortable : true, remoteSort : true, align : 'left' }, { header : '客户级别', width : 90, dataIndex : 'level', sortable : true, remoteSort : true, align : 'center' }, { header : '电话号码', width : 100, dataIndex : 'phone_number', sortable : true, remoteSort : true, align : 'center' }, { header : '客户经理', width : 120, dataIndex : 'manager', sortable : true, remoteSort : true, align : 'center' }, { header : '备用号码', width : 100, dataIndex : 'backup_number', sortable : true, remoteSort : true, align : 'center' }, { header : '经营地址', width : 240, dataIndex : 'address', sortable : true, remoteSort : true, align : 'left', renderer : function(value, meta) { meta.attr = 'title="' + value + '"'; return value; } }, { header : '订货类型', width : 60, dataIndex : 'order_type', sortable : true, remoteSort : true, align : 'center' }, { header : 'GPS(经度,纬度)', width : 150, dataIndex : 'gps', sortable : true, remoteSort : true, align : 'center' }, { header : '最近一次拜访时间', width : 180, dataIndex : 'last_visit_time', sortable : true, remoteSort : true, align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var crecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (crecords.length < 1) { alert('请选择要拜访的客户!'); return; } var size = crecords.length; var cnames = ''; for (var i = 0; i < size; i++) { cids += ',' + crecords[i].get('id'); cnames += ',' + crecords[i].get('name'); } Ext.getCmp('customer').setValue(cnames.substring(1)); Ext.getCmp('chooseCustomer').close(); } }, { text : '取消', handler : function() { Ext.getCmp('chooseCustomer').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }] }, { xtype : 'compositefield', width : 500, items : [{ fieldLabel : '客户经理', xtype : 'textfield', id : 'manager', allowBlank : false, width : 300 }, { text : '浏览…', xtype : 'button', handler : function() { // 选择客户经理 var store1 = new Ext.data.Store({ proxy : new Ext.data.HttpProxy({ url : 'customerManager.do?action=queryAll' }), reader : new Ext.data.JsonReader({ root : 'rows', totalProperty : 'total', id : 'id', fields : ['id', 'name', 'username', 'department', 'area'] }) }); var paging = new Ext.PagingToolbar({ pageSize : 20, store : store1, displayInfo : true, displayMsg : '当前显示数据 {0} - {1} of {2}', emptyMsg : '没有数据' }); var win1 = new Ext.Window({ title : '选择客户经理', id : 'bind', layout : 'fit', border : false, modal : true, width : 600, height : 400, items : [new Ext.grid.GridPanel({ id : 'grid1', loadMask : true, store : store1, cm : new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({width:38}), { header : '客户经理名称', width : 130, dataIndex : 'name', align : 'center' }, { header : '用户名', width : 130, dataIndex : 'username', align : 'center' }, { header : '部门', width : 130, dataIndex : 'department', align : 'center' }, { header : '片区', width : 130, dataIndex : 'area', align : 'center' }]), bbar : paging })], buttons : [{ text : '确定', handler : function() { var mrecords = Ext.getCmp('grid1').getSelectionModel().getSelections(); if (mrecords.length < 1) { alert('请选择客户经理!'); return; } mid = mrecords[0].get('id'); var manager = mrecords[0].get('name'); if (mrecords[0].get('department') != "") { manager = manager + "-" + mrecords[0].get('department'); } if (mrecords[0].get('area') != "") { manager = manager + "-" + mrecords[0].get('area'); } Ext.getCmp('manager').setValue(manager); Ext.getCmp('bind').close(); } }, { text : '取消', handler : function() { Ext.getCmp('bind').close(); } }] }); win1.show(Ext.getBody()); store1.load({ params : { start : 0, limit : 20 } }); } }] }], buttons : [{ text : '确定', handler : function() { Ext.getCmp('editWin').close(); Ext.getCmp('form').getForm().submit({ waitTitle : '提示', waitMsg : '正在提交数据请稍后...', url : 'task.do?action=newCustomerTask', params : { mid : mid, cids : cids, }, method : 'post', success : function(form, action) { alert(action.result.myHashMap.msg); }, failure : function(form, action) { alert(action.result.myHashMap.msg); } }); } }, { text : '取消', handler : function() { Ext.getCmp('editWin').close(); } }] })] }); win.show(Ext.getBody()); } }] }] }); } return panel; } };
hairlun/customer-visit-web
WebRoot/task/index.js
JavaScript
apache-2.0
49,167
<?php namespace App\Presenters; use Nette; class ContactPresenter extends Nette\Application\UI\Presenter { }
literat/ete89e
app/presenters/ContactPresenter.php
PHP
apache-2.0
113
/** * Copyright 2002-2016 xiaoyuepeng * * 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 xiaoyuepeng <xyp260466@163.com> */ package com.xyp260466.dubbo.annotation; import java.lang.annotation.*; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Created by xyp on 16-5-9. */ @Target({TYPE, FIELD, METHOD}) @Retention(RUNTIME) @Documented public @interface Consumer { String value() default ""; }
xyp260466/dubbo-lite
dubbo-spring/src/main/java/com/xyp260466/dubbo/annotation/Consumer.java
Java
apache-2.0
1,109
<?php namespace Test\Controllers; use Test\Models\EmailConfirmations; use Test\Models\ResetPasswords; /** * UserControlController * Provides help to users to confirm their passwords or reset them */ class UserControlController extends ControllerBase { public function initialize() { if ($this->session->has('auth-identity')) { $this->view->setTemplateBefore('private'); } } public function indexAction() { } /** * Confirms an e-mail, if the user must change thier password then changes it */ public function confirmEmailAction() { $code = $this->dispatcher->getParam('code'); $confirmation = EmailConfirmations::findFirstByCode($code); if (!$confirmation) { return $this->dispatcher->forward([ 'controller' => 'index', 'action' => 'index' ]); } if ($confirmation->confirmed != 'N') { return $this->dispatcher->forward([ 'controller' => 'session', 'action' => 'login' ]); } $confirmation->confirmed = 'Y'; $confirmation->user->active = 'Y'; /** * Change the confirmation to 'confirmed' and update the user to 'active' */ if (!$confirmation->save()) { foreach ($confirmation->getMessages() as $message) { $this->flash->error($message); } return $this->dispatcher->forward([ 'controller' => 'index', 'action' => 'index' ]); } /** * Identify the user in the application */ $this->auth->authUserById($confirmation->user->id); /** * Check if the user must change his/her password */ if ($confirmation->user->mustChangePassword == 'Y') { $this->flash->success('The email was successfully confirmed. Now you must change your password'); return $this->dispatcher->forward([ 'controller' => 'users', 'action' => 'changePassword' ]); } $this->flash->success('The email was successfully confirmed'); return $this->dispatcher->forward([ 'controller' => 'users', 'action' => 'index' ]); } public function resetPasswordAction() { $code = $this->dispatcher->getParam('code'); $resetPassword = ResetPasswords::findFirstByCode($code); if (!$resetPassword) { return $this->dispatcher->forward([ 'controller' => 'index', 'action' => 'index' ]); } if ($resetPassword->reset != 'N') { return $this->dispatcher->forward([ 'controller' => 'session', 'action' => 'login' ]); } $resetPassword->reset = 'Y'; /** * Change the confirmation to 'reset' */ if (!$resetPassword->save()) { foreach ($resetPassword->getMessages() as $message) { $this->flash->error($message); } return $this->dispatcher->forward([ 'controller' => 'index', 'action' => 'index' ]); } /** * Identify the user in the application */ $this->auth->authUserById($resetPassword->usersId); $this->flash->success('Please reset your password'); return $this->dispatcher->forward([ 'controller' => 'users', 'action' => 'changePassword' ]); } }
tetrapak07/testPhalcon
app/controllers/UserControlController.php
PHP
apache-2.0
3,697
/** * 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.hadoop.hdfs.server.namenode; import org.apache.commons.logging.*; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol; import org.apache.hadoop.hdfs.protocol.FSConstants; import org.apache.hadoop.hdfs.server.common.HdfsConstants; import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException; import org.apache.hadoop.ipc.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Daemon; import org.apache.hadoop.http.HttpServer; import org.apache.hadoop.net.NetUtils; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.apache.hadoop.metrics.jvm.JvmMetrics; /********************************************************** * The Secondary NameNode is a helper to the primary NameNode. The Secondary is * responsible for supporting periodic checkpoints of the HDFS metadata. The * current design allows only one Secondary NameNode per HDFs cluster. * * The Secondary NameNode is a daemon that periodically wakes up (determined by * the schedule specified in the configuration), triggers a periodic checkpoint * and then goes back to sleep. The Secondary NameNode uses the ClientProtocol * to talk to the primary NameNode. * **********************************************************/ public class SecondaryNameNode implements Runnable { public static final Log LOG = LogFactory.getLog(SecondaryNameNode.class .getName()); private String fsName; private CheckpointStorage checkpointImage; private NamenodeProtocol namenode; private Configuration conf; private InetSocketAddress nameNodeAddr; private volatile boolean shouldRun; private HttpServer infoServer; private int infoPort; private String infoBindAddress; private Collection<File> checkpointDirs; private Collection<File> checkpointEditsDirs; private long checkpointPeriod; // in seconds private long checkpointSize; // size (in MB) of current Edit Log /** * Utility class to facilitate junit test error simulation. */ static class ErrorSimulator { private static boolean[] simulation = null; // error simulation events static void initializeErrorSimulationEvent(int numberOfEvents) { simulation = new boolean[numberOfEvents]; for (int i = 0; i < numberOfEvents; i++) { simulation[i] = false; } } static boolean getErrorSimulation(int index) { if (simulation == null) return false; assert (index < simulation.length); return simulation[index]; } static void setErrorSimulation(int index) { assert (index < simulation.length); simulation[index] = true; } static void clearErrorSimulation(int index) { assert (index < simulation.length); simulation[index] = false; } } FSImage getFSImage() { return checkpointImage; } /** * Create a connection to the primary namenode. */ public SecondaryNameNode(Configuration conf) throws IOException { try { initialize(conf); } catch (IOException e) { shutdown(); throw e; } } /** * Initialize SecondaryNameNode. */ private void initialize(Configuration conf) throws IOException { // initiate Java VM metrics JvmMetrics.init("SecondaryNameNode", conf.get("session.id")); // Create connection to the namenode. shouldRun = true; nameNodeAddr = NameNode.getAddress(conf); this.conf = conf; this.namenode = (NamenodeProtocol) RPC.waitForProxy( NamenodeProtocol.class, NamenodeProtocol.versionID, nameNodeAddr, conf); // initialize checkpoint directories fsName = getInfoServer(); checkpointDirs = FSImage.getCheckpointDirs(conf, "/tmp/hadoop/dfs/namesecondary"); checkpointEditsDirs = FSImage.getCheckpointEditsDirs(conf, "/tmp/hadoop/dfs/namesecondary"); checkpointImage = new CheckpointStorage(); checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs); // Initialize other scheduling parameters from the configuration checkpointPeriod = conf.getLong("fs.checkpoint.period", 3600); checkpointSize = conf.getLong("fs.checkpoint.size", 4194304); // initialize the webserver for uploading files. String infoAddr = NetUtils.getServerAddress(conf, "dfs.secondary.info.bindAddress", "dfs.secondary.info.port", "dfs.secondary.http.address"); InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(infoAddr); infoBindAddress = infoSocAddr.getHostName(); int tmpInfoPort = infoSocAddr.getPort(); infoServer = new HttpServer("secondary", infoBindAddress, tmpInfoPort, tmpInfoPort == 0, conf); infoServer.setAttribute("name.system.image", checkpointImage); this.infoServer.setAttribute("name.conf", conf); infoServer.addInternalServlet("getimage", "/getimage", GetImageServlet.class); infoServer.start(); // The web-server port can be ephemeral... ensure we have the correct // info infoPort = infoServer.getPort(); conf .set("dfs.secondary.http.address", infoBindAddress + ":" + infoPort); LOG.info("Secondary Web-server up at: " + infoBindAddress + ":" + infoPort); LOG.warn("Checkpoint Period :" + checkpointPeriod + " secs " + "(" + checkpointPeriod / 60 + " min)"); LOG.warn("Log Size Trigger :" + checkpointSize + " bytes " + "(" + checkpointSize / 1024 + " KB)"); } /** * Shut down this instance of the datanode. Returns only after shutdown is * complete. */ public void shutdown() { shouldRun = false; try { if (infoServer != null) infoServer.stop(); } catch (Exception e) { LOG.warn("Exception shutting down SecondaryNameNode", e); } try { if (checkpointImage != null) checkpointImage.close(); } catch (IOException e) { LOG.warn(StringUtils.stringifyException(e)); } } // // The main work loop // public void run() { // // Poll the Namenode (once every 5 minutes) to find the size of the // pending edit log. // long period = 5 * 60; // 5 minutes long lastCheckpointTime = 0; if (checkpointPeriod < period) { period = checkpointPeriod; } while (shouldRun) { try { Thread.sleep(1000 * period); } catch (InterruptedException ie) { // do nothing } if (!shouldRun) { break; } try { long now = System.currentTimeMillis(); long size = namenode.getEditLogSize(); if (size >= checkpointSize || now >= lastCheckpointTime + 1000 * checkpointPeriod) { doCheckpoint(); lastCheckpointTime = now; } } catch (IOException e) { LOG.error("Exception in doCheckpoint: "); LOG.error(StringUtils.stringifyException(e)); e.printStackTrace(); } catch (Throwable e) { LOG.error("Throwable Exception in doCheckpoint: "); LOG.error(StringUtils.stringifyException(e)); e.printStackTrace(); Runtime.getRuntime().exit(-1); } } } /** * Download <code>fsimage</code> and <code>edits</code> files from the * name-node. * * @throws IOException */ private void downloadCheckpointFiles(CheckpointSignature sig) throws IOException { checkpointImage.cTime = sig.cTime; checkpointImage.checkpointTime = sig.checkpointTime; // get fsimage String fileid = "getimage=1"; File[] srcNames = checkpointImage.getImageFiles(); assert srcNames.length > 0 : "No checkpoint targets."; TransferFsImage.getFileClient(fsName, fileid, srcNames); LOG.info("Downloaded file " + srcNames[0].getName() + " size " + srcNames[0].length() + " bytes."); // get edits file fileid = "getedit=1"; srcNames = checkpointImage.getEditsFiles(); assert srcNames.length > 0 : "No checkpoint targets."; TransferFsImage.getFileClient(fsName, fileid, srcNames); LOG.info("Downloaded file " + srcNames[0].getName() + " size " + srcNames[0].length() + " bytes."); checkpointImage.checkpointUploadDone(); } /** * Copy the new fsimage into the NameNode */ private void putFSImage(CheckpointSignature sig) throws IOException { String fileid = "putimage=1&port=" + infoPort + "&machine=" + InetAddress.getLocalHost().getHostAddress() + "&token=" + sig.toString(); LOG.info("Posted URL " + fsName + fileid); TransferFsImage.getFileClient(fsName, fileid, (File[]) null); } /** * Returns the Jetty server that the Namenode is listening on. */ private String getInfoServer() throws IOException { URI fsName = FileSystem.getDefaultUri(conf); if (!"hdfs".equals(fsName.getScheme())) { throw new IOException("This is not a DFS"); } return NetUtils.getServerAddress(conf, "dfs.info.bindAddress", "dfs.info.port", "dfs.http.address"); } /** * Create a new checkpoint */ void doCheckpoint() throws IOException { // Do the required initialization of the merge work area. startCheckpoint(); // Tell the namenode to start logging transactions in a new edit file // Retuns a token that would be used to upload the merged image. CheckpointSignature sig = (CheckpointSignature) namenode.rollEditLog(); // error simulation code for junit test if (ErrorSimulator.getErrorSimulation(0)) { throw new IOException("Simulating error0 " + "after creating edits.new"); } downloadCheckpointFiles(sig); // Fetch fsimage and edits doMerge(sig); // Do the merge // // Upload the new image into the NameNode. Then tell the Namenode // to make this new uploaded image as the most current image. // putFSImage(sig); // error simulation code for junit test if (ErrorSimulator.getErrorSimulation(1)) { throw new IOException("Simulating error1 " + "after uploading new image to NameNode"); } namenode.rollFsImage(); checkpointImage.endCheckpoint(); LOG.warn("Checkpoint done. New Image Size: " + checkpointImage.getFsImageName().length()); } private void startCheckpoint() throws IOException { checkpointImage.unlockAll(); checkpointImage.getEditLog().close(); checkpointImage.recoverCreate(checkpointDirs, checkpointEditsDirs); checkpointImage.startCheckpoint(); } /** * Merge downloaded image and edits and write the new image into current * storage directory. */ private void doMerge(CheckpointSignature sig) throws IOException { FSNamesystem namesystem = new FSNamesystem(checkpointImage, conf); assert namesystem.dir.fsImage == checkpointImage; checkpointImage.doMerge(sig); } /** * @param argv * The parameters passed to this program. * @exception Exception * if the filesystem does not exist. * @return 0 on success, non zero on error. */ private int processArgs(String[] argv) throws Exception { if (argv.length < 1) { printUsage(""); return -1; } int exitCode = -1; int i = 0; String cmd = argv[i++]; // // verify that we have enough command line parameters // if ("-geteditsize".equals(cmd)) { if (argv.length != 1) { printUsage(cmd); return exitCode; } } else if ("-checkpoint".equals(cmd)) { if (argv.length != 1 && argv.length != 2) { printUsage(cmd); return exitCode; } if (argv.length == 2 && !"force".equals(argv[i])) { printUsage(cmd); return exitCode; } } exitCode = 0; try { if ("-checkpoint".equals(cmd)) { long size = namenode.getEditLogSize(); if (size >= checkpointSize || argv.length == 2 && "force".equals(argv[i])) { doCheckpoint(); } else { System.err.println("EditLog size " + size + " bytes is " + "smaller than configured checkpoint " + "size " + checkpointSize + " bytes."); System.err.println("Skipping checkpoint."); } } else if ("-geteditsize".equals(cmd)) { long size = namenode.getEditLogSize(); System.out.println("EditLog size is " + size + " bytes"); } else { exitCode = -1; LOG.error(cmd.substring(1) + ": Unknown command"); printUsage(""); } } catch (RemoteException e) { // // This is a error returned by hadoop server. Print // out the first line of the error mesage, ignore the stack trace. exitCode = -1; try { String[] content; content = e.getLocalizedMessage().split("\n"); LOG.error(cmd.substring(1) + ": " + content[0]); } catch (Exception ex) { LOG.error(cmd.substring(1) + ": " + ex.getLocalizedMessage()); } } catch (IOException e) { // // IO exception encountered locally. // exitCode = -1; LOG.error(cmd.substring(1) + ": " + e.getLocalizedMessage()); } finally { // Does the RPC connection need to be closed? } return exitCode; } /** * Displays format of commands. * * @param cmd * The command that is being executed. */ private void printUsage(String cmd) { if ("-geteditsize".equals(cmd)) { System.err.println("Usage: java SecondaryNameNode" + " [-geteditsize]"); } else if ("-checkpoint".equals(cmd)) { System.err.println("Usage: java SecondaryNameNode" + " [-checkpoint [force]]"); } else { System.err.println("Usage: java SecondaryNameNode " + "[-checkpoint [force]] " + "[-geteditsize] "); } } /** * main() has some simple utility methods. * * @param argv * Command line parameters. * @exception Exception * if the filesystem does not exist. */ public static void main(String[] argv) throws Exception { StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG); Configuration tconf = new Configuration(); if (argv.length >= 1) { SecondaryNameNode secondary = new SecondaryNameNode(tconf); int ret = secondary.processArgs(argv); System.exit(ret); } // Create a never ending deamon Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf)); checkpointThread.start(); } static class CheckpointStorage extends FSImage { /** */ CheckpointStorage() throws IOException { super(); } @Override public boolean isConversionNeeded(StorageDirectory sd) { return false; } /** * Analyze checkpoint directories. Create directories if they do not * exist. Recover from an unsuccessful checkpoint is necessary. * * @param dataDirs * @param editsDirs * @throws IOException */ void recoverCreate(Collection<File> dataDirs, Collection<File> editsDirs) throws IOException { Collection<File> tempDataDirs = new ArrayList<File>(dataDirs); Collection<File> tempEditsDirs = new ArrayList<File>(editsDirs); this.storageDirs = new ArrayList<StorageDirectory>(); setStorageDirectories(tempDataDirs, tempEditsDirs); for (Iterator<StorageDirectory> it = dirIterator(); it.hasNext();) { StorageDirectory sd = it.next(); boolean isAccessible = true; try { // create directories if don't exist yet if (!sd.getRoot().mkdirs()) { // do nothing, directory is already created } } catch (SecurityException se) { isAccessible = false; } if (!isAccessible) throw new InconsistentFSStateException(sd.getRoot(), "cannot access checkpoint directory."); StorageState curState; try { curState = sd .analyzeStorage(HdfsConstants.StartupOption.REGULAR); // sd is locked but not opened switch (curState) { case NON_EXISTENT: // fail if any of the configured checkpoint dirs are // inaccessible throw new InconsistentFSStateException(sd.getRoot(), "checkpoint directory does not exist or is not accessible."); case NOT_FORMATTED: break; // it's ok since initially there is no current // and VERSION case NORMAL: break; default: // recovery is possible sd.doRecover(curState); } } catch (IOException ioe) { sd.unlock(); throw ioe; } } } /** * Prepare directories for a new checkpoint. * <p> * Rename <code>current</code> to <code>lastcheckpoint.tmp</code> and * recreate <code>current</code>. * * @throws IOException */ void startCheckpoint() throws IOException { for (StorageDirectory sd : storageDirs) { File curDir = sd.getCurrentDir(); File tmpCkptDir = sd.getLastCheckpointTmp(); assert !tmpCkptDir.exists() : tmpCkptDir.getName() + " directory must not exist."; if (curDir.exists()) { // rename current to tmp rename(curDir, tmpCkptDir); } if (!curDir.mkdir()) throw new IOException("Cannot create directory " + curDir); } } void endCheckpoint() throws IOException { for (StorageDirectory sd : storageDirs) { File tmpCkptDir = sd.getLastCheckpointTmp(); File prevCkptDir = sd.getPreviousCheckpoint(); // delete previous dir if (prevCkptDir.exists()) deleteDir(prevCkptDir); // rename tmp to previous if (tmpCkptDir.exists()) rename(tmpCkptDir, prevCkptDir); } } /** * Merge image and edits, and verify consistency with the signature. */ private void doMerge(CheckpointSignature sig) throws IOException { getEditLog().open(); StorageDirectory sdName = null; StorageDirectory sdEdits = null; Iterator<StorageDirectory> it = null; it = dirIterator(NameNodeDirType.IMAGE); if (it.hasNext()) sdName = it.next(); it = dirIterator(NameNodeDirType.EDITS); if (it.hasNext()) sdEdits = it.next(); if ((sdName == null) || (sdEdits == null)) throw new IOException("Could not locate checkpoint directories"); loadFSImage(FSImage.getImageFile(sdName, NameNodeFile.IMAGE)); loadFSEdits(sdEdits); sig.validateStorageInfo(this); saveFSImage(); } } }
shot/hadoop-source-reading
src/hdfs/org/apache/hadoop/hdfs/server/namenode/SecondaryNameNode.java
Java
apache-2.0
18,270
"""Custom Exception Classes for Phylotyper Module """ class PhylotyperError(Exception): """Basic exception for errors raised by Phylotyper modules""" def __init__(self, subtype, msg=None): if msg is None: msg = "An error occured for subtype {}".format(subtype) super(PhylotyperError, self).__init__(msg) self.subtype = subtype class ValuesError(PhylotyperError): """Unknown subtype""" def __init__(self, subtype, msg=None): super(PhylotyperError, self).__init__( subtype, msg="Unrecognized subtype {}".format(subtype)) class DatabaseError(PhylotyperError): """Missing data in Database""" def __init__(self, subtype, data, msg=None): m = "Database is missing data {} for {}".format(data, subtype) super(PhylotyperError, self).__init__(subtype, m) self.data = data
superphy/backend
app/modules/phylotyper/exceptions.py
Python
apache-2.0
874
maintainer "Belly, Inc." maintainer_email "sysops@bellycard.com" license "Apache v2.0" description "Installs/Configures Google Go" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "1.0.0" # Operating systems supported %w{ debian ubuntu }.each do |os| supports os end
bellycard/procd
scripts/chef/cookbooks/go/metadata.rb
Ruby
apache-2.0
331
<?php $curdir = dirname(__FILE__); require_once($curdir.'/Db.php'); class LoanStatus extends Db { protected static $table_name = "loanstatus"; protected static $db_fields = array("id", "name", "description"); public function findById($id){ $result = $this->getrec(self::$table_name, "id=".$id, ""); return !empty($result) ? $result:false; } public function findAll(){ $result_array = $this->getarray(self::$table_name, "", "", ""); return !empty($result_array) ? $result_array : false; } public function findLoanStatus($id){ $result = $this->getfrec(self::$table_name, "name", "id=".$id, "", ""); return !empty($result) ? $result['name'] : false; } public function addLoanStatus($data){ $fields = self::$db_fields; if($this->add(self::$table_name, $fields, $this->generateAddFields($fields, $data))){ return true; } return false; } public function updateLoanStatus($data){ $fields = array_slice(1, self::$db_fields); $id = $data['id']; unset($data['id']); if($this->update(self::$table_name, $fields, $this->generateAddFields($fields, $data), "id=".$id)){ return true; } return false; } } ?>
platinalfred/buladde
lib/LoanStatus.php
PHP
apache-2.0
1,146
<?php /** * DBDelTree action message. * * PHP Version 5 * * @category PHPAMI * @package Message * @subpackage Action * @author Jaime Ziga <jaime.ziga@gmail.com> * @license http://github.com/Adrian0350/PHP-AMI/ Apache License 2.0 * @version SVN: $Id$ * @link http://github.com/Adrian0350/PHP-AMI/ * * 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. * */ require_once dirname(__FILE__) . '/ActionMessage.php'; /** * DBDelTree action message. * * PHP Version 5 * * @category PHPAMI * @package Message * @subpackage Action * @author Jaime Ziga <jaime.ziga@gmail.com> * @license http://github.com/Adrian0350/PHP-AMI/ Apache License 2.0 * @link http://github.com/Adrian0350/PHP-AMI/ */ class DBDelTreeAction extends ActionMessage { /** * Constructor. * * @param string $family Family. * @param string $key Name (optional) * * @return void */ public function __construct($family, $key = false) { parent::__construct('DBDelTree'); $this->setKey('Family', $family); if ($key != false) { $this->setKey('Key', $key); } } }
Adrian0350/PHP-AMI
src/PHPAMI/Message/Action/DBDelTreeAction.php
PHP
apache-2.0
1,740
/* ~ Copyright (c) 2014 George Norman. ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ -------------------------------------------------------------- ~ Renders <css-lab-about> tags - sharable among all projects. ~ -------------------------------------------------------------- */ /** * The &lt;css-lab-about&gt; tag renders a common introduction, displayed across all of the * CSS Lab projects and pages. There can be only one Introduction section per page. *<p> * Example: * <pre style="background:#eee; padding:6px;"> * &lt;css-lab-about style="margin-top:12px;"/&gt; * </pre> * * @module cssLabAboutTag */ var cssLabAboutTag = (function(tzDomHelper, tzCustomTagHelper) { "use strict"; // http://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript var template = ['This page contains example code used for the <a href="http://www.thruzero.com/jcat3/apps/resources/resources.jsf?rid=css.overview">CSS Summary</a>', 'at <a href="http://www.thruzero.com/">ThruZero</a>. ', 'The example code (e.g., CSS and HTML) is defined with inline-templates and then rendered live, so it will always match the rendered example. ' ].join('\n'); return { getTagName: function() { return "css-lab-about"; }, /** * Render the first &lt;css-lab-about&gt; tag on the page - only one tag per page is supported. */ renderAll: function() { tzCustomTagHelper.renderFirst(this); }, /** * Render the &lt;css-lab-about&gt; tag identified by the given tagId. * * @param tagId ID of the tag to render. */ renderTagById: function(tagId) { tzCustomTagHelper.renderTagById(this, tagId); }, /** * Render the given aboutTagNode. * * @param aboutTagNode the node to retrieve the attributes from and then render the result to. */ renderTag: function(aboutTagNode) { this.render(aboutTagNode); }, /** * Render the 'About Application' HTML, into the given containerNode. * * @param containerNode where to render the result. */ render: function(containerNode) { containerNode.style.display = 'block'; //var template = tzCustomTagHelper.getTemplate(this.getTagName() + "Template"); // @-@:p1(geo) Experimental tzCustomTagHelper.renderTagFromTemplate(containerNode, template, {}); } } }(tzDomHelperModule, tzCustomTagHelperModule));
georgenorman/css-lab
src/js/tags/cssLabAbout.js
JavaScript
apache-2.0
2,522
package me.soulmachine; import org.jruby.embed.ScriptingContainer; import java.util.List; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import javax.script.ScriptException; /** * A simple JRuby example to execute Python scripts from Java. */ final class JRubyExample { private JRubyExample() {} /** * Main entrypoint. * * @param args arguments * @throws ScriptException ScriptException */ public static void main(final String[] args) throws ScriptException { listEngines(); final String rubyHelloWord = "puts 'Hello World from JRuby!'"; // First way: Use built-in ScriptEngine from JDK { final ScriptEngineManager mgr = new ScriptEngineManager(); final ScriptEngine pyEngine = mgr.getEngineByName("ruby"); try { pyEngine.eval(rubyHelloWord); } catch (ScriptException ex) { ex.printStackTrace(); } } // Second way: Use ScriptingContainer() from JRuby { final ScriptingContainer scriptingContainer = new ScriptingContainer(); scriptingContainer.runScriptlet(rubyHelloWord); } // Call Ruby Methods from Java { final ScriptingContainer scriptingContainer = new ScriptingContainer(); final String rubyMethod = "def myAdd(a,b)\n\treturn a+b\nend"; final Object receiver = scriptingContainer.runScriptlet(rubyMethod); final Object[] arguments = new Object[2]; arguments[0] = Integer.valueOf(6); arguments[1] = Integer.valueOf(4); final Integer result = scriptingContainer.callMethod(receiver, "myAdd", arguments, Integer.class); System.out.println("Result: " + result); } } /** * Display all script engines. */ public static void listEngines() { final ScriptEngineManager mgr = new ScriptEngineManager(); final List<ScriptEngineFactory> factories = mgr.getEngineFactories(); for (final ScriptEngineFactory factory: factories) { System.out.println("ScriptEngineFactory Info"); final String engName = factory.getEngineName(); final String engVersion = factory.getEngineVersion(); final String langName = factory.getLanguageName(); final String langVersion = factory.getLanguageVersion(); System.out.printf("\tScript Engine: %s (%s)\n", engName, engVersion); final List<String> engNames = factory.getNames(); for (final String name: engNames) { System.out.printf("\tEngine Alias: %s\n", name); } System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion); } } }
soulmachine/JRubyExample
JRubyExample/src/main/java/me/soulmachine/JRubyExample.java
Java
apache-2.0
2,633
package com.arthurb.iterator.dinermergergery; import java.util.Iterator; /** * Created by Blackwood on 07.03.2016 18:16. */ public class DinerMenu implements Menu { static final int MAX_ITEMS = 6; int numberOfItems = 0; MenuItem[] menuItems; public DinerMenu() { menuItems = new MenuItem[MAX_ITEMS]; addItem("Vegetarian BLT", "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99); addItem("BLT", "Bacon with lettuce & tomato on whole wheat", false, 2.99); addItem("Soup of the day", "Soup of the day, with a side of potato salad", false, 2.99); addItem("Hotdog", "A got dog, with saurkraut, relish, onions, topped with cheese", false, 3.05); addItem("Steamed Veggies and Brown Rice", "Steamed vegetables over brown rice", true, 3.99); addItem("Pasta", "Spaghetti with Marinara Sauce, and a slice of sourdough bread", true, 3.89); } private void addItem(String name, String description, boolean vegetarian, double price) { MenuItem menuItem = new MenuItem(name, description, vegetarian, price); if (numberOfItems >= MAX_ITEMS) { // Ограничиваем размер меню, чтобы не запоминать слишком много рецептов System.err.println("Sorry, menu is full! Can't add item to menu"); } else { menuItems[numberOfItems] = menuItem; numberOfItems = numberOfItems + 1; } } public Iterator createIterator() { return new DinerMenuIterator(menuItems); } }
NeverNight/SimplesPatterns.Java
src/com/arthurb/iterator/dinermergergery/DinerMenu.java
Java
apache-2.0
1,583
/* eslint-disable local/html-template */ const documentModes = require('./document-modes'); const {AmpState, ampStateKey} = require('./amphtml-helpers'); const {html, joinFragments} = require('./html'); const jsModes = [ { value: 'default', description: `Unminified AMP JavaScript is served from the local server. For local development you will usually want to serve unminified JS to test your changes.`, }, { value: 'minified', description: html` Minified AMP JavaScript is served from the local server. This is only available after running <code>amp dist --fortesting</code> `, }, { value: 'cdn', description: 'Minified AMP JavaScript is served from the AMP Project CDN.', }, ]; const stateId = 'settings'; const htmlEnvelopePrefixStateKey = 'htmlEnvelopePrefix'; const jsModeStateKey = 'jsMode'; const panelStateKey = 'panel'; const htmlEnvelopePrefixKey = ampStateKey(stateId, htmlEnvelopePrefixStateKey); const panelKey = ampStateKey(stateId, panelStateKey); const PanelSelectorButton = ({expression, type, value}) => html` <button class="settings-panel-button" [class]="'settings-panel-button' + (${panelKey} != '${type}' ? '' : ' open')" data-type="${type}" tabindex="0" on="tap: AMP.setState({ ${stateId}: { ${panelStateKey}: (${panelKey} != '${type}' ? '${type}' : null), } })" > <span>${type}</span> <strong [text]="${expression}">${value}</strong> </button> `; const PanelSelector = ({children, compact = false, key, name = null}) => html` <amp-selector layout="container" name="${name || key}" class="${compact ? 'compact ' : ''}" on="select: AMP.setState({ ${stateId}: { ${panelStateKey}: null, ${key}: event.targetOption, } })" > ${joinFragments(children)} </amp-selector> `; const PanelSelectorBlock = ({children, id, selected, value}) => html` <div class="selector-block" ${selected ? ' selected' : ''} id="${id}" option="${value}" > <div class="check-icon icon"></div> ${children} </div> `; const HtmlEnvelopeSelector = ({htmlEnvelopePrefix}) => PanelSelector({ compact: true, key: htmlEnvelopePrefixStateKey, children: Object.entries(documentModes).map(([prefix, name]) => PanelSelectorBlock({ id: `select-html-mode-${name}`, value: prefix, selected: htmlEnvelopePrefix === prefix, children: html`<strong>${name}</strong>`, }) ), }); const JsModeSelector = ({jsMode}) => PanelSelector({ key: jsModeStateKey, name: 'mode', children: jsModes.map(({description, value}) => PanelSelectorBlock({ id: `serve-mode-${value}`, value, selected: jsMode === value, children: html` <strong>${value}</strong> <p>${description}</p> `, }) ), }); const SettingsPanelButtons = ({htmlEnvelopePrefix, jsMode}) => html` <div style="flex: 1"> <div class="settings-panel-button-container"> ${PanelSelectorButton({ type: 'HTML', expression: `${stateId}.documentModes[${htmlEnvelopePrefixKey}]`, value: documentModes[htmlEnvelopePrefix], })} ${PanelSelectorButton({ type: 'JS', expression: `${stateId}.${jsModeStateKey}`, value: jsMode, })} </div> ${SettingsPanel({htmlEnvelopePrefix, jsMode})} </div> `; const SettingsSubpanel = ({children, type}) => html` <div hidden [hidden]="${panelKey} != '${type}'">${children}</div> `; const SettingsPanel = ({htmlEnvelopePrefix, jsMode}) => html` <div class="settings-panel" hidden [hidden]="${panelKey} == null"> ${AmpState(stateId, { documentModes, [panelStateKey]: null, [htmlEnvelopePrefixStateKey]: htmlEnvelopePrefix, [jsModeStateKey]: jsMode, })} ${SettingsSubpanel({ type: 'HTML', children: html` <h4>Select an envelope to serve HTML documents.</h4> ${HtmlEnvelopeSelector({htmlEnvelopePrefix})} `, })} ${SettingsSubpanel({ type: 'JS', children: html` <h4>Select the JavaScript binaries to use in served documents.</h4> <form action="/serve_mode_change" action-xhr="/serve_mode_change" target="_blank" id="serve-mode-form" > ${JsModeSelector({jsMode})} </form> `, })} </div> `; module.exports = { SettingsPanel, SettingsPanelButtons, htmlEnvelopePrefixKey, };
jpettitt/amphtml
build-system/server/app-index/settings.js
JavaScript
apache-2.0
4,586
/** * * Web Starter Kit * Copyright 2014 Google Inc. 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 * */ 'use strict'; // Include Gulp & Tools We'll Use var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var del = require('del'); var runSequence = require('run-sequence'); var browserSync = require('browser-sync'); var reload = browserSync.reload; // Clean Output Directory gulp.task('clean', del.bind(null, ['./index.js', './assertRank.js', './specs.js'])); gulp.task('es6', ['clean'], function () { return gulp.src(['./src/**/*.js']) // .pipe($.sourcemaps.init({loadMaps: true})) .pipe($['6to5']()).on('error', console.error.bind(console)) // .pipe($.sourcemaps.write()) .pipe(gulp.dest('.')) .pipe($.size({title: 'es6'})) }) gulp.task('browserify', ['es6'], function () { return gulp.src(['./specs.js']) .pipe($.browserify({debug: false})) .pipe(gulp.dest('.')) .pipe($.size({title: 'browserify'})) }) // Watch Files For Changes & Reload gulp.task('serve', ['browserify'], function () { browserSync({ notify: false, browser: 'skip', ghostMode: false, // Customize the BrowserSync console logging prefix logPrefix: 'WSK', port: 3010, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: ['.', 'src'] }); gulp.watch(['gulpfile.js'], process.exit) gulp.watch(['./src/**/*.{js,html}'], ['browserify', reload]); }); gulp.task('default', ['es6']) // Load custom tasks from the `tasks` directory // try { require('require-dir')('tasks'); } catch (err) { console.error(err); }
markuz-brasil/runtime-type-system
gulpfile.js
JavaScript
apache-2.0
2,272
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-65704319-1', 'auto'); ga('send', 'pageview');
sofiamoral/sofiamoral.github.io
js/custom.js
JavaScript
apache-2.0
391
/** * Copyright 2017 Shusheng Shao <iblackangel@163.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. */ #include <mpl/mlog.h> #include <mpl/msysinfo.h> #include <mpl/mdatetime.h> #include <mpl/mapplication.h> #include <mpl/mprocess.h> #include <mpl/mstring.h> #include <mpl/merror.h> #include <mpl/mfile.h> #ifdef _MSC_VER # pragma warning (push) # pragma warning (disable: 4996) #endif MPL_BEGIN_NAMESPACE MLog *MLog::_ins = NULL; MLog *MLog::instance() { if (NULL == _ins) { _ins = new MLog(); atexit(desposed); } return _ins; } void MLog::desposed() { if (NULL != _ins) { delete _ins; _ins = NULL; } } MLog::MLog() : _priority(kDebug) , _performance(kNormal) , _pattern(kSyslog) { } MLog::~MLog() { } void MLog::init(const char *logfile, int priority, int performance) { if (logfile != NULL) { _logfile = logfile; _pattern = kFile; } _priority = priority; _performance = performance; } void MLog::initdir(const char *logdir, const char *prefix, int priority, int performance) { if (logdir != NULL) { _logdir = logdir; _pattern = kDir; } if (prefix != NULL) _prefix = prefix; _priority = priority; _performance = performance; } void MLog::log(const std::string &file, const std::string &func, uint32_t line, int pri, const char *__format, ...) { MScopedLock locker(_mutex); // according to pri if (pri > _priority) return; // combine log head std::string head; int len; std::string buffer; va_list vargs; va_start(vargs, __format); len = vsnprintf(NULL, 0, __format, vargs); buffer.resize(len); va_start(vargs, __format); vsnprintf(&buffer[0], len + 1, __format, vargs); va_end(vargs); // DATETIME HOSTNAME APPLICATIONNAME[PID] FILE FUNC[LINE] #if defined(_MSC_VER) || defined(M_OS_WIN) const char *fmt = "%s %s %s[%ld] %s %s[%u]: <%s> %s\n"; #else const char *fmt = "%s %s %s[%lld] %s %s[%u]: <%s> %s\n"; #endif std::string logstr = format(fmt, now().c_str(), hostname().c_str(), applicationName().c_str(), process::pid(), file.c_str(), func.c_str(), line, strpriority(pri).c_str(), buffer.c_str()); std::cout << logstr; switch (_pattern) { case kFile: logToFile(logstr); break; case kDir: logToDir(logstr); break; default: logToSyslog(logstr); break; } } std::string MLog::strpriority(int pri) const { std::string ret = "debug"; switch (pri) { case kEmerg: ret = "emerg"; break; case kAlert: ret = "alert"; break; case kCrit: ret = "crit"; break; case kError: ret = "error"; break; case kWarn: ret = "warn"; break; case kNotice: ret = "notice"; break; case kInfo: ret = "info"; break; default: break; } return ret; } void MLog::logToFile(const std::string &logstr) { file::appendbuf(_logfile.c_str(), logstr.c_str(), logstr.size()); } void MLog::logToDir(const std::string &logstr) { std::string logfile = _logdir + DIRECTORY_SEPARATOR + _prefix + MDateTime::currentDateTime().toString("%Y%m%d") + std::string(".log"); file::appendbuf(logfile.c_str(), logstr.c_str(), logstr.size()); } void MLog::logToSyslog(const std::string &logstr) { #ifdef M_OS_LINUX syslog(LOG_DEBUG, "%s", logstr.c_str()); #else OutputDebugString(logstr.c_str()); #endif } MPL_END_NAMESPACE #ifdef _MSC_VER # pragma warning (pop) #endif
i-black-angel/libpunica
src/mlog.cpp
C++
apache-2.0
3,839
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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 holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include <time.h> #include "Basics/system-functions.h" #include "Basics/tri-strings.h" #include "Replication/common-defines.h" namespace arangodb { /// @brief generate a timestamp string in a target buffer void TRI_GetTimeStampReplication(char* dst, size_t maxLength) { struct tm tb; time_t tt = time(nullptr); TRI_gmtime(tt, &tb); strftime(dst, maxLength, "%Y-%m-%dT%H:%M:%SZ", &tb); } /// @brief generate a timestamp string in a target buffer void TRI_GetTimeStampReplication(double timeStamp, char* dst, size_t maxLength) { struct tm tb; time_t tt = static_cast<time_t>(timeStamp); TRI_gmtime(tt, &tb); strftime(dst, maxLength, "%Y-%m-%dT%H:%M:%SZ", &tb); } bool TRI_ExcludeCollectionReplication(std::string const& name, bool includeSystem, bool includeFoxxQueues) { if (name.empty()) { // should not happen... return true; } if (name[0] != '_') { // all regular collections are included return false; } if (!includeSystem) { // do not include any system collections return true; } if (TRI_IsPrefixString(name.c_str(), "_statistics") || name == "_configuration" || name == "_frontend" || name == "_cluster_kickstarter_plans" || name == "_routing" || name == "_fishbowl" || name == "_foxxlog" || name == "_sessions") { // these system collections will always be excluded return true; } else if (!includeFoxxQueues && (name == "_jobs" || name == "_queues")) { return true; } return false; } } // namespace arangodb
fceller/arangodb
arangod/Replication/common-defines.cpp
C++
apache-2.0
2,510
package event import ( "time" "github.com/go-kit/kit/log" ) type logService struct { logger log.Logger next Service } // LogServiceMiddleware given a Logger wraps the next Service with logging capabilities. func LogServiceMiddleware(logger log.Logger, store string) ServiceMiddleware { return func(next Service) Service { logger = log.With( logger, "service", "event", "store", store, ) return &logService{logger: logger, next: next} } } func (s *logService) Count(ns string, opts QueryOptions) (count int, err error) { defer func(begin time.Time) { ps := []interface{}{ "count", count, "duration_ns", time.Since(begin).Nanoseconds(), "method", "Count", "namespace", ns, "opts", opts, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Count(ns, opts) } func (s *logService) Put(ns string, input *Event) (output *Event, err error) { defer func(begin time.Time) { ps := []interface{}{ "duration_ns", time.Since(begin).Nanoseconds(), "input", input, "method", "Put", "namespace", ns, "output", output, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Put(ns, input) } func (s *logService) Query(ns string, opts QueryOptions) (list List, err error) { defer func(begin time.Time) { ps := []interface{}{ "datapoints", len(list), "duration_ns", time.Since(begin).Nanoseconds(), "method", "Query", "namespace", ns, "opts", opts, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Query(ns, opts) } func (s *logService) Setup(ns string) (err error) { defer func(begin time.Time) { ps := []interface{}{ "duration_ns", time.Since(begin).Nanoseconds(), "method", "Setup", "namespace", ns, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Setup(ns) } func (s *logService) Teardown(ns string) (err error) { defer func(begin time.Time) { ps := []interface{}{ "duration_ns", time.Since(begin).Nanoseconds(), "method", "Teardown", "namespace", ns, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Teardown(ns) } type logSource struct { logger log.Logger next Source } // LogSourceMiddleware given a Logger wraps the next Source logging capabilities. func LogSourceMiddleware(store string, logger log.Logger) SourceMiddleware { return func(next Source) Source { logger = log.With( logger, "source", "event", "store", store, ) return &logSource{ logger: logger, next: next, } } } func (s *logSource) Ack(id string) (err error) { defer func(begin time.Time) { ps := []interface{}{ "ack_id", id, "duration_ns", time.Since(begin).Nanoseconds(), "method", "Ack", } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Ack(id) } func (s *logSource) Consume() (change *StateChange, err error) { defer func(begin time.Time) { ps := []interface{}{ "duration_ns", time.Since(begin).Nanoseconds(), "method", "Consume", } if change != nil { ps = append(ps, "namespace", change.Namespace, "event_new", change.New, "event_old", change.Old, ) } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Consume() } func (s *logSource) Propagate(ns string, old, new *Event) (id string, err error) { defer func(begin time.Time) { ps := []interface{}{ "duration_ns", time.Since(begin).Nanoseconds(), "id", id, "method", "Propagate", "namespace", ns, "event_new", new, "event_old", old, } if err != nil { ps = append(ps, "err", err) } _ = s.logger.Log(ps...) }(time.Now()) return s.next.Propagate(ns, old, new) }
tapglue/snaas
service/event/logging.go
GO
apache-2.0
3,954
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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. */ package com.amazonaws.services.cloudsearchv2.model.transform; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.cloudsearchv2.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * UpdateDomainEndpointOptionsResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateDomainEndpointOptionsResultStaxUnmarshaller implements Unmarshaller<UpdateDomainEndpointOptionsResult, StaxUnmarshallerContext> { public UpdateDomainEndpointOptionsResult unmarshall(StaxUnmarshallerContext context) throws Exception { UpdateDomainEndpointOptionsResult updateDomainEndpointOptionsResult = new UpdateDomainEndpointOptionsResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 2; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return updateDomainEndpointOptionsResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("DomainEndpointOptions", targetDepth)) { updateDomainEndpointOptionsResult.setDomainEndpointOptions(DomainEndpointOptionsStatusStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return updateDomainEndpointOptionsResult; } } } } private static UpdateDomainEndpointOptionsResultStaxUnmarshaller instance; public static UpdateDomainEndpointOptionsResultStaxUnmarshaller getInstance() { if (instance == null) instance = new UpdateDomainEndpointOptionsResultStaxUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-cloudsearch/src/main/java/com/amazonaws/services/cloudsearchv2/model/transform/UpdateDomainEndpointOptionsResultStaxUnmarshaller.java
Java
apache-2.0
2,682
import Observable from '../Observable'; import mergeStatic from './merge-static'; export default function merge<R>(...observables: (Observable<any>|number)[]): Observable<R> { observables.unshift(this); return mergeStatic.apply(this, observables); }
jaawerth/RxJS-1
src/operators/merge.ts
TypeScript
apache-2.0
254
package com.sissi.protocol.message; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlValue; import com.sissi.io.read.Metadata; /** * @author kim 2014年1月28日 */ @Metadata(uri = Message.XMLNS, localName = Thread.NAME) @XmlRootElement public class Thread { public final static String NAME = "thread"; private String text; private String parent; public Thread() { super(); } public Thread(String text) { super(); this.text = text; } public Thread(String text, String parent) { super(); this.text = text; this.parent = parent; } @XmlValue public String getText() { return this.text; } public Thread setText(String text) { this.text = text; return this; } @XmlAttribute public String getParent() { return this.parent; } public Thread setParent(String parent) { this.parent = parent; return this; } public boolean content() { return this.text != null && this.text.length() > 0; } }
KimShen/sissi
src/main/java/com/sissi/protocol/message/Thread.java
Java
apache-2.0
1,026
package instance import ( "io/ioutil" "os" "testing" "github.com/scaleway/scaleway-cli/internal/core" ) func Test_UserDataGet(t *testing.T) { t.Run("Get an existing key", core.Test(&core.TestConfig{ BeforeFunc: core.BeforeFuncCombine( createServer("Server"), core.ExecBeforeCmd("scw instance user-data set server-id={{.Server.ID}} key=happy content=true"), ), Commands: GetCommands(), Cmd: "scw instance user-data get server-id={{.Server.ID}} key=happy", AfterFunc: deleteServer("Server"), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), ), })) t.Run("Get an nonexistent key", core.Test(&core.TestConfig{ BeforeFunc: createServer("Server"), Commands: GetCommands(), Cmd: "scw instance user-data get server-id={{.Server.ID}} key=happy", AfterFunc: deleteServer("Server"), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(1), ), })) } func Test_UserDataList(t *testing.T) { t.Run("Simple", core.Test(&core.TestConfig{ BeforeFunc: core.BeforeFuncCombine( createServer("Server"), core.ExecBeforeCmd("scw instance user-data set server-id={{ .Server.ID }} key=foo content=bar"), core.ExecBeforeCmd("scw instance user-data set server-id={{ .Server.ID }} key=bar content=foo"), ), Commands: GetCommands(), Cmd: "scw instance user-data list server-id={{ .Server.ID }}", AfterFunc: deleteServer("Server"), Check: core.TestCheckCombine( core.TestCheckGolden(), core.TestCheckExitCode(0), ), })) } func Test_UserDataFileUpload(t *testing.T) { content := "cloud-init file content" t.Run("on-cloud-init", core.Test(&core.TestConfig{ Commands: GetCommands(), BeforeFunc: core.BeforeFuncCombine( core.ExecStoreBeforeCmd("Server", "scw instance server create stopped=true image=ubuntu-bionic"), func(ctx *core.BeforeFuncCtx) error { file, _ := ioutil.TempFile("", "test") _, _ = file.WriteString(content) ctx.Meta["filePath"] = file.Name() return nil }, ), Cmd: `scw instance user-data set key=cloud-init server-id={{ .Server.ID }} content=@{{ .filePath }}`, Check: core.TestCheckCombine( core.TestCheckGolden(), ), AfterFunc: core.AfterFuncCombine( func(ctx *core.AfterFuncCtx) error { _ = os.RemoveAll(ctx.Meta["filePath"].(string)) return nil }, ), })) t.Run("on-random-key", core.Test(&core.TestConfig{ Commands: GetCommands(), BeforeFunc: core.BeforeFuncCombine( core.ExecStoreBeforeCmd("Server", "scw instance server create stopped=true image=ubuntu-bionic"), func(ctx *core.BeforeFuncCtx) error { file, _ := ioutil.TempFile("", "test") _, _ = file.WriteString(content) ctx.Meta["filePath"] = file.Name() return nil }, ), Cmd: `scw instance user-data set key=foobar server-id={{ .Server.ID }} content=@{{ .filePath }}`, Check: core.TestCheckCombine( core.TestCheckGolden(), ), AfterFunc: core.AfterFuncCombine( func(ctx *core.AfterFuncCtx) error { _ = os.RemoveAll(ctx.Meta["filePath"].(string)) return nil }, ), })) }
scaleway/scaleway-cli
internal/namespaces/instance/v1/custom_user_data_test.go
GO
apache-2.0
3,105
using ArangoDB.Client.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArangoDB.Client { public class BaseResultAnalyzer { IArangoDatabase db; public BaseResultAnalyzer(IArangoDatabase db) { this.db = db; } public void ThrowIfNeeded(BaseResult baseResult) { if (baseResult.HasError() && db.Setting.ThrowForServerErrors == true) { throw new ArangoServerException(baseResult); } } public void Throw(BaseResult baseResult) { if (baseResult.HasError()) throw new ArangoServerException(baseResult); } } }
ra0o0f/arangoclient.net
src/ArangoDB.Client/BaseResultAnalyzer.cs
C#
apache-2.0
774
/** * Copyright (C) 2016 - 2030 youtongluan. * * 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.yx.asm; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.yx.bean.Loader; import org.yx.conf.AppInfo; import org.yx.exception.SumkException; import org.yx.log.Log; import org.yx.log.Logs; import org.yx.main.StartContext; public final class AsmUtils { private static Method defineClass; static { try { defineClass = getMethod(ClassLoader.class, "defineClass", new Class<?>[] { String.class, byte[].class, int.class, int.class }); defineClass.setAccessible(true); } catch (Exception e) { Log.printStack("sumk.error", e); StartContext.startFailed(); } } public static String proxyCalssName(Class<?> clz) { String name = clz.getName(); int index = name.lastIndexOf('.'); return name.substring(0, index) + ".sumkbox" + name.substring(index); } public static int asmVersion() { return AppInfo.getInt("sumk.asm.version", Opcodes.ASM7); } public static int jvmVersion() { return AppInfo.getInt("sumk.asm.jvm.version", Opcodes.V1_8); } public static InputStream openStreamForClass(String name) { String internalName = name.replace('.', '/') + ".class"; return Loader.getResourceAsStream(internalName); } public static boolean sameType(Type[] types, Class<?>[] clazzes) { if (types.length != clazzes.length) { return false; } for (int i = 0; i < types.length; i++) { if (!Type.getType(clazzes[i]).equals(types[i])) { return false; } } return true; } public static List<MethodParamInfo> buildMethodInfos(List<Method> methods) throws IOException { Map<Class<?>, List<Method>> map = new HashMap<>(); for (Method m : methods) { List<Method> list = map.get(m.getDeclaringClass()); if (list == null) { list = new ArrayList<>(); map.put(m.getDeclaringClass(), list); } list.add(m); } List<MethodParamInfo> ret = new ArrayList<>(); for (List<Method> ms : map.values()) { ret.addAll(buildMethodInfos(ms.get(0).getDeclaringClass(), ms)); } return ret; } private static List<MethodParamInfo> buildMethodInfos(Class<?> declaringClass, List<Method> methods) throws IOException { String classFullName = declaringClass.getName(); ClassReader cr = new ClassReader(openStreamForClass(classFullName)); MethodInfoClassVisitor cv = new MethodInfoClassVisitor(methods); cr.accept(cv, 0); return cv.getMethodInfos(); } public static Method getMethod(Class<?> clz, String methodName, Class<?>[] paramTypes) { while (clz != Object.class) { Method[] ms = clz.getDeclaredMethods(); for (Method m : ms) { if (!m.getName().equals(methodName)) { continue; } Class<?>[] paramTypes2 = m.getParameterTypes(); if (!Arrays.equals(paramTypes2, paramTypes)) { continue; } return m; } clz = clz.getSuperclass(); } return null; } public static Class<?> loadClass(String fullName, byte[] b) throws Exception { String clzOutPath = AppInfo.get("sumk.asm.debug.output"); if (clzOutPath != null && clzOutPath.length() > 0) { try { File f = new File(clzOutPath, fullName + ".class"); try (FileOutputStream fos = new FileOutputStream(f)) { fos.write(b); fos.flush(); } } catch (Exception e) { if (Logs.asm().isTraceEnabled()) { Logs.asm().error(e.getLocalizedMessage(), e); } } } synchronized (AsmUtils.class) { try { return Loader.loadClass(fullName); } catch (Throwable e) { if (!(e instanceof ClassNotFoundException)) { Logs.asm().warn(fullName + " 加载失败", e); } } Class<?> clz = (Class<?>) defineClass.invoke(Loader.loader(), fullName, b, 0, b.length); if (clz == null) { throw new SumkException(-235345436, "cannot load class " + fullName); } return clz; } } public static final int BADMODIFIERS = Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.PRIVATE; public static boolean notPublicOnly(int modifiers) { return (modifiers & (Modifier.PUBLIC | BADMODIFIERS)) != Modifier.PUBLIC; } public static boolean canProxy(int modifiers) { return (modifiers & BADMODIFIERS) == 0; } public static List<Object> getImplicitFrame(String desc) { List<Object> locals = new ArrayList<>(5); if (desc.isEmpty()) { return locals; } int i = 0; while (desc.length() > i) { int j = i; switch (desc.charAt(i++)) { case 'Z': case 'C': case 'B': case 'S': case 'I': locals.add(Opcodes.INTEGER); break; case 'F': locals.add(Opcodes.FLOAT); break; case 'J': locals.add(Opcodes.LONG); break; case 'D': locals.add(Opcodes.DOUBLE); break; case '[': while (desc.charAt(i) == '[') { ++i; } if (desc.charAt(i) == 'L') { ++i; while (desc.charAt(i) != ';') { ++i; } } locals.add(desc.substring(j, ++i)); break; case 'L': while (desc.charAt(i) != ';') { ++i; } locals.add(desc.substring(j + 1, i++)); break; default: break; } } return locals; } public static Method getSameMethod(Method method, Class<?> otherClass) { Class<?> clz = method.getDeclaringClass(); if (clz == otherClass) { return method; } String methodName = method.getName(); Class<?>[] argTypes = method.getParameterTypes(); Method[] proxyedMethods = otherClass.getMethods(); for (Method proxyedMethod : proxyedMethods) { if (proxyedMethod.getName().equals(methodName) && Arrays.equals(argTypes, proxyedMethod.getParameterTypes()) && !proxyedMethod.getDeclaringClass().isInterface()) { return proxyedMethod; } } return method; } }
youtongluan/sumk
src/main/java/org/yx/asm/AsmUtils.java
Java
apache-2.0
6,539
/********************************************************************** Copyright (c) 2009 Stefan Seelmann. 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 com.example.dao; import java.util.Collection; import com.example.Team; public class TeamDao extends AbstractDao<Team> { public Collection<Team> findByName( String name ) { return super.findByQuery( "name.startsWith(s1)", "java.lang.String s1", name ); } public Team loadWithUsers( Object id ) { return super.load( id, "users" ); } public Team load( Object id ) { return super.load( id ); } public Collection<Team> loadAll() { return super.loadAll(); } }
seelmann/ldapcon2009-datanucleus
DataNucleus-Advanced/src/main/java/com/example/dao/TeamDao.java
Java
apache-2.0
1,280
# Copyright 2015 Google 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. require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module LifesciencesV2beta # Cloud Life Sciences API # # Cloud Life Sciences is a suite of services and tools for managing, processing, # and transforming life sciences data. # # @example # require 'google/apis/lifesciences_v2beta' # # Lifesciences = Google::Apis::LifesciencesV2beta # Alias the module # service = Lifesciences::CloudLifeSciencesService.new # # @see https://cloud.google.com/life-sciences class CloudLifeSciencesService < Google::Apis::Core::BaseService # @return [String] # API key. Your API key identifies your project and provides you with API access, # quota, and reports. Required unless you provide an OAuth 2.0 token. attr_accessor :key # @return [String] # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. attr_accessor :quota_user def initialize super('https://lifesciences.googleapis.com/', '') @batch_path = 'batch' end # Gets information about a location. # @param [String] name # Resource name for the location. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::Location] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::Location] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_project_location(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v2beta/{+name}', options) command.response_representation = Google::Apis::LifesciencesV2beta::Location::Representation command.response_class = Google::Apis::LifesciencesV2beta::Location command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists information about the supported locations for this service. # @param [String] name # The resource that owns the locations collection, if applicable. # @param [String] filter # The standard list filter. # @param [Fixnum] page_size # The standard list page size. # @param [String] page_token # The standard list page token. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::ListLocationsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::ListLocationsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_project_locations(name, filter: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v2beta/{+name}/locations', options) command.response_representation = Google::Apis::LifesciencesV2beta::ListLocationsResponse::Representation command.response_class = Google::Apis::LifesciencesV2beta::ListLocationsResponse command.params['name'] = name unless name.nil? command.query['filter'] = filter unless filter.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Starts asynchronous cancellation on a long-running operation. The server makes # a best effort to cancel the operation, but success is not guaranteed. Clients # may use Operations.GetOperation or Operations.ListOperations to check whether # the cancellation succeeded or the operation completed despite cancellation. # Authorization requires the following [Google IAM](https://cloud.google.com/iam) # permission: * `lifesciences.operations.cancel` # @param [String] name # The name of the operation resource to be cancelled. # @param [Google::Apis::LifesciencesV2beta::CancelOperationRequest] cancel_operation_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::Empty] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::Empty] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def cancel_operation(name, cancel_operation_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v2beta/{+name}:cancel', options) command.request_representation = Google::Apis::LifesciencesV2beta::CancelOperationRequest::Representation command.request_object = cancel_operation_request_object command.response_representation = Google::Apis::LifesciencesV2beta::Empty::Representation command.response_class = Google::Apis::LifesciencesV2beta::Empty command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Gets the latest state of a long-running operation. Clients can use this method # to poll the operation result at intervals as recommended by the API service. # Authorization requires the following [Google IAM](https://cloud.google.com/iam) # permission: * `lifesciences.operations.get` # @param [String] name # The name of the operation resource. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def get_project_location_operation(name, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v2beta/{+name}', options) command.response_representation = Google::Apis::LifesciencesV2beta::Operation::Representation command.response_class = Google::Apis::LifesciencesV2beta::Operation command.params['name'] = name unless name.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Lists operations that match the specified filter in the request. Authorization # requires the following [Google IAM](https://cloud.google.com/iam) permission: * # `lifesciences.operations.list` # @param [String] name # The name of the operation's parent resource. # @param [String] filter # A string for filtering Operations. The following filter fields are supported: * # createTime: The time this job was created * events: The set of event (names) # that have occurred while running the pipeline. The : operator can be used to # determine if a particular event has occurred. * error: If the pipeline is # running, this value is NULL. Once the pipeline finishes, the value is the # standard Google error code. * labels.key or labels."key with space" where key # is a label key. * done: If the pipeline is running, this value is false. Once # the pipeline finishes, the value is true. # @param [Fixnum] page_size # The maximum number of results to return. The maximum value is 256. # @param [String] page_token # The standard list page token. # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::ListOperationsResponse] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::ListOperationsResponse] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def list_project_location_operations(name, filter: nil, page_size: nil, page_token: nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:get, 'v2beta/{+name}/operations', options) command.response_representation = Google::Apis::LifesciencesV2beta::ListOperationsResponse::Representation command.response_class = Google::Apis::LifesciencesV2beta::ListOperationsResponse command.params['name'] = name unless name.nil? command.query['filter'] = filter unless filter.nil? command.query['pageSize'] = page_size unless page_size.nil? command.query['pageToken'] = page_token unless page_token.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end # Runs a pipeline. The returned Operation's metadata field will contain a google. # cloud.lifesciences.v2beta.Metadata object describing the status of the # pipeline execution. The response field will contain a google.cloud. # lifesciences.v2beta.RunPipelineResponse object if the pipeline completes # successfully. **Note:** Before you can use this method, the *Life Sciences # Service Agent* must have access to your project. This is done automatically # when the Cloud Life Sciences API is first enabled, but if you delete this # permission you must disable and re-enable the API to grant the Life Sciences # Service Agent the required permissions. Authorization requires the following [ # Google IAM](https://cloud.google.com/iam/) permission: * `lifesciences. # workflows.run` # @param [String] parent # The project and location that this request should be executed against. # @param [Google::Apis::LifesciencesV2beta::RunPipelineRequest] run_pipeline_request_object # @param [String] fields # Selector specifying which fields to include in a partial response. # @param [String] quota_user # Available to use for quota purposes for server-side applications. Can be any # arbitrary string assigned to a user, but should not exceed 40 characters. # @param [Google::Apis::RequestOptions] options # Request-specific options # # @yield [result, err] Result & error if block supplied # @yieldparam result [Google::Apis::LifesciencesV2beta::Operation] parsed result object # @yieldparam err [StandardError] error object if request failed # # @return [Google::Apis::LifesciencesV2beta::Operation] # # @raise [Google::Apis::ServerError] An error occurred on the server and the request can be retried # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def run_pipeline(parent, run_pipeline_request_object = nil, fields: nil, quota_user: nil, options: nil, &block) command = make_simple_command(:post, 'v2beta/{+parent}/pipelines:run', options) command.request_representation = Google::Apis::LifesciencesV2beta::RunPipelineRequest::Representation command.request_object = run_pipeline_request_object command.response_representation = Google::Apis::LifesciencesV2beta::Operation::Representation command.response_class = Google::Apis::LifesciencesV2beta::Operation command.params['parent'] = parent unless parent.nil? command.query['fields'] = fields unless fields.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? execute_or_queue_command(command, &block) end protected def apply_command_defaults(command) command.query['key'] = key unless key.nil? command.query['quotaUser'] = quota_user unless quota_user.nil? end end end end end
googleapis/google-api-ruby-client
google-api-client/generated/google/apis/lifesciences_v2beta/service.rb
Ruby
apache-2.0
17,086
package com.metrink.action; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Provider; import com.metrink.alert.ActionBean; import com.metrink.alert.AlertBean; import com.metrink.metric.Metric; /** * The base action for all SMS actions. * * A list of gateways can be found here: http://www.emailtextmessages.com/ * */ public abstract class SmsAction implements Action { private static final Logger LOG = LoggerFactory.getLogger(SmsAction.class); private final Provider<SimpleEmail> emailProvider; public SmsAction(final Provider<SimpleEmail> emailProvider) { this.emailProvider = emailProvider; } @Override public void triggerAction(Metric metric, AlertBean alertBean, ActionBean actionBean) { final String toAddr = constructAddress(actionBean.getValue()); final String alertQuery = alertBean.getAlertQuery().substring(0, alertBean.getAlertQuery().lastIndexOf(" do ")); final StringBuilder sb = new StringBuilder(); sb.append(metric.getId()); sb.append(" "); sb.append(metric.getValue()); sb.append(" triggered "); sb.append(alertQuery); try { final SimpleEmail email = emailProvider.get(); email.addTo(toAddr); email.setSubject("METRINK Alert"); email.setMsg(sb.toString()); final String messageId = email.send(); LOG.info("Sent message {} to {}", messageId, toAddr); } catch (final EmailException e) { LOG.error("Error sending email: {}", e.getMessage()); } } /** * Given a phone number, create the address for the gateway. * @param phoneNumber the phone number. * @return the email address to use. */ protected abstract String constructAddress(String phoneNumber); }
Metrink/metrink
src/main/java/com/metrink/action/SmsAction.java
Java
apache-2.0
1,947
/** * Copyright 2017-2019 The GreyCat Authors. All rights reserved. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 greycat.internal.task; import greycat.*; import greycat.base.BaseNode; import greycat.plugin.Job; import greycat.struct.Buffer; class ActionDelete implements Action { @Override public void eval(final TaskContext ctx) { TaskResult previous = ctx.result(); DeferCounter counter = ctx.graph().newCounter(previous.size()); for (int i = 0; i < previous.size(); i++) { if (previous.get(i) instanceof BaseNode) { ((Node) previous.get(i)).drop(new Callback() { @Override public void on(Object result) { counter.count(); } }); } } counter.then(new Job() { @Override public void run() { previous.clear(); ctx.continueTask(); } }); } @Override public void serialize(final Buffer builder) { builder.writeString(CoreActionNames.DELETE); builder.writeChar(Constants.TASK_PARAM_OPEN); builder.writeChar(Constants.TASK_PARAM_CLOSE); } @Override public final String name() { return CoreActionNames.DELETE; } }
datathings/greycat
greycat/src/main/java/greycat/internal/task/ActionDelete.java
Java
apache-2.0
1,871
//Declare app level module which depends on filters, and services var SFApplicationAuth = angular.module('SFApplicationAuth.Auth',[]); SFApplicationAuth.config( [ '$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider ) { console.log("inciando bootstrap auth"); $stateProvider.state('auth', { url: '/auth', abstract: true, templateUrl: 'modules/auth/partials/template.html', data: { isPublic: true } }); $stateProvider.state('auth.login', { url: '/login', templateUrl: 'modules/auth/partials/login.html', controller: 'AuthController' }); $stateProvider.state('auth.logout', { url: '/logout', controller: 'LogoutController' }); $stateProvider.state('auth.reset-password', { url: '/reset-password', templateUrl: 'application/auth/partials/reset-password.html', controller: 'AuthController' }); }]); SFApplicationAuth.run(['$rootScope', '$state', '$location', '$log', 'authFactory', function($rootScope, $state, $location, $log, authFactory) { $log.log('Running Auth...'); $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { $log.log('$stateChangeStart'); if( toState && ( "data" in toState ) === true && ( "isPublic" in toState.data ) === true && toState.data.isPublic == true ) { $log.log( 'Public page...' ); } else if( toState && ( "data" in toState ) === true && ( ( "isPublic" in toState.data ) === false || ( "isPublic" in toState.data ) === true && toState.data.isPublic == false ) ) { $log.log( 'Private page...' ); /** * Check if has some webSession active and do the logout. */ if( ! authFactory.checkIsLogged() ) { $log.error( 'You don\'t have permission to access this area.' ); /** * Prevent Default action. */ event.preventDefault(); $log.log( 'Fazendo loggof' ); /** * Redirect to login */ $state.go( 'auth.logout' ); } } }); $rootScope.$on('$stateChangeSuccess', function(next, current) { $log.log('$stateChangeSuccess'); }); $rootScope.$on('$stateChangeError', function( event, toState, toParams, fromState, fromParams, rejection) { $log.log('$stateChangeError'); }); $rootScope.$on('$stateUpdate', function(next, current) { $log.log('$stateUpdate'); }); $rootScope.$on('$stateNotFound', function(event, unfoundState, fromState, fromParams){ $log.log('$stateNotFound'); $log.log(unfoundState.to); // "lazy.state" $log.log(unfoundState.toParams); // {a:1, b:2} $log.log(unfoundState.options); // {inherit:false} + default options }); $rootScope.$on('$viewContentLoading', function(event, viewConfig){ $log.log('$viewContentLoading'); }); $rootScope.$on('$viewContentLoaded', function(event, viewConfig){ $log.log('$viewContentLoaded'); }); }]);
chacal88/sb-admin-angular
app/modules/auth/application/bootstrap.js
JavaScript
apache-2.0
2,840
package com.at.springboot.mybatis.po; public class JsonUser { /** * This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.JSON_USER_ID * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ private byte[] jsonUserId; /** * This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.USER_NAME * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ private String userName; /** * This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.LAST_LOGIN_RESULT * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ private String lastLoginResult; /** * This field was generated by MyBatis Generator. This field corresponds to the database column JSON_USER.LAST_LOGIN_INFO * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ private String lastLoginInfo; /** * This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.JSON_USER_ID * @return the value of JSON_USER.JSON_USER_ID * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public byte[] getJsonUserId() { return jsonUserId; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.JSON_USER_ID * @param jsonUserId the value for JSON_USER.JSON_USER_ID * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public void setJsonUserId(byte[] jsonUserId) { this.jsonUserId = jsonUserId; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.USER_NAME * @return the value of JSON_USER.USER_NAME * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public String getUserName() { return userName; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.USER_NAME * @param userName the value for JSON_USER.USER_NAME * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.LAST_LOGIN_RESULT * @return the value of JSON_USER.LAST_LOGIN_RESULT * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public String getLastLoginResult() { return lastLoginResult; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.LAST_LOGIN_RESULT * @param lastLoginResult the value for JSON_USER.LAST_LOGIN_RESULT * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public void setLastLoginResult(String lastLoginResult) { this.lastLoginResult = lastLoginResult == null ? null : lastLoginResult.trim(); } /** * This method was generated by MyBatis Generator. This method returns the value of the database column JSON_USER.LAST_LOGIN_INFO * @return the value of JSON_USER.LAST_LOGIN_INFO * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public String getLastLoginInfo() { return lastLoginInfo; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column JSON_USER.LAST_LOGIN_INFO * @param lastLoginInfo the value for JSON_USER.LAST_LOGIN_INFO * @mbg.generated Thu Aug 29 17:59:18 CST 2019 */ public void setLastLoginInfo(String lastLoginInfo) { this.lastLoginInfo = lastLoginInfo == null ? null : lastLoginInfo.trim(); } }
alphatan/workspace_java
spring-boot-web-fps-demo/src/main/java/com/at/springboot/mybatis/po/JsonUser.java
Java
apache-2.0
3,937
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.stylehair.servicos; import br.com.stylehair.dao.AgendamentoDAO; import br.com.stylehair.entity.Agendamento; import com.google.gson.Gson; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; /** * * @author vinicius */ @Stateless @Path("agendamento") public class AgendamentoResource { @PersistenceContext(unitName = "StyleHairPU") private EntityManager em; private Gson gson = new Gson(); @Context private UriInfo context; @GET @Produces("application/json") public String getJson() { AgendamentoDAO dao = new AgendamentoDAO(em); List<Agendamento> agendamentos; agendamentos = dao.buscarTodosAgendamentos(); return gson.toJson(agendamentos); } @GET @Path("{agendamentoId}") @Produces("application/json") public String getAgendamento(@PathParam("agendamentoId") String id){ System.out.println("pegando o cliente"); Long n = Long.parseLong(id); System.out.println(n); AgendamentoDAO dao = new AgendamentoDAO(em); Agendamento agend = dao.consultarPorId(Agendamento.class, Long.parseLong(id)); return gson.toJson(agend); } @GET @Path("{buscardata}/{dia}/{mes}/{ano}") @Produces("application/json") public String getAgendamentoPorData(@PathParam("dia") String dia,@PathParam("mes") String mes,@PathParam("ano") String ano ) { AgendamentoDAO dao = new AgendamentoDAO(em); List<Agendamento> agendamentos; SimpleDateFormat dateFormat_hora = new SimpleDateFormat("HH:mm"); Date data = new Date(); String horaAtual = dateFormat_hora.format(data); System.out.println("hora Atual" + horaAtual); Date d1 = new Date(); SimpleDateFormat dateFormataData = new SimpleDateFormat("dd/MM/yyyy"); String dataHoje = dateFormataData.format(d1); System.out.println("dataHoje ----" + dataHoje + "-------- " + dia+"/"+mes+"/"+ano ); if(dataHoje.equalsIgnoreCase(dia+"/"+mes+"/"+ano)){ agendamentos = dao.buscarAgendamentoPorData(dia+"/"+mes+"/"+ano + " ",horaAtual); return gson.toJson(agendamentos); } agendamentos = dao.buscarAgendamentoPorData(dia+"/"+mes+"/"+ano + " ","08:00"); return gson.toJson(agendamentos); } @POST @Consumes("application/json") @Produces("application/json") public String salvarAgendamento(String agendamento) throws Exception{ Agendamento ag1 = gson.fromJson(agendamento, Agendamento.class); AgendamentoDAO dao = new AgendamentoDAO(em); return gson.toJson(dao.salvar(ag1)); } @PUT @Consumes("application/json") public void atualizarAgendamento(String agendamento) throws Exception { salvarAgendamento(agendamento); } }
ViniciusBezerra94/WsStyleHair
src/main/java/br/com/stylehair/servicos/AgendamentoResource.java
Java
apache-2.0
3,529
const spinny = 'div.spinny'; exports.command = function navigateTo (url, expectSpinny = true) { this.url('data:,'); // https://github.com/nightwatchjs/nightwatch/issues/1724 this.url(url); if (expectSpinny) { this.waitForElementVisible(spinny); this.waitForElementNotVisible(spinny); } return this; };
wwitzel3/awx
awx/ui/test/e2e/commands/navigateTo.js
JavaScript
apache-2.0
341
package com.sampleapp.base; import android.app.Application; import com.crashlytics.android.Crashlytics; import com.sampleapp.BuildConfig; import com.sampleapp.utils.UtilsModule; import io.fabric.sdk.android.Fabric; import timber.log.Timber; /** * Created by saveen_dhiman on 05-November-16. * Initialization of required libraries */ public class SampleApplication extends Application { private AppComponent mAppComponent; @Override public void onCreate() { super.onCreate(); Fabric.with(this, new Crashlytics()); //create component mAppComponent = DaggerAppComponent.builder() .utilsModule(new UtilsModule(this)).build(); //configure timber for logging if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } } public AppComponent getAppComponent() { return mAppComponent; } }
saveendhiman/SampleApp
app/src/main/java/com/sampleapp/base/SampleApplication.java
Java
apache-2.0
915
/* * Copyright 2017 Axway Software * * 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.axway.ats.core.filesystem.exceptions; import java.io.File; import com.axway.ats.common.filesystem.FileSystemOperationException; /** * Exception thrown when a file does not exist */ @SuppressWarnings( "serial") public class FileDoesNotExistException extends FileSystemOperationException { /** * Constructor * * @param fileName name of the file which does not exist */ public FileDoesNotExistException( String fileName ) { super("File '" + fileName + "' does not exist"); } /** * Constructor * * @param file the file which does not exist */ public FileDoesNotExistException( File file ) { super("File '" + file.getPath() + "' does not exist"); } }
Axway/ats-framework
corelibrary/src/main/java/com/axway/ats/core/filesystem/exceptions/FileDoesNotExistException.java
Java
apache-2.0
1,344
package com.fasterxml.jackson.databind.node; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.io.NumberOutput; import com.fasterxml.jackson.databind.SerializerProvider; /** * Numeric node that contains simple 32-bit integer values. */ @SuppressWarnings("serial") public class IntNode extends NumericNode { // // // Let's cache small set of common value final static int MIN_CANONICAL = -1; final static int MAX_CANONICAL = 10; private final static IntNode[] CANONICALS; static { int count = MAX_CANONICAL - MIN_CANONICAL + 1; CANONICALS = new IntNode[count]; for (int i = 0; i < count; ++i) { CANONICALS[i] = new IntNode(MIN_CANONICAL + i); } } /** * Integer value this node contains */ protected final int _value; /* ************************************************ * Construction ************************************************ */ public IntNode(int v) { _value = v; } public static IntNode valueOf(int i) { if (i > MAX_CANONICAL || i < MIN_CANONICAL) return new IntNode(i); return CANONICALS[i - MIN_CANONICAL]; } /* /********************************************************** /* BaseJsonNode extended API /********************************************************** */ @Override public JsonToken asToken() { return JsonToken.VALUE_NUMBER_INT; } @Override public JsonParser.NumberType numberType() { return JsonParser.NumberType.INT; } /* /********************************************************** /* Overrridden JsonNode methods /********************************************************** */ @Override public boolean isIntegralNumber() { return true; } @Override public boolean isInt() { return true; } @Override public boolean canConvertToInt() { return true; } @Override public boolean canConvertToLong() { return true; } @Override public Number numberValue() { return Integer.valueOf(_value); } @Override public short shortValue() { return (short) _value; } @Override public int intValue() { return _value; } @Override public long longValue() { return (long) _value; } @Override public float floatValue() { return (float) _value; } @Override public double doubleValue() { return (double) _value; } @Override public BigDecimal decimalValue() { return BigDecimal.valueOf(_value); } @Override public BigInteger bigIntegerValue() { return BigInteger.valueOf(_value); } @Override public String asText() { return NumberOutput.toString(_value); } @Override public boolean asBoolean(boolean defaultValue) { return _value != 0; } @Override public final void serialize(JsonGenerator g, SerializerProvider provider) throws IOException { g.writeNumber(_value); } @Override public boolean equals(Object o) { if (o == this) return true; if (o == null) return false; if (o instanceof IntNode) { return ((IntNode) o)._value == _value; } return false; } @Override public int hashCode() { return _value; } }
FasterXML/jackson-databind
src/main/java/com/fasterxml/jackson/databind/node/IntNode.java
Java
apache-2.0
3,398
package lena.lerning.selenium; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.concurrent.TimeUnit; import static org.openqa.selenium.support.ui.ExpectedConditions.titleContains; /** * Created by Lena on 01/05/2017. */ public class EdgeTest { private WebDriver driver; private WebDriverWait wait; @Before public void edgeStart(){ driver = new EdgeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @Test public void firstTest(){ driver.get("http://www.google.com"); driver.findElement(By.name("q")).sendKeys("webdriver"); driver.findElement(By.name("q")).sendKeys(Keys.ENTER); wait.until(titleContains("webdriver")); } @After public void stop(){ driver.quit(); driver=null; } }
etarnovskaya/sel_6_Lena
sel-test/src/test/java/lena/lerning/selenium/EdgeTest.java
Java
apache-2.0
1,062
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * 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.kuali.kra.common.notification.exception; /** * This exception is thrown if the given role id is not known to the given context. */ public class UnknownRoleException extends Exception { private static final long serialVersionUID = -1925770520412550327L; private final String roleId; private final String context; /** * Constructs an Unknown Role exception. * * @param roleId * @param context */ public UnknownRoleException(final String roleId, final String context) { super("Role " + roleId + " not recognized for context " + context); this.roleId = roleId; this.context = context; } public String getRoleId() { return roleId; } public String getContext() { return context; } }
vivantech/kc_fixes
src/main/java/org/kuali/kra/common/notification/exception/UnknownRoleException.java
Java
apache-2.0
1,435
package org.develnext.jphp.android.ext.classes.app; import android.os.Bundle; import org.develnext.jphp.android.AndroidStandaloneLoader; import org.develnext.jphp.android.ext.AndroidExtension; import php.runtime.annotation.Reflection; @Reflection.Name(AndroidExtension.NAMESPACE + "app\\BootstrapActivity") public class WrapBootstrapActivity extends WrapActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreateClearly(savedInstanceState); AndroidStandaloneLoader.INSTANCE.run(this); getEnvironment().invokeMethodNoThrow(this, "onCreate"); } }
livingvirus/jphp
jphp-android/src/main/java/org/develnext/jphp/android/ext/classes/app/WrapBootstrapActivity.java
Java
apache-2.0
616
package com.truward.brikar.maintenance.log.processor; import com.truward.brikar.common.log.LogUtil; import com.truward.brikar.maintenance.log.CommaSeparatedValueParser; import com.truward.brikar.maintenance.log.Severity; import com.truward.brikar.maintenance.log.message.LogMessage; import com.truward.brikar.maintenance.log.message.MaterializedLogMessage; import com.truward.brikar.maintenance.log.message.MultiLinePartLogMessage; import com.truward.brikar.maintenance.log.message.NullLogMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Message processor that converts a line into a message. * * @author Alexander Shabanov */ @ParametersAreNonnullByDefault public final class LogMessageProcessor { public static final Pattern RECORD_PATTERN = Pattern.compile( "^(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}) " + // date+time "(\\p{Upper}+) " + // severity "([\\w\\p{Punct}]+) " + // class name "((?:[\\w]+=[\\w\\+/.\\$]+)(?:, (?:[\\w]+=[\\w\\+/\\.\\$]+))*)? " + // variables "\\[[\\w\\p{Punct}&&[^\\]]]+\\] " + // thread ID "(.+)" + // message "$" ); private static final String METRIC_MARKER = LogUtil.METRIC_ENTRY + ' '; private final Logger log = LoggerFactory.getLogger(getClass()); private final DateFormat dateFormat; public LogMessageProcessor() { this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } public LogMessage parse(String line, LogMessage previousMessage) { if (previousMessage.hasMetrics() && line.startsWith("\t")) { // special case: this line is a continuation of metrics entry started on the previous line final MaterializedLogMessage logMessage = new MaterializedLogMessage(previousMessage.getUnixTime(), previousMessage.getSeverity(), line); addAttributesFromMetrics(logMessage, line.substring(1)); return logMessage; } final Matcher matcher = RECORD_PATTERN.matcher(line); if (!matcher.matches()) { return new MultiLinePartLogMessage(line); } if (matcher.groupCount() < 5) { log.error("Count of groups is not six: actual={} for line={}", matcher.groupCount(), line); return NullLogMessage.INSTANCE; // should not happen } final Date date; try { date = dateFormat.parse(matcher.group(1)); } catch (ParseException e) { log.error("Malformed date in line={}", line, e); return NullLogMessage.INSTANCE; // should not happen } final Severity severity = Severity.fromString(matcher.group(2), Severity.WARN); final MaterializedLogMessage logMessage = new MaterializedLogMessage(date.getTime(), severity, line); addAttributesFromVariables(logMessage, matcher.group(4)); final String message = matcher.group(5); if (message != null) { final int metricIndex = message.indexOf(METRIC_MARKER); if (metricIndex >= 0) { addAttributesFromMetrics(logMessage, message.substring(metricIndex + METRIC_MARKER.length())); } } return logMessage; } // // Private // private void addAttributesFromMetrics(MaterializedLogMessage logMessage, String metricBody) { putAllAttributes(logMessage, new CommaSeparatedValueParser(metricBody).readAsMap()); } private void addAttributesFromVariables(MaterializedLogMessage logMessage, @Nullable String variables) { if (variables != null) { putAllAttributes(logMessage, new CommaSeparatedValueParser(variables).readAsMap()); } } private void putAllAttributes(MaterializedLogMessage logMessage, Map<String, String> vars) { for (final Map.Entry<String, String> entry : vars.entrySet()) { final String key = entry.getKey(); final Object value; if (LogUtil.TIME_DELTA.equals(key)) { value = Long.parseLong(entry.getValue()); } else if (LogUtil.START_TIME.equals(key)) { value = Long.parseLong(entry.getValue()); } else if (LogUtil.COUNT.equals(key)) { value = Long.parseLong(entry.getValue()); } else if (LogUtil.FAILED.equals(key)) { value = Boolean.valueOf(entry.getValue()); } else { value = entry.getValue(); } logMessage.putAttribute(key, value); } } }
truward/brikar
brikar-maintenance/src/main/java/com/truward/brikar/maintenance/log/processor/LogMessageProcessor.java
Java
apache-2.0
4,636
using UnityEngine; using System.Collections; namespace MagicalFX { public class FX_SpawnDirection : MonoBehaviour { public int Number = 10; public float Frequency = 1; public bool FixRotation = false; public bool Normal; public GameObject FXSpawn; public float LifeTime = 0; public float TimeSpawn = 0; private float timeTemp; public bool UseObjectForward = true; public Vector3 Direction = Vector3.forward; void Start () { counter = 0; timeTemp = Time.time; if (TimeSpawn <= 0) { for (int i=0; i<Number-1; i++) { if (UseObjectForward) { Direction = this.transform.forward; } Spawn (this.transform.position + (Direction * Frequency * i)); } Destroy(this.gameObject); } } private int counter = 0; void Update () { if(counter >= Number-1) Destroy(this.gameObject); if (TimeSpawn > 0.0f) { if (Time.time > timeTemp + TimeSpawn) { if (UseObjectForward) { Direction = this.transform.forward; } Spawn (this.transform.position + (Direction * Frequency * counter)); counter+=1; timeTemp = Time.time; } } } void Spawn (Vector3 position) { if (FXSpawn != null) { Quaternion rotate = this.transform.rotation; if (!FixRotation) rotate = FXSpawn.transform.rotation; GameObject fx = (GameObject)GameObject.Instantiate (FXSpawn, position, rotate); if (Normal) fx.transform.forward = this.transform.forward; if (LifeTime > 0) GameObject.Destroy (fx.gameObject, LifeTime); } } } }
yimogod/boom
trunk/effect/Assets/Magical/Sources/Scripts/FX_SpawnDirection.cs
C#
apache-2.0
1,578
package ru.job4j.servlet.services; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.job4j.servlet.model.User; import ru.job4j.servlet.repository.RepositoryException; import ru.job4j.servlet.repository.UserStore; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * UpdateUserController. * * @author Stanislav (376825@mail.ru) * @since 11.01.2018 */ public class UpdateUserController extends HttpServlet { private static final Logger LOG = LoggerFactory.getLogger(UpdateUserController.class); private static final long serialVersionUID = 6328444530140780881L; private UserStore userStore = UserStore.getInstance(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { User user = userStore.findByID(Integer.valueOf(req.getParameter("id"))); if (user != null) { String name = req.getParameter("name"); String login = req.getParameter("login"); String email = req.getParameter("email"); if (name != null && !name.trim().isEmpty()) { user.setName(name); } if (login != null && !login.trim().isEmpty()) { user.setLogin(login); } if (email != null && !email.trim().isEmpty()) { user.setEmail(email); } userStore.update(user); } } catch (NumberFormatException e) { LOG.error("Not the correct format id. ", e); } catch (RepositoryException e) { LOG.error("Error adding user. ", e); } resp.sendRedirect(req.getContextPath().length() == 0 ? "/" : req.getContextPath()); } }
StanislavEsin/estanislav
chapter_007/src/main/java/ru/job4j/servlet/services/UpdateUserController.java
Java
apache-2.0
1,967
package com.kenshin.windystreet.db; import org.litepal.crud.DataSupport; /** * Created by Kenshin on 2017/4/3. */ public class County extends DataSupport { private int id; //编号 private String countyName; //县名 private String weatherId; //对应的天气id private int cityId; //所属市的id public void setId(int id) { this.id = id; } public void setCountyName(String countyName) { this.countyName = countyName; } public void setWeatherId(String weatherId) { this.weatherId = weatherId; } public void setCityId(int cityId) { this.cityId = cityId; } public int getId() { return id; } public String getCountyName() { return countyName; } public String getWeatherId() { return weatherId; } public int getCityId() { return cityId; } }
Asucanc/Windy-Street-Weather
app/src/main/java/com/kenshin/windystreet/db/County.java
Java
apache-2.0
901
/* * Copyright 2016-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.core.model.actiongraph; import com.facebook.buck.core.rules.BuildRuleResolver; import com.facebook.buck.core.util.immutables.BuckStyleImmutable; import org.immutables.value.Value; /** Holds an ActionGraph with the BuildRuleResolver that created it. */ @Value.Immutable @BuckStyleImmutable interface AbstractActionGraphAndResolver { @Value.Parameter ActionGraph getActionGraph(); @Value.Parameter BuildRuleResolver getResolver(); }
LegNeato/buck
src/com/facebook/buck/core/model/actiongraph/AbstractActionGraphAndResolver.java
Java
apache-2.0
1,075
package water.api; import org.reflections.Reflections; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import hex.schemas.ModelBuilderSchema; import water.DKV; import water.H2O; import water.Iced; import water.Job; import water.Key; import water.Value; import water.exceptions.H2OIllegalArgumentException; import water.exceptions.H2OKeyNotFoundArgumentException; import water.exceptions.H2ONotFoundArgumentException; import water.fvec.Frame; import water.util.IcedHashMap; import water.util.Log; import water.util.MarkdownBuilder; import water.util.Pair; import water.util.PojoUtils; import water.util.ReflectionUtils; /** * Base Schema class; all REST API Schemas inherit from here. * <p> * The purpose of Schemas is to provide a stable, versioned interface to * the functionality in H2O, which allows the back end implementation to * change rapidly without breaking REST API clients such as the Web UI * and R and Python bindings. Schemas also allow for functionality which exposes the * schema metadata to clients, allowing them to do service discovery and * to adapt dynamically to new H2O functionality, e.g. to be able to call * any ModelBuilder, even new ones written since the client was built, * without knowing any details about the specific algo. * <p> * In most cases, Java developers who wish to expose new functionality through the * REST API will need only to define their schemas with the fields that they * wish to expose, adding @API annotations to denote the field metadata. * Their fields will be copied back and forth through the reflection magic in this * class. If there are fields they have to adapt between the REST API representation * and the back end this can be done piecemeal by overriding the fill* methods, calling * the versions in super, and making only those changes that are absolutely necessary. * A lot of work has gone into avoiding boilerplate code. * <p> * Schemas are versioned for stability. When you look up the schema for a given impl * object or class you supply a version number. If a schema for that version doesn't * exist then the versions are searched in reverse order. For example, if you ask for * version 5 and the highest schema version for that impl class is 3 then V3 will be returned. * This allows us to move to higher versions without having to write gratuitous new schema * classes for the things that haven't changed in the new version. * <p> * The current version can be found by calling * Schema.getHighestSupportedVersion(). For schemas that are still in flux * because development is ongoing we also support an EXPERIMENTAL_VERSION, which * indicates that there are no interface stability guarantees between H2O versions. * Eventually these schemas will move to a normal, stable version number. Call * Schema.getExperimentalVersion() to find the experimental version number (99 as * of this writing). * <p> * Schema names must be unique within an application in a single namespace. The * class getSimpleName() is used as the schema name. During Schema discovery and * registration there are checks to ensure that the names are unique. * <p> * Most schemas have a 1-to-1 mapping to an Iced implementation object, aka the "impl" * or implementation class. This class is specified as a type parameter to the Schema class. * This type parameter is used by reflection magic to avoid a large amount of boilerplate * code. * <p> * Both the Schema and the Iced object may have children, or (more often) not. * Occasionally, e.g. in the case of schemas used only to handle HTTP request * parameters, there will not be a backing impl object and the Schema will be * parameterized by Iced. * <p> * Other than Schemas backed by Iced this 1-1 mapping is enforced: a check at Schema * registration time ensures that at most one Schema is registered for each Iced class. * This 1-1 mapping allows us to have generic code here in the Schema class which does * all the work for common cases. For example, one can write code which accepts any * Schema instance and creates and fills an instance of its associated impl class: * {@code * I impl = schema.createAndFillImpl(); * } * <p> * Schemas have a State section (broken into Input, Output and InOut fields) * and an Adapter section. The adapter methods fill the State to and from the * Iced impl objects and from HTTP request parameters. In the simple case, where * the backing object corresponds 1:1 with the Schema and no adapting need be * done, the methods here in the Schema class will do all the work based on * reflection. In that case your Schema need only contain the fields you wish * to expose, and no adapter code. * <p> * Methods here allow us to convert from Schema to Iced (impl) and back in a * flexible way. The default behaviour is to map like-named fields back and * forth, often with some default type conversions (e.g., a Keyed object like a * Model will be automagically converted back and forth to a Key). * Subclasses can override methods such as fillImpl or fillFromImpl to * provide special handling when adapting from schema to impl object and back. * Usually they will want to call super to get the default behavior, and then * modify the results a bit (e.g., to map differently-named fields, or to * compute field values). * <p> * Schema Fields must have a single @API annotation describing their direction * of operation and any other properties such as "required". Fields are * API.Direction.INPUT by default. Transient and static fields are ignored. * <p> * Most Java developers need not be concerned with the details that follow, because the * framework will make these calls as necessary. * <p> * Some use cases: * <p> * To find and create an instance of the appropriate schema for an Iced object, with the * given version or the highest previous version:<pre> * Schema s = Schema.schema(6, impl); * </pre> * <p> * To create a schema object and fill it from an existing impl object (the common case):<pre> * S schema = MySchemaClass(version).fillFromImpl(impl);</pre> * or more generally: * <pre> * S schema = Schema(version, impl).fillFromImpl(impl);</pre> * To create an impl object and fill it from an existing schema object (the common case): * <pre> * I impl = schema.createImpl(); // create an empty impl object and any empty children * schema.fillImpl(impl); // fill the empty impl object and any children from the Schema and its children</pre> * or * <pre> * I impl = schema.createAndFillImpl(); // helper which does schema.fillImpl(schema.createImpl())</pre> * <p> * Schemas that are used for HTTP requests are filled with the default values of their impl * class, and then any present HTTP parameters override those default values. * <p> * To create a schema object filled from the default values of its impl class and then * overridden by HTTP request params: * <pre> * S schema = MySchemaClass(version); * I defaults = schema.createImpl(); * schema.fillFromImpl(defaults); * schema.fillFromParms(parms); * </pre> * or more tersely: * <pre> * S schema = MySchemaClass(version).fillFromImpl(schema.createImpl()).fillFromParms(parms); * </pre> * @see Meta#getSchema_version() * @see Meta#getSchema_name() * @see Meta#getSchema_type() * @see water.api.API */ public class Schema<I extends Iced, S extends Schema<I,S>> extends Iced { private transient Class<I> _impl_class = getImplClass(); // see getImplClass() private static final int HIGHEST_SUPPORTED_VERSION = 3; private static final int EXPERIMENTAL_VERSION = 99; /** * Metadata for a Schema, including the version, name and type. This information is included in all REST API * responses as a field in the Schema so that the payloads are self-describing, and it is also available through * the /Metadata/schemas REST API endpoint for the purposes of REST service discovery. */ public static final class Meta extends Iced { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // CAREFUL: This class has its own JSON serializer. If you add a field here you probably also want to add it to the serializer! //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version, meaning that * there are no stability guarantees between H2O versions. */ @API(help="Version number of this Schema. Must not be changed after creation (treat as final).", direction=API.Direction.OUTPUT) private int schema_version; /** Get the simple schema (class) name, for example DeepLearningParametersV3. Must not be changed after creation (treat as final). */ @API(help="Simple name of this Schema. NOTE: the schema_names form a single namespace.", direction=API.Direction.OUTPUT) private String schema_name; /** Get the simple name of H2O type that this Schema represents, for example DeepLearningParameters. */ @API(help="Simple name of H2O type that this Schema represents. Must not be changed after creation (treat as final).", direction=API.Direction.OUTPUT) private String schema_type; // subclasses can redefine this /** Default constructor used only for newInstance() in generic reflection-based code. */ public Meta() {} /** Standard constructor which supplies all the fields. The fields should be treated as immutable once set. */ public Meta(int version, String name, String type) { this.schema_version = version; this.schema_name = name; this.schema_type = type; } /** * Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version, * meaning that there are no stability guarantees between H2O versions. */ public int getSchema_version() { return schema_version; } /** Get the simple schema (class) name, for example DeepLearningParametersV3. */ public String getSchema_name() { return schema_name; } /** Get the simple name of the H2O type that this Schema represents, for example DeepLearningParameters. */ public String getSchema_type() { return schema_type; } /** Set the simple name of the H2O type that this Schema represents, for example Key&lt;Frame&gt;. NOTE: using this is a hack and should be avoided. */ protected void setSchema_type(String schema_type) { this.schema_type = schema_type; } // TODO: make private in Iced: /** Override the JSON serializer to prevent a recursive loop in AutoBuffer. User code should not call this, and soon it should be made protected. */ @Override public final water.AutoBuffer writeJSON_impl(water.AutoBuffer ab) { // Overridden because otherwise we get in a recursive loop trying to serialize this$0. ab.putJSON4("schema_version", schema_version) .put1(',').putJSONStr("schema_name", schema_name) .put1(',').putJSONStr("schema_type", schema_type); return ab; } } @API(help="Metadata on this schema instance, to make it self-describing.", direction=API.Direction.OUTPUT) private Meta __meta = null; /** Get the metadata for this schema instance which makes it self-describing when serialized to JSON. */ protected Meta get__meta() { return __meta; } // Registry which maps a simple schema name to its class. NOTE: the simple names form a single namespace. // E.g., "DeepLearningParametersV2" -> hex.schemas.DeepLearningV2.DeepLearningParametersV2 private static Map<String, Class<? extends Schema>> schemas = new HashMap<>(); // Registry which maps a Schema simpleName to its Iced Class. // E.g., "DeepLearningParametersV2" -> hex.deeplearning.DeepLearning.DeepLearningParameters private static Map<String, Class<? extends Iced>> schema_to_iced = new HashMap<>(); // Registry which maps an Iced simpleName (type) and schema_version to its Schema Class. // E.g., (DeepLearningParameters, 2) -> "DeepLearningParametersV2" // // Note that iced_to_schema gets lazily filled if a higher version is asked for than is // available (e.g., if the highest version of Frame is FrameV2 and the client asks for // the schema for (Frame, 17) then FrameV2 will be returned, and all the mappings between // 17 and 3 will get added to the Map. private static Map<Pair<String, Integer>, Class<? extends Schema>> iced_to_schema = new HashMap<>(); /** * Default constructor; triggers lazy schema registration. * @throws water.exceptions.H2OFailException if there is a name collision or there is more than one schema which maps to the same Iced class */ public Schema() { String name = this.getClass().getSimpleName(); int version = extractVersion(name); String type = _impl_class.getSimpleName(); __meta = new Meta(version, name, type); if (null == schema_to_iced.get(name)) { Log.debug("Registering schema: " + name + " schema_version: " + version + " with Iced class: " + _impl_class.toString()); if (null != schemas.get(name)) throw H2O.fail("Found a duplicate schema name in two different packages: " + schemas.get(name) + " and: " + this.getClass().toString()); schemas.put(name, this.getClass()); schema_to_iced.put(name, _impl_class); if (_impl_class != Iced.class) { Pair versioned = new Pair(type, version); // Check for conflicts if (null != iced_to_schema.get(versioned)) { throw H2O.fail("Found two schemas mapping to the same Iced class with the same version: " + iced_to_schema.get(versioned) + " and: " + this.getClass().toString() + " both map to version: " + version + " of Iced class: " + _impl_class); } iced_to_schema.put(versioned, this.getClass()); } } } private static Pattern _version_pattern = null; /** Extract the version number from the schema class name. Returns -1 if there's no version number at the end of the classname. */ private static int extractVersion(String clz_name) { if (null == _version_pattern) // can't just use a static initializer _version_pattern = Pattern.compile(".*V(\\d+)"); Matcher m = _version_pattern.matcher(clz_name); if (! m.matches()) return -1; return Integer.valueOf(m.group(1)); } /** * Get the version number of this schema, for example 3 or 99. Note that 99 is the "experimental" version, meaning that * there are no stability guarantees between H2O versions. */ public int getSchemaVersion() { return __meta.schema_version; } private static int latest_version = -1; /** * Get the highest schema version number that we've encountered during schema registration. */ public final static int getLatestVersion() { return latest_version; } /** * Get the highest schema version that we support. This bounds the search for a schema if we haven't yet * registered all schemas and don't yet know the latest_version. */ public final static int getHighestSupportedVersion() { return HIGHEST_SUPPORTED_VERSION; } /** * Get the experimental schema version, which indicates that a schema is not guaranteed stable between H2O releases. */ public final static int getExperimentalVersion() { return EXPERIMENTAL_VERSION; } /** * Register the given schema class. * @throws water.exceptions.H2OFailException if there is a name collision, if the type parameters are bad, or if the version is bad */ private static void register(Class<? extends Schema> clz) { synchronized(clz) { // Was there a race to get here? If so, return. Class<? extends Schema> existing = schemas.get(clz.getSimpleName()); if (null != existing) { if (clz != existing) throw H2O.fail("Two schema classes have the same simpleName; this is not supported: " + clz + " and " + existing + "."); return; } // Check that the Schema has the correct type parameters: if (clz.getGenericSuperclass() instanceof ParameterizedType) { Type[] schema_type_parms = ((ParameterizedType) (clz.getGenericSuperclass())).getActualTypeArguments(); if (schema_type_parms.length < 2) throw H2O.fail("Found a Schema that does not pass at least two type parameters. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz); Class parm0 = ReflectionUtils.findActualClassParameter(clz, 0); if (!Iced.class.isAssignableFrom(parm0)) throw H2O.fail("Found a Schema with bad type parameters. First parameter is a subclass of Iced. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm0); if (Schema.class.isAssignableFrom(parm0)) throw H2O.fail("Found a Schema with bad type parameters. First parameter is a subclass of Schema. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm0); Class parm1 = ReflectionUtils.findActualClassParameter(clz, 1); if (!Schema.class.isAssignableFrom(parm1)) throw H2O.fail("Found a Schema with bad type parameters. Second parameter is not a subclass of Schema. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz + ". Second parameter is of class: " + parm1); } else { throw H2O.fail("Found a Schema that does not have a parameterized superclass. Each Schema needs to be parameterized on the backing class (if any, or Iced if not) and itself: " + clz); } int version = extractVersion(clz.getSimpleName()); if (version > getHighestSupportedVersion() && version != EXPERIMENTAL_VERSION) throw H2O.fail("Found a schema with a version higher than the highest supported version; you probably want to bump the highest supported version: " + clz); // NOTE: we now allow non-versioned schemas, for example base classes like ModelMetricsBase, so that we can fetch the metadata for them. if (version > -1 && version != EXPERIMENTAL_VERSION) { // Track highest version of all schemas; only valid after all are registered at startup time. if (version > HIGHEST_SUPPORTED_VERSION) throw H2O.fail("Found a schema with a version greater than the highest supported version of: " + getHighestSupportedVersion() + ": " + clz); if (version > latest_version) { synchronized (Schema.class) { if (version > latest_version) latest_version = version; } } } Schema s = null; try { s = clz.newInstance(); } catch (Exception e) { Log.err("Failed to instantiate schema class: " + clz + " because: " + e); } if (null != s) { Log.debug("Registered Schema: " + clz.getSimpleName()); // Validate the fields: SchemaMetadata meta = new SchemaMetadata(s); for (SchemaMetadata.FieldMetadata field_meta : meta.fields) { String name = field_meta.name; if ("__meta".equals(name) || "__http_status".equals(name) || "_exclude_fields".equals(name) || "_include_fields".equals(name)) continue; if ("Gini".equals(name)) // proper name continue; if (name.endsWith("AUC")) // trainAUC, validAUC continue; // TODO: remove after we move these into a TwoDimTable: if ("F0point5".equals(name) || "F0point5_for_criteria".equals(name) || "F1_for_criteria".equals(name) || "F2_for_criteria".equals(name)) continue; if (name.startsWith("_")) Log.warn("Found schema field which violates the naming convention; name starts with underscore: " + meta.name + "." + name); if (!name.equals(name.toLowerCase()) && !name.equals(name.toUpperCase())) // allow AUC but not residualDeviance Log.warn("Found schema field which violates the naming convention; name has mixed lowercase and uppercase characters: " + meta.name + "." + name); } } } } /** * Create an appropriate implementation object and any child objects but does not fill them. * The standard purpose of a createImpl without a fillImpl is to be able to get the default * values for all the impl's fields. * <p> * For objects without children this method does all the required work. For objects * with children the subclass will need to override, e.g. by calling super.createImpl() * and then calling createImpl() on its children. * <p> * Note that impl objects for schemas which override this method don't need to have * a default constructor (e.g., a Keyed object constructor can still create and set * the Key), but they must not fill any fields which can be filled later from the schema. * <p> * TODO: We could handle the common case of children with the same field names here * by finding all of our fields that are themselves Schemas. * @throws H2OIllegalArgumentException if Class.newInstance fails */ public I createImpl() { try { return this.getImplClass().newInstance(); } catch (Exception e) { String msg = "Exception instantiating implementation object of class: " + this.getImplClass().toString() + " for schema class: " + this.getClass(); Log.err(msg + ": " + e); H2OIllegalArgumentException heae = new H2OIllegalArgumentException(msg); heae.initCause(e); throw heae; } } /** Fill an impl object and any children from this schema and its children. If a schema doesn't need to adapt any fields if does not need to override this method. */ public I fillImpl(I impl) { PojoUtils.copyProperties(impl, this, PojoUtils.FieldNaming.CONSISTENT); // TODO: make field names in the impl classes consistent and remove PojoUtils.copyProperties(impl, this, PojoUtils.FieldNaming.DEST_HAS_UNDERSCORES); return impl; } /** Convenience helper which creates and fills an impl object from this schema. */ final public I createAndFillImpl() { return this.fillImpl(this.createImpl()); } /** Fill this Schema from the given implementation object. If a schema doesn't need to adapt any fields if does not need to override this method. */ public S fillFromImpl(I impl) { PojoUtils.copyProperties(this, impl, PojoUtils.FieldNaming.ORIGIN_HAS_UNDERSCORES); PojoUtils.copyProperties(this, impl, PojoUtils.FieldNaming.CONSISTENT); // TODO: make field names in the impl classes consistent and remove return (S)this; } /** Return the class of the implementation type parameter I for the given Schema class. Used by the metadata facilities and the reflection-base field-copying magic in PojoUtils. */ public static Class<? extends Iced> getImplClass(Class<? extends Schema> clz) { Class<? extends Iced> impl_class = (Class<? extends Iced>)ReflectionUtils.findActualClassParameter(clz, 0); if (null == impl_class) Log.warn("Failed to find an impl class for Schema: " + clz); return impl_class; } /** Return the class of the implementation type parameter I for this Schema. Used by generic code which deals with arbitrary schemas and their backing impl classes. */ public Class<I> getImplClass() { if (null == _impl_class) _impl_class = (Class<I>) ReflectionUtils.findActualClassParameter(this.getClass(), 0); if (null == _impl_class) Log.warn("Failed to find an impl class for Schema: " + this.getClass()); return _impl_class; } /** * Fill this Schema object from a set of parameters. * * @param parms parameters - set of tuples (parameter name, parameter value) * @return this schema * * @see #fillFromParms(Properties, boolean) */ public S fillFromParms(Properties parms) { return fillFromParms(parms, true); } /** * Fill this Schema from a set of (generally HTTP) parameters. * <p> * Using reflection this process determines the type of the target field and * conforms the types if possible. For example, if the field is a Keyed type * the name (ID) will be looked up in the DKV and mapped appropriately. * <p> * The process ignores parameters which are not fields in the schema, and it * verifies that all fields marked as required are present in the parameters * list. * <p> * It also does various sanity checks for broken Schemas, for example fields must * not be private, and since input fields get filled here they must not be final. * @param parms Properties map of parameter values * @param checkRequiredFields perform check for missing required fields * @return this schema * @throws H2OIllegalArgumentException for bad/missing parameters */ public S fillFromParms(Properties parms, boolean checkRequiredFields) { // Get passed-in fields, assign into Schema Class thisSchemaClass = this.getClass(); Map<String, Field> fields = new HashMap<>(); Field current = null; // declare here so we can print in catch{} try { Class clz = thisSchemaClass; do { Field[] some_fields = clz.getDeclaredFields(); for (Field f : some_fields) { current = f; if (null == fields.get(f.getName())) fields.put(f.getName(), f); } clz = clz.getSuperclass(); } while (Iced.class.isAssignableFrom(clz.getSuperclass())); } catch (SecurityException e) { throw H2O.fail("Exception accessing field: " + current + " in class: " + this.getClass() + ": " + e); } for( String key : parms.stringPropertyNames() ) { try { Field f = fields.get(key); // No such field error, if parm is junk if (null == f) { throw new H2OIllegalArgumentException("Unknown parameter: " + key, "Unknown parameter in fillFromParms: " + key + " for class: " + this.getClass().toString()); } int mods = f.getModifiers(); if( Modifier.isTransient(mods) || Modifier.isStatic(mods) ) { // Attempting to set a transient or static; treat same as junk fieldname throw new H2OIllegalArgumentException( "Bad parameter for field: " + key + " for class: " + this.getClass().toString(), "Bad parameter definition for field: " + key + " in fillFromParms for class: " + this.getClass().toString() + " (field was declared static or transient)"); } // Only support a single annotation which is an API, and is required API api = (API)f.getAnnotations()[0]; // Must have one of these set to be an input field if( api.direction() == API.Direction.OUTPUT ) { throw new H2OIllegalArgumentException( "Attempting to set output field: " + key + " for class: " + this.getClass().toString(), "Attempting to set output field: " + key + " in fillFromParms for class: " + this.getClass().toString() + " (field was annotated as API.Direction.OUTPUT)"); } // Parse value and set the field setField(this, f, key, parms.getProperty(key), api.required(), thisSchemaClass); } catch( ArrayIndexOutOfBoundsException aioobe ) { // Come here if missing annotation throw H2O.fail("Broken internal schema; missing API annotation for field: " + key); } catch( IllegalAccessException iae ) { // Come here if field is final or private throw H2O.fail("Broken internal schema; field cannot be private nor final: " + key); } } // Here every thing in 'parms' was set into some field - so we have already // checked for unknown or extra parms. // Confirm required fields are set if (checkRequiredFields) { for (Field f : fields.values()) { int mods = f.getModifiers(); if (Modifier.isTransient(mods) || Modifier.isStatic(mods)) continue; // Ignore transient & static try { API api = (API) f.getAnnotations()[0]; // TODO: is there a more specific way we can do this? if (api.required()) { if (parms.getProperty(f.getName()) == null) { IcedHashMap.IcedHashMapStringObject values = new IcedHashMap.IcedHashMapStringObject(); values.put("schema", this.getClass().getSimpleName()); values.put("argument", f.getName()); throw new H2OIllegalArgumentException( "Required field " + f.getName() + " not specified", "Required field " + f.getName() + " not specified for schema class: " + this .getClass(), values); } } } catch (ArrayIndexOutOfBoundsException e) { throw H2O.fail("Missing annotation for API field: " + f.getName()); } } } return (S) this; } /** * Safe method to set the field on given schema object * @param o schema object to modify * @param f field to modify * @param key name of field to modify * @param value string-based representation of value to set * @param required is field required by API * @param thisSchemaClass class of schema handling this (can be null) * @throws IllegalAccessException */ public static <T extends Schema> void setField(T o, Field f, String key, String value, boolean required, Class thisSchemaClass) throws IllegalAccessException { // Primitive parse by field type Object parse_result = parse(key, value, f.getType(), required, thisSchemaClass); if (parse_result != null && f.getType().isArray() && parse_result.getClass().isArray() && (f.getType().getComponentType() != parse_result.getClass().getComponentType())) { // We have to conform an array of primitives. There's got to be a better way. . . if (parse_result.getClass().getComponentType() == int.class && f.getType().getComponentType() == Integer.class) { int[] from = (int[])parse_result; Integer[] copy = new Integer[from.length]; for (int i = 0; i < from.length; i++) copy[i] = from[i]; f.set(o, copy); } else if (parse_result.getClass().getComponentType() == Integer.class && f.getType().getComponentType() == int.class) { Integer[] from = (Integer[])parse_result; int[] copy = new int[from.length]; for (int i = 0; i < from.length; i++) copy[i] = from[i]; f.set(o, copy); } else if (parse_result.getClass().getComponentType() == Double.class && f.getType().getComponentType() == double.class) { Double[] from = (Double[])parse_result; double[] copy = new double[from.length]; for (int i = 0; i < from.length; i++) copy[i] = from[i]; f.set(o, copy); } else if (parse_result.getClass().getComponentType() == Float.class && f.getType().getComponentType() == float.class) { Float[] from = (Float[])parse_result; float[] copy = new float[from.length]; for (int i = 0; i < from.length; i++) copy[i] = from[i]; f.set(o, copy); } else { throw H2O.fail("Don't know how to cast an array of: " + parse_result.getClass().getComponentType() + " to an array of: " + f.getType().getComponentType()); } } else { f.set(o, parse_result); } } static <E> Object parsePrimitve(String s, Class fclz) { if (fclz.equals(String.class)) return s; // Strings already the right primitive type if (fclz.equals(int.class)) return parseInteger(s, int.class); if (fclz.equals(long.class)) return parseInteger(s, long.class); if (fclz.equals(short.class)) return parseInteger(s, short.class); if (fclz.equals(boolean.class)) { if (s.equals("0")) return Boolean.FALSE; if (s.equals("1")) return Boolean.TRUE; return Boolean.valueOf(s); } if (fclz.equals(byte.class)) return parseInteger(s, byte.class); if (fclz.equals(double.class)) return Double.valueOf(s); if (fclz.equals(float.class)) return Float.valueOf(s); //FIXME: if (fclz.equals(char.class)) return Character.valueOf(s); throw H2O.fail("Unknown primitive type to parse: " + fclz.getSimpleName()); } // URL parameter parse static <E> Object parse(String field_name, String s, Class fclz, boolean required, Class schemaClass) { if (fclz.isPrimitive() || String.class.equals(fclz)) { try { return parsePrimitve(s, fclz); } catch (NumberFormatException ne) { String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": cannot convert \"" + s + "\" to type " + fclz.getSimpleName(); throw new H2OIllegalArgumentException(msg); } } // An array? if (fclz.isArray()) { // Get component type Class<E> afclz = (Class<E>) fclz.getComponentType(); // Result E[] a = null; // Handle simple case with null-array if (s.equals("null") || s.length() == 0) return null; // Splitted values String[] splits; // "".split(",") => {""} so handle the empty case explicitly if (s.startsWith("[") && s.endsWith("]") ) { // It looks like an array read(s, 0, '[', fclz); read(s, s.length() - 1, ']', fclz); String inside = s.substring(1, s.length() - 1).trim(); if (inside.length() == 0) splits = new String[]{}; else splits = splitArgs(inside); } else { // Lets try to parse single value as an array! // See PUBDEV-1955 splits = new String[] { s.trim() }; } // Can't cast an int[] to an Object[]. Sigh. if (afclz == int.class) { // TODO: other primitive types. . . a = (E[]) Array.newInstance(Integer.class, splits.length); } else if (afclz == double.class) { a = (E[]) Array.newInstance(Double.class, splits.length); } else if (afclz == float.class) { a = (E[]) Array.newInstance(Float.class, splits.length); } else { // Fails with primitive classes; need the wrapper class. Thanks, Java. a = (E[]) Array.newInstance(afclz, splits.length); } for (int i = 0; i < splits.length; i++) { if (String.class == afclz || KeyV3.class.isAssignableFrom(afclz)) { // strip quotes off string values inside array String stripped = splits[i].trim(); if ("null".equals(stripped)) { a[i] = null; } else if (!stripped.startsWith("\"") || !stripped.endsWith("\"")) { String msg = "Illegal argument for field: " + field_name + " of schema: " + schemaClass.getSimpleName() + ": string and key arrays' values must be double quoted, but the client sent: " + stripped; IcedHashMap.IcedHashMapStringObject values = new IcedHashMap.IcedHashMapStringObject(); values.put("function", fclz.getSimpleName() + ".fillFromParms()"); values.put("argument", field_name); values.put("value", stripped); throw new H2OIllegalArgumentException(msg, msg, values); } stripped = stripped.substring(1, stripped.length() - 1); a[i] = (E) parse(field_name, stripped, afclz, required, schemaClass); } else { a[i] = (E) parse(field_name, splits[i].trim(), afclz, required, schemaClass); } } return a; } if (fclz.equals(Key.class)) if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s); else if (!required && (s == null || s.length() == 0)) return null; else return Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s); // If the key name is in an array we need to trim surrounding quotes. if (KeyV3.class.isAssignableFrom(fclz)) { if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s); if (!required && (s == null || s.length() == 0)) return null; return KeyV3.make(fclz, Key.make(s.startsWith("\"") ? s.substring(1, s.length() - 1) : s)); // If the key name is in an array we need to trim surrounding quotes. } if (Enum.class.isAssignableFrom(fclz)) return Enum.valueOf(fclz, s); // TODO: try/catch needed! // TODO: these can be refactored into a single case using the facilities in Schema: if (FrameV3.class.isAssignableFrom(fclz)) { if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(field_name, s); else if (!required && (s == null || s.length() == 0)) return null; else { Value v = DKV.get(s); if (null == v) return null; // not required if (!v.isFrame()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Frame", v.get().getClass()); return new FrameV3((Frame) v.get()); // TODO: version! } } if (JobV3.class.isAssignableFrom(fclz)) { if ((s == null || s.length() == 0) && required) throw new H2OKeyNotFoundArgumentException(s); else if (!required && (s == null || s.length() == 0)) return null; else { Value v = DKV.get(s); if (null == v) return null; // not required if (!v.isJob()) throw H2OIllegalArgumentException.wrongKeyType(field_name, s, "Job", v.get().getClass()); return new JobV3().fillFromImpl((Job) v.get()); // TODO: version! } } // TODO: for now handle the case where we're only passing the name through; later we need to handle the case // where the frame name is also specified. if (FrameV3.ColSpecifierV3.class.isAssignableFrom(fclz)) { return new FrameV3.ColSpecifierV3(s); } if (ModelSchema.class.isAssignableFrom(fclz)) throw H2O.fail("Can't yet take ModelSchema as input."); /* if( (s==null || s.length()==0) && required ) throw new IllegalArgumentException("Missing key"); else if (!required && (s == null || s.length() == 0)) return null; else { Value v = DKV.get(s); if (null == v) return null; // not required if (! v.isModel()) throw new IllegalArgumentException("Model argument points to a non-model object."); return v.get(); } */ throw H2O.fail("Unimplemented schema fill from " + fclz.getSimpleName()); } // parse() /** * Helper functions for parse() **/ /** * Parses a string into an integer data type specified by parameter return_type. Accepts any format that * is accepted by java's BigDecimal class. * - Throws a NumberFormatException if the evaluated string is not an integer or if the value is too large to * be stored into return_type without overflow. * - Throws an IllegalAgumentException if return_type is not an integer data type. **/ static private <T> T parseInteger(String s, Class<T> return_type) { try { java.math.BigDecimal num = new java.math.BigDecimal(s); T result = (T) num.getClass().getDeclaredMethod(return_type.getSimpleName() + "ValueExact", new Class[0]).invoke(num); return result; } catch (InvocationTargetException ite) { throw new NumberFormatException("The expression's numeric value is out of the range of type " + return_type.getSimpleName()); } catch (NoSuchMethodException nsme) { throw new IllegalArgumentException(return_type.getSimpleName() + " is not an integer data type"); } catch (IllegalAccessException iae) { throw H2O.fail("Cannot parse expression as " + return_type.getSimpleName() + " (Illegal Access)"); } } static private int read( String s, int x, char c, Class fclz ) { if( peek(s,x,c) ) return x+1; throw new IllegalArgumentException("Expected '"+c+"' while reading a "+fclz.getSimpleName()+", but found "+s); } static private boolean peek( String s, int x, char c ) { return x < s.length() && s.charAt(x) == c; } // Splits on commas, but ignores commas in double quotes. Required // since using a regex blow the stack on long column counts // TODO: detect and complain about malformed JSON private static String[] splitArgs(String argStr) { StringBuffer sb = new StringBuffer (argStr); StringBuffer arg = new StringBuffer (); List<String> splitArgList = new ArrayList<String> (); boolean inDoubleQuotes = false; boolean inSquareBrackets = false; // for arrays of arrays for (int i=0; i < sb.length(); i++) { if (sb.charAt(i) == '"' && !inDoubleQuotes && !inSquareBrackets) { inDoubleQuotes = true; arg.append(sb.charAt(i)); } else if (sb.charAt(i) == '"' && inDoubleQuotes && !inSquareBrackets) { inDoubleQuotes = false; arg.append(sb.charAt(i)); } else if (sb.charAt(i) == ',' && !inDoubleQuotes && !inSquareBrackets) { splitArgList.add(arg.toString()); // clear the field for next word arg.setLength(0); } else if (sb.charAt(i) == '[') { inSquareBrackets = true; arg.append(sb.charAt(i)); } else if (sb.charAt(i) == ']') { inSquareBrackets = false; arg.append(sb.charAt(i)); } else { arg.append(sb.charAt(i)); } } if (arg.length() > 0) splitArgList.add(arg.toString()); return splitArgList.toArray(new String[splitArgList.size()]); } private static boolean schemas_registered = false; /** * Find all schemas using reflection and register them. */ synchronized static public void registerAllSchemasIfNecessary() { if (schemas_registered) return; // if (!Paxos._cloudLocked) return; // TODO: It's never getting locked. . . :-( long before = System.currentTimeMillis(); // Microhack to effect Schema.register(Schema.class), which is // normally not allowed because it has no version: new Schema(); String[] packages = new String[] { "water", "hex", /* Disallow schemas whose parent is in another package because it takes ~4s to do the getSubTypesOf call: "" */}; // For some reason when we're run under Hadoop Reflections is failing to find some of the classes unless we're extremely explicit here: Class<? extends Schema> clzs[] = new Class[] { Schema.class, ModelBuilderSchema.class, ModelSchema.class, ModelOutputSchema.class, ModelParametersSchema.class }; for (String pkg : packages) { Reflections reflections = new Reflections(pkg); for (Class<? extends Schema> clz : clzs) { // NOTE: Reflections sees ModelOutputSchema but not ModelSchema. Another bug to work around: Log.debug("Registering: " + clz.toString() + " in package: " + pkg); if (!Modifier.isAbstract(clz.getModifiers())) Schema.register(clz); // Register the subclasses: Log.debug("Registering subclasses of: " + clz.toString() + " in package: " + pkg); for (Class<? extends Schema> schema_class : reflections.getSubTypesOf(clz)) if (!Modifier.isAbstract(schema_class.getModifiers())) Schema.register(schema_class); } } schemas_registered = true; Log.info("Registered: " + Schema.schemas().size() + " schemas in: " + (System.currentTimeMillis() - before) + "mS"); } /** * Return an immutable Map of all the schemas: schema_name -> schema Class. */ protected static Map<String, Class<? extends Schema>> schemas() { return Collections.unmodifiableMap(new HashMap<>(schemas)); } /** * For a given version and Iced class return the appropriate Schema class, if any.f * @see #schemaClass(int, java.lang.String) */ protected static Class<? extends Schema> schemaClass(int version, Class<? extends Iced> impl_class) { return schemaClass(version, impl_class.getSimpleName()); } /** * For a given version and type (Iced class simpleName) return the appropriate Schema * class, if any. * <p> * If a higher version is asked for than is available (e.g., if the highest version of * Frame is FrameV2 and the client asks for the schema for (Frame, 17) then FrameV2 will * be returned. This compatibility lookup is cached. */ private static Class<? extends Schema> schemaClass(int version, String type) { if (version < 1) return null; Class<? extends Schema> clz = iced_to_schema.get(new Pair(type, version)); if (null != clz) return clz; // found! clz = schemaClass(version - 1, type); if (null != clz) iced_to_schema.put(new Pair(type, version), clz); // found a lower-numbered schema: cache return clz; } /** * For a given version and Iced object return an appropriate Schema instance, if any. * @see #schema(int, java.lang.String) */ public static Schema schema(int version, Iced impl) { return schema(version, impl.getClass().getSimpleName()); } /** * For a given version and Iced class return an appropriate Schema instance, if any. * @throws H2OIllegalArgumentException if Class.newInstance() throws * @see #schema(int, java.lang.String) */ public static Schema schema(int version, Class<? extends Iced> impl_class) { return schema(version, impl_class.getSimpleName()); } // FIXME: can be parameterized by type: public static <T extends Schema> T newInstance(Class<T> clz) public static <T extends Schema> T newInstance(Class<T> clz) { T s = null; try { s = clz.newInstance(); } catch (Exception e) { throw new H2OIllegalArgumentException("Failed to instantiate schema of class: " + clz.getCanonicalName() + ", cause: " + e); } return s; } /** * For a given version and type (Iced class simpleName) return an appropriate new Schema * object, if any. * <p> * If a higher version is asked for than is available (e.g., if the highest version of * Frame is FrameV2 and the client asks for the schema for (Frame, 17) then an instance * of FrameV2 will be returned. This compatibility lookup is cached. * @throws H2ONotFoundArgumentException if an appropriate schema is not found */ private static Schema schema(int version, String type) { Class<? extends Schema> clz = schemaClass(version, type); if (null == clz) clz = schemaClass(Schema.getExperimentalVersion(), type); if (null == clz) throw new H2ONotFoundArgumentException("Failed to find schema for version: " + version + " and type: " + type, "Failed to find schema for version: " + version + " and type: " + type); return Schema.newInstance(clz); } /** * For a given schema_name (e.g., "FrameV2") return an appropriate new schema object (e.g., a water.api.Framev2). * @throws H2ONotFoundArgumentException if an appropriate schema is not found */ protected static Schema newInstance(String schema_name) { Class<? extends Schema> clz = schemas.get(schema_name); if (null == clz) throw new H2ONotFoundArgumentException("Failed to find schema for schema_name: " + schema_name, "Failed to find schema for schema_name: " + schema_name); return Schema.newInstance(clz); } /** * Generate Markdown documentation for this Schema possibly including only the input or output fields. * @throws H2ONotFoundArgumentException if reflection on a field fails */ public StringBuffer markdown(StringBuffer appendToMe, boolean include_input_fields, boolean include_output_fields) { return markdown(new SchemaMetadata(this), appendToMe, include_input_fields, include_output_fields); } /** * Append Markdown documentation for another Schema, given we already have the metadata constructed. * @throws H2ONotFoundArgumentException if reflection on a field fails */ public StringBuffer markdown(SchemaMetadata meta, StringBuffer appendToMe) { return markdown(meta, appendToMe, true, true); } /** * Generate Markdown documentation for this Schema, given we already have the metadata constructed. * @throws H2ONotFoundArgumentException if reflection on a field fails */ public StringBuffer markdown(SchemaMetadata meta , StringBuffer appendToMe, boolean include_input_fields, boolean include_output_fields) { MarkdownBuilder builder = new MarkdownBuilder(); builder.comment("Preview with http://jbt.github.io/markdown-editor"); builder.heading1("schema ", this.getClass().getSimpleName()); builder.hline(); // builder.paragraph(metadata.summary); // TODO: refactor with Route.markdown(): // fields boolean first; // don't print the table at all if there are no rows try { if (include_input_fields) { first = true; builder.heading2("input fields"); for (SchemaMetadata.FieldMetadata field_meta : meta.fields) { if (field_meta.direction == API.Direction.INPUT || field_meta.direction == API.Direction.INOUT) { if (first) { builder.tableHeader("name", "required?", "level", "type", "schema?", "schema", "default", "description", "values", "is member of frames", "is mutually exclusive with"); first = false; } builder.tableRow( field_meta.name, String.valueOf(field_meta.required), field_meta.level.name(), field_meta.type, String.valueOf(field_meta.is_schema), field_meta.is_schema ? field_meta.schema_name : "", (null == field_meta.value ? "(null)" : field_meta.value.toString()), // Something better for toString()? field_meta.help, (field_meta.values == null || field_meta.values.length == 0 ? "" : Arrays.toString(field_meta.values)), (field_meta.is_member_of_frames == null ? "[]" : Arrays.toString(field_meta.is_member_of_frames)), (field_meta.is_mutually_exclusive_with == null ? "[]" : Arrays.toString(field_meta.is_mutually_exclusive_with)) ); } } if (first) builder.paragraph("(none)"); } if (include_output_fields) { first = true; builder.heading2("output fields"); for (SchemaMetadata.FieldMetadata field_meta : meta.fields) { if (field_meta.direction == API.Direction.OUTPUT || field_meta.direction == API.Direction.INOUT) { if (first) { builder.tableHeader("name", "type", "schema?", "schema", "default", "description", "values", "is member of frames", "is mutually exclusive with"); first = false; } builder.tableRow( field_meta.name, field_meta.type, String.valueOf(field_meta.is_schema), field_meta.is_schema ? field_meta.schema_name : "", (null == field_meta.value ? "(null)" : field_meta.value.toString()), // something better than toString()? field_meta.help, (field_meta.values == null || field_meta.values.length == 0 ? "" : Arrays.toString(field_meta.values)), (field_meta.is_member_of_frames == null ? "[]" : Arrays.toString(field_meta.is_member_of_frames)), (field_meta.is_mutually_exclusive_with == null ? "[]" : Arrays.toString(field_meta.is_mutually_exclusive_with))); } } if (first) builder.paragraph("(none)"); } // TODO: render examples and other stuff, if it's passed in } catch (Exception e) { IcedHashMap.IcedHashMapStringObject values = new IcedHashMap.IcedHashMapStringObject(); values.put("schema", this); // TODO: This isn't quite the right exception type: throw new H2OIllegalArgumentException("Caught exception using reflection on schema: " + this, "Caught exception using reflection on schema: " + this + ": " + e, values); } if (null != appendToMe) appendToMe.append(builder.stringBuffer()); return builder.stringBuffer(); } // markdown() }
madmax983/h2o-3
h2o-core/src/main/java/water/api/Schema.java
Java
apache-2.0
52,870
package eu.uqasar.model.measure; /* * #%L * U-QASAR * %% * Copyright (C) 2012 - 2015 U-QASAR Consortium * %% * 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 java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.wicket.model.IModel; import eu.uqasar.util.resources.IResourceKeyProvider; import eu.uqasar.util.resources.ResourceBundleLocator; public enum MetricSource implements IResourceKeyProvider { TestingFramework("test"), IssueTracker("issue"), StaticAnalysis("static"), ContinuousIntegration("ci"), CubeAnalysis("cube"), VersionControl("vcs"), Manual("manual"), ; private final String labelKey; MetricSource(final String labelKey) { this.labelKey = labelKey; } public String toString() { return getLabelModel().getObject(); } public IModel<String> getLabelModel() { return ResourceBundleLocator.getLabelModel(this.getClass(), this); } @Override public String getKey() { return "label.source." + this.labelKey; } public static List<MetricSource> getAllMetricSources(){ List<MetricSource> list = new ArrayList<>(); Collections.addAll(list, MetricSource.values()); return list; } }
U-QASAR/u-qasar.platform
src/main/java/eu/uqasar/model/measure/MetricSource.java
Java
apache-2.0
1,796
'use strict'; import * as _ from 'lodash'; import * as fs from 'fs'; import * as xml2js from 'xml2js'; import * as Mustache from 'mustache'; import * as helpers from './helpers'; import * as utils from './utils'; import * as conf from './conf'; const parseString: (xml: string, options: xml2js.Options) => Promise<any> = helpers.promisify_callback(xml2js.parseString); const readFile = helpers.promisify_callback(fs.readFile); // alike xpath //k function deepGetKey(o, k) { if (!o) { return undefined; } else if (k in o) { return o[k]; } else if (_.isArray(o)) { return o.length === 1 ? deepGetKey(o[0], k) : undefined; } else { let ks = _.keys(o); return ks.length === 1 ? deepGetKey(o[ks[0]], k) : undefined; } } function raw_soap(url, body) { let headers = { SOAPAction: "", "content-type": "text/xml", }; return utils.post(url, body, { headers }).then(result => ( parseString(result, { explicitArray: false, ignoreAttrs: true }) )); } function soap(templateName, params, opts : { responseTag: string, fault_to_string?: (any) => string }) { if (!conf.esup_activ_bo.url) throw "configuration issue: conf.esup_activ_bo.url is missing"; let templateFile = __dirname + "/templates/esup-activ-bo/" + templateName; return readFile(templateFile).then(data => ( Mustache.render(data.toString(), helpers.mapLeaves(params, helpers.escapeXml)) )).then(body => { //console.log(body); const operation = conf.esup_activ_bo.url.replace(/\/AccountManagement$/, '') + '/' + (templateName.match(/Cas/) ? 'CasAccountManagement' : 'AccountManagement'); return raw_soap(operation, body); }).then(xml => { //console.dir(xml, { depth: null }); let response = deepGetKey(xml, opts.responseTag); if (response === undefined) throw get_fault(xml, opts.fault_to_string) || JSON.stringify(xml); return response; }) } const fault_detail_key = (fault) => fault.detail && Object.keys(fault.detail)[0] // Example of response: // <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Identification ...chou..e : (&amp;(supannEmpId=14464)(up1BirthDay=19741002000000Z))</faultstring><detail><AuthentificationException xmlns="http://remote.services.activbo.esupportail.org" /></detail></soap:Fault></soap:Body></soap:Envelope> function get_fault(xml, to_string = undefined) { let fault = deepGetKey(xml, 'soap:Fault'); return fault && (to_string && to_string(fault) || fault.faultstring); } function _get_entries(response) { let entries = deepGetKey(response, 'entry'); if (!_.isArray(entries)) return undefined; let r = _.zipObject(_.map(entries, 'key'), _.map(entries, 'value')); r = _.mapValues(r, val => val.split(conf.esup_activ_bo.multiValue_separator)); return r; } // returns "attrPersoInfo" + code, mail, supannAliasLogin // throws: "Authentification invalide pour l'utilisateur xxx" // throws: "Login invalide" export const authentificateUser = (supannAliasLogin: string, password: string, attrPersoInfo: string[]) => ( soap("authentificateUser.xml", { id: supannAliasLogin, password, attrPersoInfo }, { responseTag: 'ns1:authentificateUserResponse' }).then(_get_entries) ) export const authentificateUserWithCas = (supannAliasLogin: string, proxyticket: string, targetUrl: string, attrPersoInfo: string[]) => ( soap("authentificateUserWithCas.xml", { id: supannAliasLogin, proxyticket, targetUrl, attrPersoInfo }, { responseTag: 'ns1:authentificateUserWithCasResponse' }).then(_get_entries) ) // returns "attrPersoInfo" + possibleChannels, mail, supannAliasLogin + code if account is not activated // ("code" is useful for setPassword or validateCode) // throws: "AuthentificationException" export function validateAccount(userInfoToValidate: Dictionary<string>, attrPersoInfo: string[]): Promise<Dictionary<string>> { console.log("esup_activ_bo._validateAccount " + JSON.stringify(userInfoToValidate)); const hashInfToValidate = _.map(userInfoToValidate, (value, key) => ({ value, key })); let params = { hashInfToValidate, attrPersoInfo }; return soap("validateAccount.xml", params, { responseTag: 'ns1:validateAccountResponse', fault_to_string: fault_detail_key }).then(_get_entries); } // throws: "UserPermissionException" export const updatePersonalInformations = (supannAliasLogin: string, code: string, userInfo: Dictionary<string>) => { const hashBeanPersoInfo = _.map(userInfo, (value, key) => { if (_.isArray(value)) value = value.join(conf.esup_activ_bo.multiValue_separator) return { value, key } }); return soap("updatePersonalInformations.xml", { id: supannAliasLogin, code, hashBeanPersoInfo }, { responseTag: 'ns1:updatePersonalInformationsResponse', fault_to_string: fault_detail_key }) } async function _getCode(hashInfToValidate: Dictionary<string>): Promise<string> { const vals = await validateAccount(hashInfToValidate, []); if (!vals.code) throw "esup_activ_bo.validateAccount did not return code for " + JSON.stringify(hashInfToValidate) + ". Account already activated?"; return vals.code; } // NB: no error in case of unknown channel // throws: "Utilisateur xxx inconnu" // throws: "Utilisateur sdianat n'a pas de mail perso" export const sendCode = (supannAliasLogin: string, channel: string) => ( // Response in case of success: // <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><ns1:sendCodeResponse xmlns:ns1="http://remote.services.activbo.esupportail.org" /></soap:Body></soap:Envelope> soap("sendCode.xml", { id: supannAliasLogin, channel }, { responseTag: 'ns1:sendCodeResponse' }).then(response => { if (response === '') return; // OK! else throw "unexpected sendCode error: " + JSON.stringify(response); }) ); export const validateCode = (supannAliasLogin: string, code: string) => ( // Response in case of success: // <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><ns1:validateCodeResponse xmlns:ns1="http://remote.services.activbo.esupportail.org"><ns1:out>true</ns1:out></ns1:validateCodeResponse></soap:Body></soap:Envelope> soap("validateCode.xml", { id: supannAliasLogin, code }, { responseTag: 'ns1:validateCodeResponse' }).then(response => { return response['ns1:out'] === 'true'; }) ); export function setPassword(supannAliasLogin: string, code: string, password: string) { console.log("esup_activ_bo._setPassword " + supannAliasLogin + " using code " + code); let params = { id: supannAliasLogin, code, password }; return soap("setPassword.xml", params, { responseTag: 'ns1:setPasswordResponse' }).then(response => { if (response === '') return; // OK! else throw "unexpected setPassword error: " + JSON.stringify(response); }); } // TODO //export const changeLogin = (supannAliasLogin: string, code: string, newLogin: string, currentPassword: string) => ... //export const changeLogin = (supannAliasLogin: string, code: string, newLogin: string) => ... export const setNewAccountPassword = (uid: string, supannAliasLogin: string, password: string) => ( _getCode({ uid }).then(code => ( code && setPassword(supannAliasLogin, code, password) )) );
prigaux/compte-externe
server/esup_activ_bo.ts
TypeScript
apache-2.0
7,793
# Copyright 2019 The TensorFlow Authors. 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. # ============================================================================== """Tests for download_data.""" from unittest import mock from google.protobuf import text_format import tensorflow as tf from tensorboard.backend.event_processing import plugin_event_multiplexer from tensorboard.plugins import base_plugin from tensorboard.plugins.hparams import api_pb2 from tensorboard.plugins.hparams import backend_context from tensorboard.plugins.hparams import download_data EXPERIMENT = """ description: 'Test experiment' user: 'Test user' hparam_infos: [ { name: 'initial_temp' type: DATA_TYPE_FLOAT64 }, { name: 'final_temp' type: DATA_TYPE_FLOAT64 }, { name: 'string_hparam' }, { name: 'bool_hparam' }, { name: 'optional_string_hparam' } ] metric_infos: [ { name: { tag: 'current_temp' } }, { name: { tag: 'delta_temp' } }, { name: { tag: 'optional_metric' } } ] """ SESSION_GROUPS = """ session_groups { name: "group_1" hparams { key: "bool_hparam" value { bool_value: true } } hparams { key: "final_temp" value { number_value: 150.0 } } hparams { key: "initial_temp" value { number_value: 270.0 } } hparams { key: "string_hparam" value { string_value: "a string" } } metric_values { name { tag: "current_temp" } value: 10 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: 15 training_step: 2 wall_time_secs: 10.0 } metric_values { name { tag: "optional_metric" } value: 33 training_step: 20 wall_time_secs: 2.0 } sessions { name: "session_1" start_time_secs: 314159 end_time_secs: 314164 status: STATUS_SUCCESS metric_values { name { tag: "current_temp" } value: 10 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: 15 training_step: 2 wall_time_secs: 10.0 } metric_values { name { tag: "optional_metric" } value: 33 training_step: 20 wall_time_secs: 2.0 } } } session_groups { name: "group_2" hparams { key: "bool_hparam" value { bool_value: false } } hparams { key: "final_temp" value { number_value: 100.0 } } hparams { key: "initial_temp" value { number_value: 280.0 } } hparams { key: "string_hparam" value { string_value: "AAAAA"}} metric_values { name { tag: "current_temp" } value: 51.0 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: 44.5 training_step: 2 wall_time_secs: 10.3333333 } sessions { name: "session_2" start_time_secs: 314159 end_time_secs: 314164 status: STATUS_SUCCESS metric_values { name { tag: "current_temp" } value: 100 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: 150 training_step: 3 wall_time_secs: 11.0 } } sessions { name: "session_3" start_time_secs: 314159 end_time_secs: 314164 status: STATUS_FAILURE metric_values { name { tag: "current_temp" } value: 1.0 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: 1.5 training_step: 2 wall_time_secs: 10.0 } } sessions { name: "session_5" start_time_secs: 314159 end_time_secs: 314164 status: STATUS_SUCCESS metric_values { name { tag: "current_temp" } value: 52.0 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: -18 training_step: 2 wall_time_secs: 10.0 } } } session_groups { name: "group_3" hparams { key: "bool_hparam" value { bool_value: true } } hparams { key: "final_temp" value { number_value: 0.000012 } } hparams { key: "initial_temp" value { number_value: 300.0 } } hparams { key: "string_hparam" value { string_value: "a string_3"}} hparams { key: 'optional_string_hparam' value { string_value: 'BB' } } metric_values { name { tag: "current_temp" } value: 101.0 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: -15100000.0 training_step: 2 wall_time_secs: 10.0 } sessions { name: "session_4" start_time_secs: 314159 end_time_secs: 314164 status: STATUS_UNKNOWN metric_values { name { tag: "current_temp" } value: 101.0 training_step: 1 wall_time_secs: 1.0 } metric_values { name { tag: "delta_temp" } value: -151000000.0 training_step: 2 wall_time_secs: 10.0 } } } total_size: 3 """ EXPECTED_LATEX = r"""\begin{table}[tbp] \begin{tabular}{llllllll} initial\_temp & final\_temp & string\_hparam & bool\_hparam & optional\_string\_hparam & current\_temp & delta\_temp & optional\_metric \\ \hline $270$ & $150$ & a string & $1$ & & $10$ & $15$ & $33$ \\ $280$ & $100$ & AAAAA & $0$ & & $51$ & $44.5$ & - \\ $300$ & $1.2\cdot 10^{-5}$ & a string\_3 & $1$ & BB & $101$ & $-1.51\cdot 10^{7}$ & - \\ \hline \end{tabular} \end{table} """ EXPECTED_CSV = """initial_temp,final_temp,string_hparam,bool_hparam,optional_string_hparam,current_temp,delta_temp,optional_metric\r 270.0,150.0,a string,True,,10.0,15.0,33.0\r 280.0,100.0,AAAAA,False,,51.0,44.5,\r 300.0,1.2e-05,a string_3,True,BB,101.0,-15100000.0,\r """ class DownloadDataTest(tf.test.TestCase): def setUp(self): self._mock_multiplexer = mock.create_autospec( plugin_event_multiplexer.EventMultiplexer ) self._mock_tb_context = base_plugin.TBContext( multiplexer=self._mock_multiplexer ) def _run_handler(self, experiment, session_groups, response_format): experiment_proto = text_format.Merge(experiment, api_pb2.Experiment()) session_groups_proto = text_format.Merge( session_groups, api_pb2.ListSessionGroupsResponse() ) num_columns = len(experiment_proto.hparam_infos) + len( experiment_proto.metric_infos ) handler = download_data.Handler( backend_context.Context(self._mock_tb_context), experiment_proto, session_groups_proto, response_format, [True] * num_columns, ) return handler.run() def test_csv(self): body, mime_type = self._run_handler( EXPERIMENT, SESSION_GROUPS, download_data.OutputFormat.CSV ) self.assertEqual("text/csv", mime_type) self.assertEqual(EXPECTED_CSV, body) def test_latex(self): body, mime_type = self._run_handler( EXPERIMENT, SESSION_GROUPS, download_data.OutputFormat.LATEX ) self.assertEqual("application/x-latex", mime_type) self.assertEqual(EXPECTED_LATEX, body) def test_json(self): body, mime_type = self._run_handler( EXPERIMENT, SESSION_GROUPS, download_data.OutputFormat.JSON ) self.assertEqual("application/json", mime_type) expected_result = { "header": [ "initial_temp", "final_temp", "string_hparam", "bool_hparam", "optional_string_hparam", "current_temp", "delta_temp", "optional_metric", ], "rows": [ [270.0, 150.0, "a string", True, "", 10.0, 15.0, 33.0], [280.0, 100.0, "AAAAA", False, "", 51.0, 44.5, None], [ 300.0, 1.2e-05, "a string_3", True, "BB", 101.0, -15100000.0, None, ], ], } self.assertEqual(expected_result, body) if __name__ == "__main__": tf.test.main()
tensorflow/tensorboard
tensorboard/plugins/hparams/download_data_test.py
Python
apache-2.0
8,571
package com.feiyu.storm.streamingdatacollection.spout; /** * from https://github.com/apache/incubator-storm/blob/master/examples/storm-starter/src/jvm/storm/starter/spout/RandomSentenceSpout.java * modified by feiyu */ import java.util.Map; import java.util.Random; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseRichSpout; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; import backtype.storm.utils.Utils; @SuppressWarnings("serial") public class ForTestFakeSpout extends BaseRichSpout { private SpoutOutputCollector _collector; private Random _rand; @SuppressWarnings("rawtypes") @Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { _collector = collector; _rand = new Random(); } @Override public void nextTuple() { Utils.sleep(5000); String[] tweets = new String[]{ "I rated X-Men: Days of Future Past 8/10 #IMDb http://www.imdb.com/title/tt1877832", "I rated Game of Thrones 10/10 #IMDb http://www.imdb.com/title/tt0944947", "I rated Snowpiercer 7/10 #IMDb really enjoyed this. Beautifully shot & choreographed. Great performance from Swinton http://www.imdb.com/title/tt1706620", "Back on form. That ending = awesome! - I rated X-Men: Days of Future Past 7/10 #IMDb http://www.imdb.com/title/tt1877832", "A great movie especially for those trying to learn German ~> I rated Run Lola Run 8/10 #IMDb http://www.imdb.com/title/tt0130827", "I rated Breaking Bad 8/10 #IMDb :: I would say 7 but last season made it worth it... Matter of taste @mmelgarejoc http://www.imdb.com/title/tt0903747", "I rated White House Down 7/10 #IMDb bunch of explosions and one liners, fun for all http://www.imdb.com/title/tt2334879" }; String tweet = tweets[_rand.nextInt(tweets.length)]; _collector.emit(new Values(tweet)); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("tweet")); } }
faustineinsun/WiseCrowdRec
deprecated-wisecrowdrec-springmvc/WiseCrowdRec/src/main/java/com/feiyu/storm/streamingdatacollection/spout/ForTestFakeSpout.java
Java
apache-2.0
2,356
/* * Copyright 2016 Axibase Corporation or its affiliates. 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 * * https://www.axibase.com/atsd/axibase-apache-2.0.pdf * * 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. */ package com.axibase.tsd.model.meta; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.experimental.Accessors; import java.util.Map; @Data /* Use chained setters that return this instead of void */ @Accessors(chain = true) @JsonIgnoreProperties(ignoreUnknown = true) public class EntityAndTags { @JsonProperty("entity") private String entityName; private Long lastInsertTime; @JsonProperty private Map<String, String> tags; }
axibase/atsd-api-java
src/main/java/com/axibase/tsd/model/meta/EntityAndTags.java
Java
apache-2.0
1,151
<?php /** * This example populates a first party audience segment. To determine which * audience segments exist, run GetAllAudienceSegments.php. * * PHP version 5 * * Copyright 2014, Google Inc. 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 GoogleApiAdsDfp * @subpackage v201611 * @category WebServices * @copyright 2014, Google Inc. All Rights Reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, * Version 2.0 */ error_reporting(E_STRICT | E_ALL); // You can set the include path to src directory or reference // DfpUser.php directly via require_once. // $path = '/path/to/dfp_api_php_lib/src'; $path = dirname(__FILE__) . '/../../../../src'; set_include_path(get_include_path() . PATH_SEPARATOR . $path); require_once 'Google/Api/Ads/Dfp/Lib/DfpUser.php'; require_once 'Google/Api/Ads/Dfp/Util/v201611/StatementBuilder.php'; require_once dirname(__FILE__) . '/../../../Common/ExampleUtils.php'; // Set the ID of the first party audience segment to populate. $audienceSegmentId = 'INSERT_AUDIENCE_SEGMENT_ID_HERE'; try { // Get DfpUser from credentials in "../auth.ini" // relative to the DfpUser.php file's directory. $user = new DfpUser(); // Log SOAP XML request and response. $user->LogDefaults(); // Get the AudienceSegmentService. $audienceSegmentService = $user->GetService('AudienceSegmentService', 'v201611'); // Create a statement to only select a specified first party audience // segment. $statementBuilder = new StatementBuilder(); $statementBuilder->Where('id = :id and type = :type') ->OrderBy('id ASC') ->Limit(1) ->WithBindVariableValue('id', $audienceSegmentId) ->WithBindVariableValue('type', 'FIRST_PARTY'); // Default for total result set size. $totalResultSetSize = 0; do { // Get audience segments by statement. $page = $audienceSegmentService->getAudienceSegmentsByStatement( $statementBuilder->ToStatement()); // Display results. if (isset($page->results)) { $totalResultSetSize = $page->totalResultSetSize; $i = $page->startIndex; foreach ($page->results as $audienceSegment) { printf("%d) Audience segment with ID %d and name '%s' will be " . "populated.\n", $i++, $audienceSegment->id, $audienceSegment->name); } } $statementBuilder->IncreaseOffsetBy(StatementBuilder::SUGGESTED_PAGE_LIMIT); } while ($statementBuilder->GetOffset() < $totalResultSetSize); printf("Number of audience segments to be populated: %d\n", $totalResultSetSize); if ($totalResultSetSize > 0) { // Remove limit and offset from statement. $statementBuilder->RemoveLimitAndOffset(); // Create action. $action = new PopulateAudienceSegments(); // Perform action. $result = $audienceSegmentService->performAudienceSegmentAction($action, $statementBuilder->ToStatement()); // Display results. if (isset($result) && $result->numChanges > 0) { printf("Number of audience segments populated: %d\n", $result->numChanges); } else { printf("No audience segments were populated.\n"); } } } catch (OAuth2Exception $e) { ExampleUtils::CheckForOAuth2Errors($e); } catch (ValidationException $e) { ExampleUtils::CheckForOAuth2Errors($e); } catch (Exception $e) { printf("%s\n", $e->getMessage()); }
Getsidecar/googleads-php-lib
examples/Dfp/v201611/AudienceSegmentService/PopulateFirstPartyAudienceSegments.php
PHP
apache-2.0
3,948
package main import ( "log" "net/http" "github.com/gophergala/melted_brains/http_handler" "golang.org/x/net/websocket" ) func main() { http.HandleFunc("/game/", http_handler.GameHandler) http.Handle("/events/", websocket.Handler(http_handler.EventsHandler)) http.Handle("/waiting/", websocket.Handler(http_handler.EventsHandler)) http.Handle("/", http.FileServer(http.Dir("./static"))) err := http.ListenAndServe(":8000", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
gophergala/melted_brains
server.go
GO
apache-2.0
498
import React from 'react'; import renderer from 'react-test-renderer'; import VideoQuestion from './VideoQuestion'; jest.mock('expo', () => ({ Video: 'Video' })); it('renders without crashing', () => { const tree = renderer.create( <VideoQuestion video={require('../../assets/videos/placeholder.mp4')} question="Wer ist eine Ananas?" answers={[ 'Ich bin eine Ananas', 'Du bist eine Ananas', 'Wir sind eine Ananas' ]} /> ); expect(tree).toMatchSnapshot(); });
cognostics/serlo-abc
src/components/exercises/VideoQuestion.test.js
JavaScript
apache-2.0
526
#!/usr/bin/python # # Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es) # # 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. # from exaqute.ExaquteTask import * from pycompss.api.task import task from pycompss.api.api import compss_wait_on from pycompss.api.api import compss_barrier from pycompss.api.api import compss_delete_object from pycompss.api.api import compss_delete_file from pycompss.api.parameter import * from pycompss.api.implement import implement from pycompss.api.constraint import * class ExaquteTask(object): def __init__(self, *args, **kwargs): global scheduler scheduler = "Current scheduler is PyCOMPSs" self.task_instance = task(*args, **kwargs) def __call__(self, f): return self.task_instance.__call__(f) def barrier(): # Wait compss_barrier() def get_value_from_remote(obj): # Gather obj = compss_wait_on(obj) return obj def delete_object(obj): # Release compss_delete_object(obj) def delete_file(file_path): compss_delete_file(file_path) def compute(obj): # Submit task return obj
mF2C/COMPSs
compss/programming_model/bindings/python/src/exaqute/ExaquteTaskPyCOMPSs.py
Python
apache-2.0
1,613
"use strict"; const apisObject = { "type": "object", "required": false, "patternProperties": { "^[_a-z\/][_a-zA-Z0-9\/:]*$": { //pattern to match an api route "type": "object", "required": true, "properties": { "access": {"type": "boolean", "required": false}, } } } }; const aclRoute = { "type": "array", "required": false, "items": { "type": "object", "required": false, "properties": { "access": {"type": "string", "required": false}, "apis": apisObject } } }; const scope = { "type": "object", "patternProperties": { "^[^\W\.]+$": { "type": "object", "required": false, "patternProperties": { ".+": { "type": "object", "required": false, "properties": { "access": {"type": "boolean", "required": false}, "apisPermission": { "type": "string", "enum": ["restricted"], "required": false }, "get": aclRoute, "post": aclRoute, "put": aclRoute, "delete": aclRoute, "head": aclRoute, "options": aclRoute, "other": aclRoute, "additionalProperties": false }, "additionalProperties": false } }, "additionalProperties": false }, }, "additionalProperties": false }; module.exports = scope;
soajs/soajs.dashboard
schemas/updateScopeAcl.js
JavaScript
apache-2.0
1,270
package br.com.ceducarneiro.analisadorsintatico; public class LexException extends Exception { private char badCh; private int line, column; public LexException(int line, int column, char ch) { badCh = ch; this.line = line; this.column = column; } @Override public String toString() { return String.format("Caractere inesperado: \"%s\" na linha %d coluna %d", badCh != 0 ? badCh : "EOF", line, column); } }
edu1910/AnalisadorSintatico
src/br/com/ceducarneiro/analisadorsintatico/LexException.java
Java
apache-2.0
473
/* * 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 code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.cloudtasks.v2.model; /** * Encapsulates settings provided to GetIamPolicy. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Tasks API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GetPolicyOptions extends com.google.api.client.json.GenericJson { /** * Optional. The maximum policy version that will be used to format the policy. Valid values are * 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with * any conditional role bindings must specify version 3. Policies with no conditional role * bindings may specify any valid value or leave the field unset. The policy in the response might * use the policy version that you specified, or it might use a lower policy version. For example, * if you specify version 3, but the policy has no conditional role bindings, the response uses * version 1. To learn which resources support conditions in their IAM policies, see the [IAM * documentation](https://cloud.google.com/iam/help/conditions/resource-policies). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer requestedPolicyVersion; /** * Optional. The maximum policy version that will be used to format the policy. Valid values are * 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with * any conditional role bindings must specify version 3. Policies with no conditional role * bindings may specify any valid value or leave the field unset. The policy in the response might * use the policy version that you specified, or it might use a lower policy version. For example, * if you specify version 3, but the policy has no conditional role bindings, the response uses * version 1. To learn which resources support conditions in their IAM policies, see the [IAM * documentation](https://cloud.google.com/iam/help/conditions/resource-policies). * @return value or {@code null} for none */ public java.lang.Integer getRequestedPolicyVersion() { return requestedPolicyVersion; } /** * Optional. The maximum policy version that will be used to format the policy. Valid values are * 0, 1, and 3. Requests specifying an invalid value will be rejected. Requests for policies with * any conditional role bindings must specify version 3. Policies with no conditional role * bindings may specify any valid value or leave the field unset. The policy in the response might * use the policy version that you specified, or it might use a lower policy version. For example, * if you specify version 3, but the policy has no conditional role bindings, the response uses * version 1. To learn which resources support conditions in their IAM policies, see the [IAM * documentation](https://cloud.google.com/iam/help/conditions/resource-policies). * @param requestedPolicyVersion requestedPolicyVersion or {@code null} for none */ public GetPolicyOptions setRequestedPolicyVersion(java.lang.Integer requestedPolicyVersion) { this.requestedPolicyVersion = requestedPolicyVersion; return this; } @Override public GetPolicyOptions set(String fieldName, Object value) { return (GetPolicyOptions) super.set(fieldName, value); } @Override public GetPolicyOptions clone() { return (GetPolicyOptions) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-cloudtasks/v2/1.31.0/com/google/api/services/cloudtasks/v2/model/GetPolicyOptions.java
Java
apache-2.0
4,445
package me.banxi.androiddemo; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends Activity{ public void onCreate(Bundle bundle){ super.onCreate(bundle); TextView textView = new TextView(this); textView.setText("Hello,World"); setContentView(textView); } }
banxi1988/android-demo
src/main/java/me/banxi/androiddemo/MainActivity.java
Java
apache-2.0
366
from rest_framework import generics, permissions, views, response,status from .models import Account from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \ UpdateAccountSerializer, AccountRetrieveSerializer # Create your views here. class AccountCreateView(generics.CreateAPIView): queryset = Account.objects.all() serializer_class = AccountCreateSerializer permission_classes = [permissions.AllowAny] class AccountListView(generics.ListAPIView): queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [permissions.IsAuthenticated] class AccountRetrieveView(generics.RetrieveAPIView): queryset = Account.objects.all() serializer_class = AccountRetrieveSerializer class UpdateAccountView(generics.UpdateAPIView): queryset = Account.objects.all() serializer_class = UpdateAccountSerializer # permission_classes = [permissions.IsAuthenticated] class AccountAuthenticationView(views.APIView): queryset = Account.objects.all() serializer_class = AuthenticateSerializer def post(self, request): data = request.data serializer = AuthenticateSerializer(data=data) if serializer.is_valid(raise_exception=True): new_date = serializer.data return response.Response(new_date,status=status.HTTP_200_OK) return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
jiafengwu0301/App_BackEnd
api/views.py
Python
apache-2.0
1,474
/* * 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.activemq.artemis.tests.integration.server; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.core.server.Queue; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class ExpiryRunnerTest extends ActiveMQTestBase { private ActiveMQServer server; private ClientSession clientSession; private final SimpleString qName = new SimpleString("ExpiryRunnerTestQ"); private final SimpleString qName2 = new SimpleString("ExpiryRunnerTestQ2"); private SimpleString expiryQueue; private SimpleString expiryAddress; private ServerLocator locator; @Test public void testBasicExpire() throws Exception { ClientProducer producer = clientSession.createProducer(qName); int numMessages = 100; long expiration = System.currentTimeMillis(); for (int i = 0; i < numMessages; i++) { ClientMessage m = createTextMessage(clientSession, "m" + i); m.setExpiration(expiration); producer.send(m); } Thread.sleep(1600); Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); } @Test public void testExpireFromMultipleQueues() throws Exception { ClientProducer producer = clientSession.createProducer(qName); clientSession.createQueue(qName2, qName2, null, false); AddressSettings addressSettings = new AddressSettings().setExpiryAddress(expiryAddress); server.getAddressSettingsRepository().addMatch(qName2.toString(), addressSettings); ClientProducer producer2 = clientSession.createProducer(qName2); int numMessages = 100; long expiration = System.currentTimeMillis(); for (int i = 0; i < numMessages; i++) { ClientMessage m = createTextMessage(clientSession, "m" + i); m.setExpiration(expiration); producer.send(m); m = createTextMessage(clientSession, "m" + i); m.setExpiration(expiration); producer2.send(m); } Thread.sleep(1600); Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); } @Test public void testExpireHalf() throws Exception { ClientProducer producer = clientSession.createProducer(qName); int numMessages = 100; long expiration = System.currentTimeMillis(); for (int i = 0; i < numMessages; i++) { ClientMessage m = createTextMessage(clientSession, "m" + i); if (i % 2 == 0) { m.setExpiration(expiration); } producer.send(m); } Thread.sleep(1600); Assert.assertEquals(numMessages / 2, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); } @Test public void testExpireConsumeHalf() throws Exception { ClientProducer producer = clientSession.createProducer(qName); int numMessages = 100; long expiration = System.currentTimeMillis() + 1000; for (int i = 0; i < numMessages; i++) { ClientMessage m = createTextMessage(clientSession, "m" + i); m.setExpiration(expiration); producer.send(m); } ClientConsumer consumer = clientSession.createConsumer(qName); clientSession.start(); for (int i = 0; i < numMessages / 2; i++) { ClientMessage cm = consumer.receive(500); Assert.assertNotNull("message not received " + i, cm); cm.acknowledge(); Assert.assertEquals("m" + i, cm.getBodyBuffer().readString()); } consumer.close(); Thread.sleep(2100); Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); } @Test public void testExpireToExpiryQueue() throws Exception { AddressSettings addressSettings = new AddressSettings().setExpiryAddress(expiryAddress); server.getAddressSettingsRepository().addMatch(qName2.toString(), addressSettings); clientSession.deleteQueue(qName); clientSession.createQueue(qName, qName, null, false); clientSession.createQueue(qName, qName2, null, false); ClientProducer producer = clientSession.createProducer(qName); int numMessages = 100; long expiration = System.currentTimeMillis(); for (int i = 0; i < numMessages; i++) { ClientMessage m = createTextMessage(clientSession, "m" + i); m.setExpiration(expiration); producer.send(m); } Thread.sleep(1600); Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getMessageCount()); Assert.assertEquals(0, ((Queue) server.getPostOffice().getBinding(qName).getBindable()).getDeliveringCount()); ClientConsumer consumer = clientSession.createConsumer(expiryQueue); clientSession.start(); for (int i = 0; i < numMessages; i++) { ClientMessage cm = consumer.receive(500); Assert.assertNotNull(cm); // assertEquals("m" + i, cm.getBody().getString()); } for (int i = 0; i < numMessages; i++) { ClientMessage cm = consumer.receive(500); Assert.assertNotNull(cm); // assertEquals("m" + i, cm.getBody().getString()); } consumer.close(); } @Test public void testExpireWhilstConsumingMessagesStillInOrder() throws Exception { ClientProducer producer = clientSession.createProducer(qName); ClientConsumer consumer = clientSession.createConsumer(qName); CountDownLatch latch = new CountDownLatch(1); DummyMessageHandler dummyMessageHandler = new DummyMessageHandler(consumer, latch); clientSession.start(); Thread thr = new Thread(dummyMessageHandler); thr.start(); long expiration = System.currentTimeMillis() + 1000; int numMessages = 0; long sendMessagesUntil = System.currentTimeMillis() + 2000; do { ClientMessage m = createTextMessage(clientSession, "m" + numMessages++); m.setExpiration(expiration); producer.send(m); Thread.sleep(100); } while (System.currentTimeMillis() < sendMessagesUntil); Assert.assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); consumer.close(); consumer = clientSession.createConsumer(expiryQueue); do { ClientMessage cm = consumer.receive(2000); if (cm == null) { break; } String text = cm.getBodyBuffer().readString(); cm.acknowledge(); Assert.assertFalse(dummyMessageHandler.payloads.contains(text)); dummyMessageHandler.payloads.add(text); } while (true); for (int i = 0; i < numMessages; i++) { if (dummyMessageHandler.payloads.isEmpty()) { break; } Assert.assertTrue("m" + i, dummyMessageHandler.payloads.remove("m" + i)); } consumer.close(); thr.join(); } // // public static void main(final String[] args) throws Exception // { // for (int i = 0; i < 1000; i++) // { // TestSuite suite = new TestSuite(); // ExpiryRunnerTest expiryRunnerTest = new ExpiryRunnerTest(); // expiryRunnerTest.setName("testExpireWhilstConsuming"); // suite.addTest(expiryRunnerTest); // // TestResult result = TestRunner.run(suite); // if (result.errorCount() > 0 || result.failureCount() > 0) // { // System.exit(1); // } // } // } @Override @Before public void setUp() throws Exception { super.setUp(); ConfigurationImpl configuration = (ConfigurationImpl) createDefaultInVMConfig().setMessageExpiryScanPeriod(1000); server = addServer(ActiveMQServers.newActiveMQServer(configuration, false)); // start the server server.start(); // then we create a client as normal locator = createInVMNonHALocator().setBlockOnAcknowledge(true); ClientSessionFactory sessionFactory = createSessionFactory(locator); clientSession = sessionFactory.createSession(false, true, true); clientSession.createQueue(qName, qName, null, false); expiryAddress = new SimpleString("EA"); expiryQueue = new SimpleString("expiryQ"); AddressSettings addressSettings = new AddressSettings().setExpiryAddress(expiryAddress); server.getAddressSettingsRepository().addMatch(qName.toString(), addressSettings); server.getAddressSettingsRepository().addMatch(qName2.toString(), addressSettings); clientSession.createQueue(expiryAddress, expiryQueue, null, false); } private static class DummyMessageHandler implements Runnable { List<String> payloads = new ArrayList<>(); private final ClientConsumer consumer; private final CountDownLatch latch; private DummyMessageHandler(final ClientConsumer consumer, final CountDownLatch latch) { this.consumer = consumer; this.latch = latch; } @Override public void run() { while (true) { try { ClientMessage message = consumer.receive(5000); if (message == null) { break; } message.acknowledge(); payloads.add(message.getBodyBuffer().readString()); Thread.sleep(110); } catch (Exception e) { e.printStackTrace(); } } latch.countDown(); } } }
lburgazzoli/apache-activemq-artemis
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/server/ExpiryRunnerTest.java
Java
apache-2.0
11,691
// // https://github.com/Dogfalo/materialize/issues/634#issuecomment-113213629 // and // https://github.com/noodny/materializecss-amd/blob/master/config.js // // require([ 'global', 'initial', 'animation', 'buttons', 'cards', 'carousel', 'character_counter', 'chips', 'collapsible', 'dropdown', 'forms', 'hammerjs', 'jquery.easing', 'jquery.hammer', 'jquery.timeago', 'leanModal', 'materialbox', 'parallax', 'picker', 'picker.date', 'prism', 'pushpin', 'scrollFire', 'scrollspy', 'sideNav', 'slider', 'tabs', 'toasts', 'tooltip', 'transitions', 'velocity' ], function(Materialize) { return Materialize; } );
romeomaryns/ripple
gateway/src/main/resources/static/materialize-css.js
JavaScript
apache-2.0
680
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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. // //*********************************************************// using System; using System.Runtime.InteropServices; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.Project; namespace Microsoft.NodejsTools.Project { [Guid("62E8E091-6914-498E-A47B-6F198DC1873D")] class NodejsGeneralPropertyPage : CommonPropertyPage { private readonly NodejsGeneralPropertyPageControl _control; public NodejsGeneralPropertyPage() { _control = new NodejsGeneralPropertyPageControl(this); } public override System.Windows.Forms.Control Control { get { return _control; } } internal override CommonProjectNode Project { get { return base.Project; } set { if (value == null && base.Project != null) { base.Project.PropertyPage = null; } base.Project = value; if (value != null) { ((NodejsProjectNode)value).PropertyPage = this; } } } public override void Apply() { Project.SetProjectProperty(NodeProjectProperty.NodeExePath, _control.NodeExePath); Project.SetProjectProperty(NodeProjectProperty.NodeExeArguments, _control.NodeExeArguments); Project.SetProjectProperty(CommonConstants.StartupFile, _control.ScriptFile); Project.SetProjectProperty(NodeProjectProperty.ScriptArguments, _control.ScriptArguments); Project.SetProjectProperty(NodeProjectProperty.NodejsPort, _control.NodejsPort); Project.SetProjectProperty(NodeProjectProperty.StartWebBrowser, _control.StartWebBrowser.ToString()); Project.SetProjectProperty(CommonConstants.WorkingDirectory, _control.WorkingDirectory); Project.SetProjectProperty(NodeProjectProperty.LaunchUrl, _control.LaunchUrl); Project.SetProjectProperty(NodeProjectProperty.DebuggerPort, _control.DebuggerPort); Project.SetProjectProperty(NodeProjectProperty.Environment, _control.Environment); IsDirty = false; } public override void LoadSettings() { Loading = true; try { _control.NodeExeArguments = Project.GetUnevaluatedProperty(NodeProjectProperty.NodeExeArguments); _control.NodeExePath = Project.GetUnevaluatedProperty(NodeProjectProperty.NodeExePath); _control.ScriptFile = Project.GetUnevaluatedProperty(CommonConstants.StartupFile); _control.ScriptArguments = Project.GetUnevaluatedProperty(NodeProjectProperty.ScriptArguments); _control.WorkingDirectory = Project.GetUnevaluatedProperty(CommonConstants.WorkingDirectory); _control.LaunchUrl = Project.GetUnevaluatedProperty(NodeProjectProperty.LaunchUrl); _control.NodejsPort = Project.GetUnevaluatedProperty(NodeProjectProperty.NodejsPort); _control.DebuggerPort = Project.GetUnevaluatedProperty(NodeProjectProperty.DebuggerPort); _control.Environment = Project.GetUnevaluatedProperty(NodeProjectProperty.Environment); // Attempt to parse the boolean. If we fail, assume it is true. bool startWebBrowser; if (!Boolean.TryParse(Project.GetUnevaluatedProperty(NodeProjectProperty.StartWebBrowser), out startWebBrowser)) { startWebBrowser = true; } _control.StartWebBrowser = startWebBrowser; } finally { Loading = false; } } public override string Name { get { return "General"; } } } }
mjbvz/nodejstools
Nodejs/Product/Nodejs/Project/NodejsGeneralPropertyPage.cs
C#
apache-2.0
4,380
package org.plista.kornakapi.core.training.preferencechanges; import java.util.List; import java.util.Map; import com.google.common.collect.Lists; import com.google.common.collect.Maps; public class DelegatingPreferenceChangeListenerForLabel implements PreferenceChangeListenerForLabel { private final Map<String,List<PreferenceChangeListener>> delegates = Maps.newLinkedHashMap(); public void addDelegate(PreferenceChangeListener listener, String label) { if(delegates.containsKey(label)){ delegates.get(label).add(listener); }else{ List<PreferenceChangeListener> delegatesPerLabel = Lists.newArrayList(); delegatesPerLabel.add(listener); delegates.put(label, delegatesPerLabel); } } @Override public void notifyOfPreferenceChange(String label) { for (PreferenceChangeListener listener : delegates.get(label)) { listener.notifyOfPreferenceChange(); } } }
plista/kornakapi
src/main/java/org/plista/kornakapi/core/training/preferencechanges/DelegatingPreferenceChangeListenerForLabel.java
Java
apache-2.0
935
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Windows.Forms; using CompatCheckAndMigrate.Helpers; using CompatCheckAndMigrate.ObjectModel; namespace CompatCheckAndMigrate.Controls { public partial class SiteStatusControl : UserControl, IWizardStep { private IISServers IISServers; public SiteStatusControl() { InitializeComponent(); IISServers = null; } public event EventHandler<GoToWizardStepEventArgs> GoTo; public void SetState(object state, bool isNavigatingBack = false) { if (state != null) { this.IISServers = (IISServers)state; } } private void FireGoToEvent(WizardSteps step, object state = null) { EventHandler<GoToWizardStepEventArgs> _goTo = GoTo; if (_goTo != null) { _goTo(this, new GoToWizardStepEventArgs(step, state)); } } private void btnFeedback_Click(object sender, EventArgs e) { FireGoToEvent(WizardSteps.FeedbackPage, this.IISServers); } private void btnInstall_Click(object sender, EventArgs e) { FireGoToEvent(WizardSteps.InstallWebDeploy, this.IISServers); } private void btnClose_Click(object sender, EventArgs e) { System.Windows.Forms.Application.Exit(); } private void SiteStatusControl_Load(object sender, EventArgs e) { if (this.IISServers != null) { foreach (var server in this.IISServers.Servers.Values) { foreach (var site in server.Sites.Where(s => s.PublishProfile != null && !string.IsNullOrEmpty(s.PublishProfile.SiteName))) { var siteItem = new SiteItemControl(site.PublishProfile.SiteName, string.IsNullOrEmpty(site.SiteCreationError)); siteItem.Dock = DockStyle.Top; statusPanel.Controls.Add(siteItem); } } } } private void button1_Click(object sender, EventArgs e) { Process.Start(TraceHelper.Tracer.TraceFile); } } }
Azure/Azure-Websites-Migration-Tool
Controls/SiteStatusControl.cs
C#
apache-2.0
2,342
<?php namespace DCarbone\PHPClassBuilder\Template; /* * Copyright 2016-2017 Daniel Carbone (daniel.p.carbone@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. */ use DCarbone\PHPClassBuilder\Exception\CommentLineIndexNotFoundException; use DCarbone\PHPClassBuilder\Exception\FilePartNotFoundException; use DCarbone\PHPClassBuilder\Exception\InvalidClassNameException; use DCarbone\PHPClassBuilder\Exception\InvalidCommentLineArgumentException; use DCarbone\PHPClassBuilder\Exception\InvalidCompileOptionValueException; use DCarbone\PHPClassBuilder\Exception\InvalidFilePartException; use DCarbone\PHPClassBuilder\Exception\InvalidFunctionBodyPartArgumentException; use DCarbone\PHPClassBuilder\Exception\InvalidFunctionNameException; use DCarbone\PHPClassBuilder\Exception\InvalidInterfaceFunctionScopeException; use DCarbone\PHPClassBuilder\Exception\InvalidInterfaceNameException; use DCarbone\PHPClassBuilder\Exception\InvalidInterfaceParentArgumentException; use DCarbone\PHPClassBuilder\Exception\InvalidNamespaceNameException; use DCarbone\PHPClassBuilder\Exception\InvalidOutputPathException; use DCarbone\PHPClassBuilder\Exception\InvalidVariableNameException; use DCarbone\PHPClassBuilder\Exception\MissingNameException; use DCarbone\PHPClassBuilder\Template\Structure\FunctionTemplate; /** * Class AbstractTemplate * @package DCarbone\PHPClassBuilder\Template */ abstract class AbstractTemplate implements TemplateInterface { /** * TODO: All templates MUST be able to compile with no options * * @return string */ public function __toString() { return $this->compile(); } /** * @param mixed $name * @return InvalidClassNameException */ protected function createInvalidClassNameException($name) { return new InvalidClassNameException(sprintf( '%s - Specified class name "%s" is not valid. Please see http://php.net/manual/en/language.oop5.basic.php for more information.', get_class($this), $this->_determineExceptionValueOutput($name) )); } /** * @param mixed $name * @return InvalidInterfaceNameException */ protected function createInvalidInterfaceNameException($name) { return new InvalidInterfaceNameException(sprintf( '%s - Specified interface name "%s" is not valid. Please see http://php.net/manual/en/language.oop5.basic.php for more information.', get_class($this), $this->_determineExceptionValueOutput($name) )); } /** * @param mixed $namespace * @return InvalidNamespaceNameException */ protected function createInvalidNamespaceNameException($namespace) { return new InvalidNamespaceNameException(sprintf( '%s - Specified namespace "%s" is not valid. Please see http://php.net/manual/en/language.oop5.basic.php for more information', get_class($this), $this->_determineExceptionValueOutput($namespace) )); } /** * @param string $name * @return \DCarbone\PHPClassBuilder\Exception\InvalidFunctionNameException */ protected function createInvalidFunctionNameException($name) { return new InvalidFunctionNameException(sprintf( '%s - Specified method name "%s" is not valid. Please see http://php.net/manual/en/language.oop5.basic.php for more information', get_class($this), $this->_determineExceptionValueOutput($name) )); } /** * @param string $name * @return \DCarbone\PHPClassBuilder\Exception\InvalidVariableNameException */ protected function createInvalidVariableNameException($name) { return new InvalidVariableNameException(sprintf( '%s - Specified variable name "%s" is not valid. Please see http://php.net/manual/en/language.oop5.basic.php for more information', get_class($this), $this->_determineExceptionValueOutput($name) )); } /** * @param string $context * @return \DCarbone\PHPClassBuilder\Exception\MissingNameException */ protected function createMissingNameException($context) { return new MissingNameException(sprintf( '%s - %s', get_class($this), $context )); } /** * @param string $arg * @param string $expectedStatement * @param mixed $actualValue * @return \DCarbone\PHPClassBuilder\Exception\InvalidCompileOptionValueException */ protected function createInvalidCompileOptionValueException($arg, $expectedStatement, $actualValue) { return new InvalidCompileOptionValueException(sprintf( '%s - Specified invalid value "%s" for compile argument "%s". Expected: %s', get_class($this), $this->_determineExceptionValueOutput($actualValue), $arg, $expectedStatement )); } /** * @param mixed $sought * @return \OutOfBoundsException */ protected function createFilePartNotFoundException($sought) { return new FilePartNotFoundException(sprintf( '%s - Specified invalid offset "%s".', get_class($this), $this->_determineExceptionValueOutput($sought) )); } /** * @param mixed $part * @return InvalidFilePartException */ protected function createInvalidFilePartException($part) { return new InvalidFilePartException(sprintf( '%s - Files may only contain Comments and Structures, attempted to add "%s".', get_class($this), $this->_determineExceptionValueOutput($part) )); } /** * @param mixed $path * @return InvalidOutputPathException */ protected function createInvalidOutputPathException($path) { return new InvalidOutputPathException(sprintf( '%s - Specified output path "%s" does not appear to be a valid filepath.', get_class($path), $this->_determineExceptionValueOutput($path) )); } /** * @param mixed $line * @return InvalidCommentLineArgumentException */ protected function createInvalidCommentLineArgumentException($line) { return new InvalidCommentLineArgumentException(sprintf( '%s - Comment lines must be scalar types, %s seen.', get_class($this), $this->_determineExceptionValueOutput($line) )); } /** * @param mixed $offset * @return CommentLineIndexNotFoundException */ protected function createCommentLineIndexNotFoundException($offset) { return new CommentLineIndexNotFoundException(sprintf( '%s - Comment has no line at index "%s"', get_class($this), $this->_determineExceptionValueOutput($offset) )); } /** * @param mixed $line * @return InvalidFunctionBodyPartArgumentException */ protected function createInvalidFunctionBodyPartArgumentException($line) { return new InvalidFunctionBodyPartArgumentException(sprintf( '%s - Function body lines must be strings, %s seen.', get_class($this), $this->_determineExceptionValueOutput($line) )); } /** * @param mixed $argument * @return InvalidInterfaceParentArgumentException */ protected function createInvalidInterfaceParentArgumentException($argument) { return new InvalidInterfaceParentArgumentException(sprintf( '%s - Interface parent arguments must either be a string or an instance of InterfaceTemplate, %s seen.', get_class($this), $this->_determineExceptionValueOutput($argument) )); } /** * @param FunctionTemplate $function * @return InvalidInterfaceFunctionScopeException */ protected function createInvalidInterfaceFunctionScopeException(FunctionTemplate $function) { return new InvalidInterfaceFunctionScopeException(sprintf( '%s - Interface functions must be public, added function %s has scope of %s.', get_class($this), $this->_determineExceptionValueOutput($function->getName()), (string)$function->getScope() )); } /** * @param mixed $value * @return string */ private function _determineExceptionValueOutput($value) { switch (gettype($value)) { case 'string': return $value; case 'integer': case 'double': return (string)$value; case 'boolean': return $value ? '(boolean)TRUE' : '(boolean)FALSE'; case 'null': return 'NULL'; case 'array': return 'array'; case 'object': return get_class($value); case 'resource': return get_resource_type($value); default: return 'UNKNOWN'; } } }
dcarbone/php-class-builder
src/Template/AbstractTemplate.php
PHP
apache-2.0
9,603
/** * 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 tools.descartes.teastore.persistence.rest; import java.util.ArrayList; import java.util.List; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.QueryParam; import tools.descartes.teastore.persistence.domain.OrderItemRepository; import tools.descartes.teastore.persistence.repository.DataGenerator; import tools.descartes.teastore.registryclient.util.AbstractCRUDEndpoint; import tools.descartes.teastore.entities.OrderItem; /** * Persistence endpoint for for CRUD operations on orders. * @author Joakim von Kistowski * */ @Path("orderitems") public class OrderItemEndpoint extends AbstractCRUDEndpoint<OrderItem> { /** * {@inheritDoc} */ @Override protected long createEntity(final OrderItem orderItem) { if (DataGenerator.GENERATOR.isMaintenanceMode()) { return -1L; } return OrderItemRepository.REPOSITORY.createEntity(orderItem); } /** * {@inheritDoc} */ @Override protected OrderItem findEntityById(final long id) { OrderItem item = OrderItemRepository.REPOSITORY.getEntity(id); if (item == null) { return null; } return new OrderItem(item); } /** * {@inheritDoc} */ @Override protected List<OrderItem> listAllEntities(final int startIndex, final int maxResultCount) { List<OrderItem> orderItems = new ArrayList<OrderItem>(); for (OrderItem oi : OrderItemRepository.REPOSITORY.getAllEntities(startIndex, maxResultCount)) { orderItems.add(new OrderItem(oi)); } return orderItems; } /** * {@inheritDoc} */ @Override protected boolean updateEntity(long id, OrderItem orderItem) { return OrderItemRepository.REPOSITORY.updateEntity(id, orderItem); } /** * {@inheritDoc} */ @Override protected boolean deleteEntity(long id) { if (DataGenerator.GENERATOR.isMaintenanceMode()) { return false; } return OrderItemRepository.REPOSITORY.removeEntity(id); } /** * Returns all order items with the given product Id (all order items for that product). * @param productId The id of the product. * @param startPosition The index (NOT ID) of the first order item with the product to return. * @param maxResult The max number of order items to return. * @return list of order items with the product. */ @GET @Path("product/{product:[0-9][0-9]*}") public List<OrderItem> listAllForProduct(@PathParam("product") final Long productId, @QueryParam("start") final Integer startPosition, @QueryParam("max") final Integer maxResult) { if (productId == null) { return listAll(startPosition, maxResult); } List<OrderItem> orderItems = new ArrayList<OrderItem>(); for (OrderItem oi : OrderItemRepository.REPOSITORY.getAllEntitiesWithProduct(productId, parseIntQueryParam(startPosition), parseIntQueryParam(maxResult))) { orderItems.add(new OrderItem(oi)); } return orderItems; } /** * Returns all order items with the given order Id (all order items for that order). * @param orderId The id of the product. * @param startPosition The index (NOT ID) of the first order item with the product to return. * @param maxResult The max number of order items to return. * @return list of order items with the product. */ @GET @Path("order/{order:[0-9][0-9]*}") public List<OrderItem> listAllForOrder(@PathParam("order") final Long orderId, @QueryParam("start") final Integer startPosition, @QueryParam("max") final Integer maxResult) { if (orderId == null) { return listAll(startPosition, maxResult); } List<OrderItem> orderItems = new ArrayList<OrderItem>(); for (OrderItem oi : OrderItemRepository.REPOSITORY.getAllEntitiesWithOrder(orderId, parseIntQueryParam(startPosition), parseIntQueryParam(maxResult))) { orderItems.add(new OrderItem(oi)); } return orderItems; } }
DescartesResearch/Pet-Supply-Store
services/tools.descartes.teastore.persistence/src/main/java/tools/descartes/teastore/persistence/rest/OrderItemEndpoint.java
Java
apache-2.0
4,492
package apple.mlcompute; import apple.NSObject; import apple.foundation.NSArray; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import apple.foundation.protocol.NSCopying; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.MappedReturn; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; /** * MLCRMSPropOptimizer * <p> * The MLCRMSPropOptimizer specifies the RMSProp optimizer. */ @Generated @Library("MLCompute") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class MLCRMSPropOptimizer extends MLCOptimizer implements NSCopying { static { NatJ.register(); } @Generated protected MLCRMSPropOptimizer(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Owned @Selector("alloc") public static native MLCRMSPropOptimizer alloc(); @Owned @Generated @Selector("allocWithZone:") public static native MLCRMSPropOptimizer allocWithZone(VoidPtr zone); /** * [@property] alpha * <p> * The smoothing constant. * <p> * The default is 0.99. */ @Generated @Selector("alpha") public native float alpha(); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Owned @Selector("copyWithZone:") @MappedReturn(ObjCObjectMapper.class) public native Object copyWithZone(VoidPtr zone); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); /** * [@property] epsilon * <p> * A term added to improve numerical stability. * <p> * The default is 1e-8. */ @Generated @Selector("epsilon") public native float epsilon(); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("init") public native MLCRMSPropOptimizer init(); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); /** * [@property] isCentered * <p> * If True, compute the centered RMSProp, the gradient is normalized by an estimation of its variance. * <p> * The default is false. */ @Generated @Selector("isCentered") public native boolean isCentered(); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key); /** * [@property] momentumScale * <p> * The momentum factor. A hyper-parameter. * <p> * The default is 0.0. */ @Generated @Selector("momentumScale") public native float momentumScale(); @Generated @Owned @Selector("new") public static native MLCRMSPropOptimizer new_objc(); /** * Create a MLCRMSPropOptimizer object with defaults * * @return A new MLCRMSPropOptimizer object. */ @Generated @Selector("optimizerWithDescriptor:") public static native MLCRMSPropOptimizer optimizerWithDescriptor(MLCOptimizerDescriptor optimizerDescriptor); /** * Create a MLCRMSPropOptimizer object * * @param optimizerDescriptor The optimizer descriptor object * @param momentumScale The momentum scale * @param alpha The smoothing constant value * @param epsilon The epsilon value to use to improve numerical stability * @param isCentered A boolean to specify whether to compute the centered RMSProp or not * @return A new MLCRMSPropOptimizer object. */ @Generated @Selector("optimizerWithDescriptor:momentumScale:alpha:epsilon:isCentered:") public static native MLCRMSPropOptimizer optimizerWithDescriptorMomentumScaleAlphaEpsilonIsCentered( MLCOptimizerDescriptor optimizerDescriptor, float momentumScale, float alpha, float epsilon, boolean isCentered); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("version") @NInt public static native long version_static(); }
multi-os-engine/moe-core
moe.apple/moe.platform.ios/src/main/java/apple/mlcompute/MLCRMSPropOptimizer.java
Java
apache-2.0
6,672
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ /** * External dependencies */ import styled from 'styled-components'; import PropTypes from 'prop-types'; import { Popup } from '@googleforcreators/design-system'; import { __ } from '@googleforcreators/i18n'; /** * Internal dependencies */ import { useCanvas, useConfig } from '../../../app'; import useElementsWithLinks from '../../../utils/useElementsWithLinks'; import { OUTLINK_THEME } from '../../../constants'; import DefaultIcon from './icons/defaultIcon.svg'; import ArrowIcon from './icons/arrowBar.svg'; const Wrapper = styled.div` position: absolute; display: flex; align-items: center; justify-content: flex-end; flex-direction: column; bottom: 0; height: 20%; width: 100%; color: ${({ theme }) => theme.colors.standard.white}; z-index: 3; `; const Guideline = styled.div` mix-blend-mode: difference; position: absolute; height: 1px; bottom: 20%; width: 100%; background-image: ${({ theme }) => `linear-gradient(to right, ${theme.colors.standard.black} 50%, ${theme.colors.standard.white} 0%)`}; background-position: top; background-size: 16px 0.5px; background-repeat: repeat-x; z-index: 3; `; // The CSS here is based on how it's displayed in the front-end, including static // font-size, line-height, etc. independent of the viewport size -- it's not responsive. const ArrowBar = styled(ArrowIcon)` display: block; cursor: pointer; margin-bottom: 10px; filter: drop-shadow(0px 2px 6px rgba(0, 0, 0, 0.3)); width: 20px; height: 8px; `; const OutlinkChip = styled.div` height: 36px; display: flex; position: relative; padding: 10px 6px; margin: 0 0 20px; max-width: calc(100% - 64px); border-radius: 30px; place-items: center; box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.15); background: ${({ bgColor }) => bgColor}; `; const TextWrapper = styled.span` font-family: Roboto, sans-serif; font-size: 16px; line-height: 18px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; position: relative; padding-inline-start: 6px; padding-inline-end: 8px; height: 16px; letter-spacing: 0.3px; font-weight: 700; max-width: 210px; color: ${({ fgColor }) => fgColor}; `; const Tooltip = styled.div` background-color: ${({ theme }) => theme.colors.standard.black}; color: ${({ theme }) => theme.colors.standard.white}; width: 200px; padding: 8px; font-size: 14px; border-radius: 4px; text-align: center; `; const LinkImage = styled.div` height: 24px; width: 24px; vertical-align: middle; background-size: cover; background-repeat: no-repeat; background-position: 50%; border-radius: 50%; background-image: url('${({ icon }) => icon}') !important; `; const spacing = { x: 8 }; const LIGHT_COLOR = '#FFFFFF'; const DARK_COLOR = '#000000'; function PageAttachment({ pageAttachment = {} }) { const { displayLinkGuidelines, pageAttachmentContainer, setPageAttachmentContainer, } = useCanvas((state) => ({ displayLinkGuidelines: state.state.displayLinkGuidelines, pageAttachmentContainer: state.state.pageAttachmentContainer, setPageAttachmentContainer: state.actions.setPageAttachmentContainer, })); const { hasInvalidLinkSelected } = useElementsWithLinks(); const { ctaText = __('Learn more', 'web-stories'), url, icon, theme, } = pageAttachment; const { isRTL, styleConstants: { topOffset } = {} } = useConfig(); const bgColor = theme === OUTLINK_THEME.DARK ? DARK_COLOR : LIGHT_COLOR; const fgColor = theme === OUTLINK_THEME.DARK ? LIGHT_COLOR : DARK_COLOR; return ( <> {(displayLinkGuidelines || hasInvalidLinkSelected) && <Guideline />} <Wrapper role="presentation" ref={setPageAttachmentContainer}> {url?.length > 0 && ( <> <ArrowBar fill={bgColor} /> <OutlinkChip bgColor={bgColor}> {icon ? ( <LinkImage icon={icon} /> ) : ( <DefaultIcon fill={fgColor} width={24} height={24} /> )} <TextWrapper fgColor={fgColor}>{ctaText}</TextWrapper> </OutlinkChip> {pageAttachmentContainer && hasInvalidLinkSelected && ( <Popup isRTL={isRTL} anchor={{ current: pageAttachmentContainer }} isOpen placement={'left'} spacing={spacing} topOffset={topOffset} > <Tooltip> {__( 'Links can not reside below the dashed line when a page attachment is present. Your viewers will not be able to click on the link.', 'web-stories' )} </Tooltip> </Popup> )} </> )} </Wrapper> </> ); } PageAttachment.propTypes = { pageAttachment: PropTypes.shape({ url: PropTypes.string, ctaText: PropTypes.string, }), }; export default PageAttachment;
GoogleForCreators/web-stories-wp
packages/story-editor/src/components/canvas/pageAttachment/index.js
JavaScript
apache-2.0
5,600
package com.jflyfox.dudu.module.system.dao; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.jflyfox.dudu.component.model.Query; import com.jflyfox.dudu.module.system.model.SysMenu; import com.jflyfox.util.StrUtils; import org.apache.ibatis.annotations.SelectProvider; import org.apache.ibatis.jdbc.SQL; import java.util.List; /** * 菜单 数据层 * * @author flyfox 369191470@qq.com on 2017-06-20. */ public interface MenuMapper extends BaseMapper<SysMenu> { @SelectProvider(type = SqlBuilder.class, method = "selectMenuPage") List<SysMenu> selectMenuPage(Query query); class SqlBuilder { public String selectMenuPage(Query query) { String sqlColumns = "t.id,t.parentid,t.name,t.urlkey,t.url,t.status,t.type,t.sort,t.level,t.enable,t.update_time as updateTime,t.update_id as updateId,t.create_time as createTime,t.create_id as createId"; return new SQL() {{ SELECT(sqlColumns + " ,p.name as parentName,uu.username as updateName,uc.username as createName"); FROM(" sys_menu t "); LEFT_OUTER_JOIN(" sys_user uu on t.update_id = uu.id "); LEFT_OUTER_JOIN(" sys_user uc on t.create_id = uc.id "); LEFT_OUTER_JOIN(" sys_menu p on t.parentid = p.id "); if (StrUtils.isNotEmpty(query.getStr("name"))) { WHERE(" t.name like concat('%',#{name},'%')"); } if (StrUtils.isNotEmpty(query.getOrderBy())) { ORDER_BY(query.getOrderBy()); } else { ORDER_BY(" t.id desc"); } }}.toString(); } } }
jflyfox/dudu
dudu-admin/src/main/java/com/jflyfox/dudu/module/system/dao/MenuMapper.java
Java
apache-2.0
1,715
/** * * Copyright 2003-2007 Jive Software. * * 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.jivesoftware.smack.chat; import java.util.Collections; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import org.jivesoftware.smack.SmackException.NotConnectedException; import org.jivesoftware.smack.StanzaCollector; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.util.StringUtils; import org.jxmpp.jid.EntityJid; /** * A chat is a series of messages sent between two users. Each chat has a unique * thread ID, which is used to track which messages are part of a particular * conversation. Some messages are sent without a thread ID, and some clients * don't send thread IDs at all. Therefore, if a message without a thread ID * arrives it is routed to the most recently created Chat with the message * sender. * * @author Matt Tucker * @deprecated use <code>org.jivesoftware.smack.chat2.Chat</code> from <code>smack-extensions</code> instead. */ @Deprecated public class Chat { private final ChatManager chatManager; private final String threadID; private final EntityJid participant; private final Set<ChatMessageListener> listeners = new CopyOnWriteArraySet<>(); /** * Creates a new chat with the specified user and thread ID. * * @param chatManager the chatManager the chat will use. * @param participant the user to chat with. * @param threadID the thread ID to use. */ Chat(ChatManager chatManager, EntityJid participant, String threadID) { if (StringUtils.isEmpty(threadID)) { throw new IllegalArgumentException("Thread ID must not be null"); } this.chatManager = chatManager; this.participant = participant; this.threadID = threadID; } /** * Returns the thread id associated with this chat, which corresponds to the * <tt>thread</tt> field of XMPP messages. This method may return <tt>null</tt> * if there is no thread ID is associated with this Chat. * * @return the thread ID of this chat. */ public String getThreadID() { return threadID; } /** * Returns the name of the user the chat is with. * * @return the name of the user the chat is occuring with. */ public EntityJid getParticipant() { return participant; } /** * Sends the specified text as a message to the other chat participant. * This is a convenience method for: * * <pre> * Message message = chat.createMessage(); * message.setBody(messageText); * chat.sendMessage(message); * </pre> * * @param text the text to send. * @throws NotConnectedException * @throws InterruptedException */ public void sendMessage(String text) throws NotConnectedException, InterruptedException { Message message = new Message(); message.setBody(text); sendMessage(message); } /** * Sends a message to the other chat participant. The thread ID, recipient, * and message type of the message will automatically set to those of this chat. * * @param message the message to send. * @throws NotConnectedException * @throws InterruptedException */ public void sendMessage(Message message) throws NotConnectedException, InterruptedException { // Force the recipient, message type, and thread ID since the user elected // to send the message through this chat object. message.setTo(participant); message.setType(Message.Type.chat); message.setThread(threadID); chatManager.sendMessage(this, message); } /** * Adds a stanza(/packet) listener that will be notified of any new messages in the * chat. * * @param listener a stanza(/packet) listener. */ public void addMessageListener(ChatMessageListener listener) { if (listener == null) { return; } // TODO these references should be weak. listeners.add(listener); } public void removeMessageListener(ChatMessageListener listener) { listeners.remove(listener); } /** * Closes the Chat and removes all references to it from the {@link ChatManager}. The chat will * be unusable when this method returns, so it's recommend to drop all references to the * instance right after calling {@link #close()}. */ public void close() { chatManager.closeChat(this); listeners.clear(); } /** * Returns an unmodifiable set of all of the listeners registered with this chat. * * @return an unmodifiable set of all of the listeners registered with this chat. */ public Set<ChatMessageListener> getListeners() { return Collections.unmodifiableSet(listeners); } /** * Creates a {@link org.jivesoftware.smack.StanzaCollector} which will accumulate the Messages * for this chat. Always cancel StanzaCollectors when finished with them as they will accumulate * messages indefinitely. * * @return the StanzaCollector which returns Messages for this chat. */ public StanzaCollector createCollector() { return chatManager.createStanzaCollector(this); } /** * Delivers a message directly to this chat, which will add the message * to the collector and deliver it to all listeners registered with the * Chat. This is used by the XMPPConnection class to deliver messages * without a thread ID. * * @param message the message. */ void deliver(Message message) { // Because the collector and listeners are expecting a thread ID with // a specific value, set the thread ID on the message even though it // probably never had one. message.setThread(threadID); for (ChatMessageListener listener : listeners) { listener.processMessage(this, message); } } @Override public String toString() { return "Chat [(participant=" + participant + "), (thread=" + threadID + ")]"; } @Override public int hashCode() { int hash = 1; hash = hash * 31 + threadID.hashCode(); hash = hash * 31 + participant.hashCode(); return hash; } @Override public boolean equals(Object obj) { return obj instanceof Chat && threadID.equals(((Chat) obj).getThreadID()) && participant.equals(((Chat) obj).getParticipant()); } }
vanitasvitae/smack-omemo
smack-im/src/main/java/org/jivesoftware/smack/chat/Chat.java
Java
apache-2.0
7,127
module.exports = function (config) { 'use strict'; config.set({ basePath: '../', files: [ // Angular libraries. 'app/assets/lib/angular/angular.js', 'app/assets/lib/angular-ui-router/release/angular-ui-router.js', 'app/assets/lib/angular-bootstrap/ui-bootstrap.min.js', 'app/assets/lib/angular-mocks/angular-mocks.js', 'app/assets/lib/angular-bootstrap/ui-bootstrap-tpls.min.js', 'app/assets/lib/angular-busy/dist/angular-busy.min.js', 'app/assets/lib/angular-resource/angular-resource.min.js', 'app/assets/lib/angular-confirm-modal/angular-confirm.js', // JS files. 'app/app.js', 'app/components/**/*.js', 'app/shared/*.js', 'app/shared/**/*.js', 'app/assets/js/*.js', // Test Specs. 'tests/unit/*.js' ], autoWatch: true, frameworks: ['jasmine'], browsers: ['Firefox', 'PhantomJS', 'Chrome'], plugins: [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-phantomjs-launcher', 'karma-jasmine' ], junitReporter: { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
markvoelker/refstack
refstack-ui/tests/karma.conf.js
JavaScript
apache-2.0
1,354
package edu.kit.tm.pseprak2.alushare.view; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.os.Environment; import android.util.Log; import java.io.IOException; /** * Represent the AudioRecorder of the ChatActivity. * Enables recording sound and playing the music before sending. * * Created by Arthur Anselm on 17.08.15. */ public class AudioRecorder { private String mFileName = null; private String TAG = "AudioRecorder"; private MediaRecorder mRecorder = null; private MediaPlayer mPlayer = null; private ChatController controller; private boolean busy; //private SeekBar mSeekbar; //private Handler mHandler; /** * The constructor of this class. * @param controller the controller for this audioRecorder object */ public AudioRecorder(ChatController controller){ if(controller == null){ throw new NullPointerException(); } this.controller = controller; //this.mSeekbar = seekBar; //this.mHandler = new Handler(); this.mFileName = Environment.getExternalStorageDirectory().getAbsolutePath(); this.mFileName += "/audiorecord_alushare.m4a"; this.busy = false; } /** * Invokes the method startRecording() (and sets busy to true) if start is true else * stopRecording(). * @param start boolean to start or stop recording */ public void onRecord(boolean start) { if (start) { busy = true; startRecording(); } else { stopRecording(); } } /** * Invokes startPlaying() if start is true else stopPlaying(). * @param start boolean to start or stop playing */ public void onPlay(boolean start) { if (start) { startPlaying(); } else { stopPlaying(); } } /** * Creates a new mediaPlayer and sets it up. After that starts playing the audoFile stored in * the filesPath mFileName */ private void startPlaying() { if(mFileName == null){ throw new NullPointerException("Recorded file is null."); } setUpMediaPlayer(); try { mPlayer.setDataSource(mFileName); mPlayer.prepare(); mPlayer.start(); } catch (IOException e) { Log.e(TAG, "prepare() failed"); } } /** * Creates a new mediaPlayer and sets the completion listener. */ private void setUpMediaPlayer(){ mPlayer = new MediaPlayer(); mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Log.e(TAG, " : Playing of Sound completed"); controller.setPlayButtonVisible(true); } }); /* mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(final MediaPlayer mp) { mSeekbar.setMax(mp.getDuration()); new Thread(new Runnable() { @Override public void run() { while (mp != null && mp.getCurrentPosition() < mp.getDuration()) { mSeekbar.setProgress(mp.getCurrentPosition()); Message msg = new Message(); int millis = mp.getCurrentPosition(); msg.obj = millis / 1000; mHandler.sendMessage(msg); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } });*/ } /** * Stops playing the mediaPlayer with the method release() and releases the references to the * mediaPlayer if the mediaPlayer isn't null. */ private void stopPlaying() { if(mPlayer != null) { mPlayer.release(); mPlayer = null; } else { Log.e(TAG, "MediaPlayer is null. stopPlaying() can't be executed."); } } /** * Creates a new mediaRecorder and set it up. * Start recording and saving the audio data into the file stored at fileName. */ private void startRecording() { mRecorder = new MediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); mRecorder.setAudioChannels(1); mRecorder.setAudioSamplingRate(44100); mRecorder.setAudioEncodingBitRate(96000); mRecorder.setOutputFile(mFileName); try { mRecorder.prepare(); } catch (IOException e) { Log.e(TAG, "prepare() failed"); return; } mRecorder.start(); } /** * Stops recording, invokes release of the mediaRecorder and releases the references to the * mediaRecorder if the mediaRecorder isn't null. */ private void stopRecording() { if(mRecorder != null) { mRecorder.stop(); mRecorder.release(); mRecorder = null; } else { Log.e(TAG, "MediaRecorder is null. stopRecording() can't be executed."); } } /** *Return the filePath of the recorded audio file * @return this.mFileName */ public String getFilePath(){ return mFileName; } /** * Sets the busyness of this audioRecorder * @param busy true if the audioRecorder is active else false */ public void setBusy(boolean busy){ this.busy = busy; } /** * Checks if this audioRecorder is active oder not. Returns busy. * @return busy */ public boolean isBusy(){ return busy; } }
weichweich/AluShare
app/src/main/java/edu/kit/tm/pseprak2/alushare/view/AudioRecorder.java
Java
apache-2.0
6,151
package com.zts.service.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = DataSourceProperties.DS, ignoreUnknownFields = false) public class DataSourceProperties { //对应配置文件里的配置键 public final static String DS="mysql"; private String driverClassName ="com.mysql.jdbc.Driver"; private String url; private String username; private String password; private int maxActive = 100; private int maxIdle = 8; private int minIdle = 8; private int initialSize = 10; private String validationQuery; public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getMaxActive() { return maxActive; } public void setMaxActive(int maxActive) { this.maxActive = maxActive; } public int getMaxIdle() { return maxIdle; } public void setMaxIdle(int maxIdle) { this.maxIdle = maxIdle; } public int getMinIdle() { return minIdle; } public void setMinIdle(int minIdle) { this.minIdle = minIdle; } public int getInitialSize() { return initialSize; } public void setInitialSize(int initialSize) { this.initialSize = initialSize; } public String getValidationQuery() { return validationQuery; } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } public boolean isTestOnBorrow() { return testOnBorrow; } public void setTestOnBorrow(boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } public boolean isTestOnReturn() { return testOnReturn; } public void setTestOnReturn(boolean testOnReturn) { this.testOnReturn = testOnReturn; } private boolean testOnBorrow = false; private boolean testOnReturn = false; }
tushengtuzhang/zts
cloud-simple-service/src/main/java/com/zts/service/config/DataSourceProperties.java
Java
apache-2.0
2,197
package com.github.approval.sesame; /* * #%L * approval-sesame * %% * Copyright (C) 2014 Nikolavp * %% * 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 com.github.approval.Reporter; import com.github.approval.reporters.ExecutableDifferenceReporter; import com.github.approval.reporters.Reporters; import com.github.approval.reporters.SwingInteractiveReporter; import java.io.File; /** * <p> * A reporter that can be used to verify dot files. It will compile the file to an image and open it through * {@link com.github.approval.reporters.Reporters#fileLauncher()}. * </p> * <p> * Note that this reporter cannot be used for anything else and will give you an error beceause it will * try to compile the verification file with the "dot" command. * </p> */ public final class GraphReporter extends ExecutableDifferenceReporter { /** * Get an instance of the reporter. * @return a graph reporter */ public static Reporter getInstance() { return SwingInteractiveReporter.wrap(new GraphReporter()); } /** * Main constructor for the executable reporter. */ private GraphReporter() { super("dot -T png -O ", "dot -T png -O ", "dot"); } private static File addPng(File file) { return new File(file.getAbsoluteFile().getAbsolutePath() + ".png"); } @Override public void approveNew(byte[] value, File approvalDestination, File fileForVerification) { super.approveNew(value, approvalDestination, fileForVerification); Reporters.fileLauncherWithoutInteraction().approveNew(value, addPng(approvalDestination), addPng(fileForVerification)); } @Override protected String[] buildApproveNewCommand(File approvalDestination, File fileForVerification) { return new String[]{getApprovalCommand(), approvalDestination.getAbsolutePath()}; } @Override protected String[] buildNotTheSameCommand(File fileForVerification, File fileForApproval) { return new String[]{getDiffCommand(), fileForApproval.getAbsolutePath()}; } @Override public void notTheSame(byte[] oldValue, File fileForVerification, byte[] newValue, File fileForApproval) { super.notTheSame(oldValue, fileForVerification, newValue, fileForApproval); Reporters.fileLauncherWithoutInteraction().notTheSame(oldValue, addPng(fileForVerification), newValue, addPng(fileForApproval)); } }
nikolavp/approval
approval-sesame/src/main/java/com/github/approval/sesame/GraphReporter.java
Java
apache-2.0
2,951
import { inject as service } from '@ember/service'; import Route from '@ember/routing/route'; import { get } from '@ember/object'; export default Route.extend({ access: service(), catalog: service(), scope: service(), beforeModel() { this._super(...arguments); return get(this, 'catalog').fetchUnScopedCatalogs().then((hash) => { this.set('catalogs', hash); }); }, model(params) { return get(this, 'catalog').fetchTemplates(params) .then((res) => { res.catalogs = get(this, 'catalogs'); return res; }); }, resetController(controller, isExiting/* , transition*/) { if (isExiting) { controller.setProperties({ category: '', catalogId: '', projectCatalogId: '', clusterCatalogId: '', }) } }, deactivate() { // Clear the cache when leaving the route so that it will be reloaded when you come back. this.set('cache', null); }, actions: { refresh() { // Clear the cache so it has to ask the server again this.set('cache', null); this.refresh(); }, }, queryParams: { category: { refreshModel: true }, catalogId: { refreshModel: true }, clusterCatalogId: { refreshModel: true }, projectCatalogId: { refreshModel: true }, }, });
lvuch/ui
lib/global-admin/addon/multi-cluster-apps/catalog/route.js
JavaScript
apache-2.0
1,345
package AbsSytree; import java.util.ArrayList; public class SynExprSeq extends AbsSynNode { public ArrayList<AbsSynNode> exprs; public SynExprSeq(AbsSynNode e) { this.exprs = new ArrayList<AbsSynNode>(); this.exprs.add(e); } public SynExprSeq append(AbsSynNode e) { this.exprs.add(e); return this; } @Override public Object visit(SynNodeVisitor visitor) { return visitor.visit(this); } @Override public void dumpNode(int indent) { for (int i = 0; i < this.exprs.size(); ++i) { this.exprs.get(i).dumpNode(indent); this.dumpFormat(indent, ";"); } } @Override public void clearAttr() { this.attr = null; for (int i = 0; i < this.exprs.size(); ++i) this.exprs.get(i).clearAttr(); } }
mingyuan-xia/TigerCC
src/AbsSytree/SynExprSeq.java
Java
apache-2.0
767
/** * Copyright 2017 Matthieu Jimenez. All rights reserved. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 paw.graph.customTypes.bitset; import greycat.base.BaseCustomType; import greycat.struct.EStructArray; import greycat.utility.HashHelper; import org.roaringbitmap.IntIterator; import java.util.List; public abstract class CTBitset extends BaseCustomType{ public static final String BITS = "bits"; protected static final int BITS_H = HashHelper.hash(BITS); public CTBitset(EStructArray p_backend) { super(p_backend); } public abstract void save(); public abstract void clear(); public abstract boolean add(int index); public abstract boolean addAll(List<Integer> indexs); public abstract void clear(int index); public abstract int size(); public abstract int cardinality(); public abstract boolean get(int index); public abstract int nextSetBit(int startIndex); public abstract IntIterator iterator(); }
greycat-incubator/Paw
src/main/java/paw/graph/customTypes/bitset/CTBitset.java
Java
apache-2.0
1,522
/* * Copyright (c) 2015 PLUMgrid, 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. */ #include "bcc_common.h" #include "bpf_module.h" extern "C" { void * bpf_module_create_c(const char *filename, unsigned flags, const char *cflags[], int ncflags, bool allow_rlimit, const char *dev_name) { auto mod = new ebpf::BPFModule(flags, nullptr, true, "", allow_rlimit, dev_name); if (mod->load_c(filename, cflags, ncflags) != 0) { delete mod; return nullptr; } return mod; } void * bpf_module_create_c_from_string(const char *text, unsigned flags, const char *cflags[], int ncflags, bool allow_rlimit, const char *dev_name) { auto mod = new ebpf::BPFModule(flags, nullptr, true, "", allow_rlimit, dev_name); if (mod->load_string(text, cflags, ncflags) != 0) { delete mod; return nullptr; } return mod; } bool bpf_module_rw_engine_enabled() { return ebpf::bpf_module_rw_engine_enabled(); } void bpf_module_destroy(void *program) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return; delete mod; } size_t bpf_num_functions(void *program) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return 0; return mod->num_functions(); } const char * bpf_function_name(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return nullptr; return mod->function_name(id); } void * bpf_function_start(void *program, const char *name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return nullptr; return mod->function_start(name); } void * bpf_function_start_id(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return nullptr; return mod->function_start(id); } size_t bpf_function_size(void *program, const char *name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return 0; return mod->function_size(name); } size_t bpf_function_size_id(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return 0; return mod->function_size(id); } char * bpf_module_license(void *program) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return nullptr; return mod->license(); } unsigned bpf_module_kern_version(void *program) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return 0; return mod->kern_version(); } size_t bpf_num_tables(void *program) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->num_tables(); } size_t bpf_table_id(void *program, const char *table_name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return ~0ull; return mod->table_id(table_name); } int bpf_table_fd(void *program, const char *table_name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->table_fd(table_name); } int bpf_table_fd_id(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->table_fd(id); } int bpf_table_type(void *program, const char *table_name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->table_type(table_name); } int bpf_table_type_id(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->table_type(id); } size_t bpf_table_max_entries(void *program, const char *table_name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return 0; return mod->table_max_entries(table_name); } size_t bpf_table_max_entries_id(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return 0; return mod->table_max_entries(id); } int bpf_table_flags(void *program, const char *table_name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->table_flags(table_name); } int bpf_table_flags_id(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->table_flags(id); } const char * bpf_table_name(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return nullptr; return mod->table_name(id); } const char * bpf_table_key_desc(void *program, const char *table_name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return nullptr; return mod->table_key_desc(table_name); } const char * bpf_table_key_desc_id(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return nullptr; return mod->table_key_desc(id); } const char * bpf_table_leaf_desc(void *program, const char *table_name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return nullptr; return mod->table_leaf_desc(table_name); } const char * bpf_table_leaf_desc_id(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return nullptr; return mod->table_leaf_desc(id); } size_t bpf_table_key_size(void *program, const char *table_name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return 0; return mod->table_key_size(table_name); } size_t bpf_table_key_size_id(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return 0; return mod->table_key_size(id); } size_t bpf_table_leaf_size(void *program, const char *table_name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return 0; return mod->table_leaf_size(table_name); } size_t bpf_table_leaf_size_id(void *program, size_t id) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return 0; return mod->table_leaf_size(id); } int bpf_table_key_snprintf(void *program, size_t id, char *buf, size_t buflen, const void *key) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->table_key_printf(id, buf, buflen, key); } int bpf_table_leaf_snprintf(void *program, size_t id, char *buf, size_t buflen, const void *leaf) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->table_leaf_printf(id, buf, buflen, leaf); } int bpf_table_key_sscanf(void *program, size_t id, const char *buf, void *key) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->table_key_scanf(id, buf, key); } int bpf_table_leaf_sscanf(void *program, size_t id, const char *buf, void *leaf) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->table_leaf_scanf(id, buf, leaf); } int bcc_func_load(void *program, int prog_type, const char *name, const struct bpf_insn *insns, int prog_len, const char *license, unsigned kern_version, int log_level, char *log_buf, unsigned log_buf_size, const char *dev_name) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return -1; return mod->bcc_func_load(prog_type, name, insns, prog_len, license, kern_version, log_level, log_buf, log_buf_size, dev_name); } size_t bpf_perf_event_fields(void *program, const char *event) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return 0; return mod->perf_event_fields(event); } const char * bpf_perf_event_field(void *program, const char *event, size_t i) { auto mod = static_cast<ebpf::BPFModule *>(program); if (!mod) return nullptr; return mod->perf_event_field(event, i); } }
iovisor/bcc
src/cc/bcc_common.cc
C++
apache-2.0
8,190
/** * Copyright Microsoft Corporation * * 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.microsoft.windowsazure.core.pipeline; import com.sun.jersey.core.util.Base64; import javax.xml.bind.annotation.adapters.XmlAdapter; /* * JAXB adapter for a Base64 encoded string element */ public class Base64StringAdapter extends XmlAdapter<String, String> { @Override public String marshal(String arg0) throws Exception { return new String(Base64.encode(arg0), "UTF-8"); } @Override public String unmarshal(String arg0) throws Exception { return Base64.base64Decode(arg0); } }
southworkscom/azure-sdk-for-java
core/azure-core/src/main/java/com/microsoft/windowsazure/core/pipeline/Base64StringAdapter.java
Java
apache-2.0
1,133
/** * Copyright 2016 William Van Woensel 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 wvw * */ package wvw.utils.rule.builder; public abstract class RuleBuilder { protected String id; protected StringBuffer templateClause = new StringBuffer(); protected StringBuffer conditionClause = new StringBuffer(); public RuleBuilder() { } public RuleBuilder(String id) { this.id = id; } public void appendTemplate(String template) { templateClause.append("\t").append(template); } public void appendCondition(String condition) { conditionClause.append("\t").append(condition); } public String getId() { return id; } public abstract String toString(); }
darth-willy/mobibench
MobiBenchWebService/src/main/java/wvw/utils/rule/builder/RuleBuilder.java
Java
apache-2.0
1,192
// Copyright 2012 Max Toro Q. // // 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. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace myxsl.saxon { static class StringExtensions { public static bool HasValue(this string s) { return !String.IsNullOrEmpty(s); } } }
maxtoroq/myxsl
src/myxsl.saxon/util/StringExtensions.cs
C#
apache-2.0
851
using System; using System.IO; using System.Text; namespace NuGet { public static class StreamExtensions { public static byte[] ReadAllBytes(this Stream stream) { var memoryStream = stream as MemoryStream; if (memoryStream != null) { return memoryStream.ToArray(); } else { using (memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); return memoryStream.ToArray(); } } } /// <summary> /// Turns an existing stream into one that a stream factory that can be reopened. /// </summary> public static Func<Stream> ToStreamFactory(this Stream stream) { byte[] buffer; using (var ms = new MemoryStream()) { stream.CopyTo(ms); buffer = ms.ToArray(); } return () => new MemoryStream(buffer); } public static string ReadToEnd(this Stream stream) { using (var streamReader = new StreamReader(stream)) { return streamReader.ReadToEnd(); } } public static Stream AsStream(this string value) { return AsStream(value, Encoding.UTF8); } public static Stream AsStream(this string value, Encoding encoding) { return new MemoryStream(encoding.GetBytes(value)); } public static bool ContentEquals(this Stream stream, Stream otherStream) { return Crc32.Calculate(stream) == Crc32.Calculate(otherStream); } } }
xero-github/Nuget
src/Core/Extensions/StreamExtensions.cs
C#
apache-2.0
1,831
/* * Copyright (c) 2010-2014. Axon Framework * * 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.axonframework.common.lock; /** * Interface to the lock factory. A lock factory produces locks on resources that are shared between threads. * * @author Allard Buijze * @since 0.3 */ public interface LockFactory { /** * Obtain a lock for a resource identified by given {@code identifier}. Depending on the strategy, this * method may return immediately or block until a lock is held. * * @param identifier the identifier of the resource to obtain a lock for. * @return a handle to release the lock. */ Lock obtainLock(String identifier); }
soulrebel/AxonFramework
core/src/main/java/org/axonframework/common/lock/LockFactory.java
Java
apache-2.0
1,205
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'litleleprikon' from random import randint FIGURES = ['камень', 'бумага', 'ножницы'] FIG_LEN = len(FIGURES) class Player: """ Player class is needed to store tactics and to generate figures by this tactic -- Doctests -- >>> player = Player() >>> player.figure in FIGURES True """ def __init__(self, number: int): self.name = 'игрок{}'.format(number) tactic = randint(0, FIG_LEN-1) self.main_figure = FIGURES[tactic] self.__figures = [FIGURES[(tactic+i) % FIG_LEN] for i in range(FIG_LEN)] def __str__(self): return '{}: {}'.format(self.name, self.main_figure) @property def figure(self): rand = randint(0, FIG_LEN) return self.__figures[rand % FIG_LEN]
litleleprikon/innopolis_test_task
problem_2_rock_paper_scissor/player.py
Python
apache-2.0
846
package site; public class Autocomplete { private final String label; private final String value; public Autocomplete(String label, String value) { this.label = label; this.value = value; } public final String getLabel() { return this.label; } public final String getValue() { return this.value; } }
CaroleneBertoldi/CountryDetails
country/src/main/java/site/Autocomplete.java
Java
apache-2.0
337
/* Copyright 2015 Crunchy Data Solutions, 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 adminapi import ( "github.com/ant0ine/go-json-rest/rest" "github.com/crunchydata/crunchy-postgresql-manager/admindb" "github.com/crunchydata/crunchy-postgresql-manager/cpmserverapi" "github.com/crunchydata/crunchy-postgresql-manager/logit" "github.com/crunchydata/crunchy-postgresql-manager/swarmapi" "github.com/crunchydata/crunchy-postgresql-manager/types" "github.com/crunchydata/crunchy-postgresql-manager/util" "net/http" "strings" ) const CONTAINER_NOT_FOUND = "CONTAINER NOT FOUND" // GetNode returns the container node definition func GetNode(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ID := r.PathParam("ID") if ID == "" { logit.Error.Println("error node ID required") rest.Error(w, "node ID required", http.StatusBadRequest) return } node, err2 := admindb.GetContainer(dbConn, ID) if node.ID == "" { rest.NotFound(w, r) return } if err2 != nil { logit.Error.Println(err2.Error()) rest.Error(w, err2.Error(), http.StatusBadRequest) return } var currentStatus = "UNKNOWN" request := &swarmapi.DockerInspectRequest{} var inspectInfo swarmapi.DockerInspectResponse request.ContainerName = node.Name inspectInfo, err = swarmapi.DockerInspect(request) if err != nil { logit.Error.Println(err.Error()) currentStatus = CONTAINER_NOT_FOUND } if currentStatus != "CONTAINER NOT FOUND" { var pgport types.Setting pgport, err = admindb.GetSetting(dbConn, "PG-PORT") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } currentStatus, err = util.FastPing(pgport.Value, node.Name) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } //logit.Info.Println("pinging db finished") } clusternode := new(types.ClusterNode) clusternode.ID = node.ID clusternode.ClusterID = node.ClusterID clusternode.Name = node.Name clusternode.Role = node.Role clusternode.Image = node.Image clusternode.CreateDate = node.CreateDate clusternode.Status = currentStatus clusternode.ProjectID = node.ProjectID clusternode.ProjectName = node.ProjectName clusternode.ClusterName = node.ClusterName clusternode.ServerID = inspectInfo.ServerID clusternode.IPAddress = inspectInfo.IPAddress w.WriteJson(clusternode) } // GetAllNodesForProject returns all node definitions for a given project func GetAllNodesForProject(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ID := r.PathParam("ID") if ID == "" { logit.Error.Println("project ID required") rest.Error(w, "project ID required", http.StatusBadRequest) return } results, err := admindb.GetAllContainersForProject(dbConn, ID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) } nodes := make([]types.ClusterNode, len(results)) i := 0 for i = range results { nodes[i].ID = results[i].ID nodes[i].Name = results[i].Name nodes[i].ClusterID = results[i].ClusterID nodes[i].Role = results[i].Role nodes[i].Image = results[i].Image nodes[i].CreateDate = results[i].CreateDate nodes[i].ProjectID = results[i].ProjectID nodes[i].ProjectName = results[i].ProjectName nodes[i].ClusterName = results[i].ClusterName //nodes[i].Status = "UNKNOWN" i++ } w.WriteJson(&nodes) } // TODO func GetAllNodes(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } results, err := admindb.GetAllContainers(dbConn) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) } nodes := make([]types.ClusterNode, len(results)) i := 0 for i = range results { nodes[i].ID = results[i].ID nodes[i].Name = results[i].Name nodes[i].ClusterID = results[i].ClusterID nodes[i].Role = results[i].Role nodes[i].Image = results[i].Image nodes[i].CreateDate = results[i].CreateDate nodes[i].ProjectID = results[i].ProjectID nodes[i].ProjectName = results[i].ProjectName nodes[i].ClusterName = results[i].ClusterName //nodes[i].Status = "UNKNOWN" i++ } w.WriteJson(&nodes) } // TODO func GetAllNodesNotInCluster(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } results, err := admindb.GetAllContainersNotInCluster(dbConn) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) } nodes := make([]types.ClusterNode, len(results)) i := 0 for i = range results { nodes[i].ID = results[i].ID nodes[i].Name = results[i].Name nodes[i].ClusterID = results[i].ClusterID nodes[i].Role = results[i].Role nodes[i].Image = results[i].Image nodes[i].CreateDate = results[i].CreateDate nodes[i].ProjectID = results[i].ProjectID nodes[i].ProjectName = results[i].ProjectName nodes[i].ClusterName = results[i].ClusterName //nodes[i].Status = "UNKNOWN" i++ } w.WriteJson(&nodes) } // GetAllNodesForCluster returns a list of nodes for a given cluster func GetAllNodesForCluster(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ClusterID := r.PathParam("ClusterID") if ClusterID == "" { logit.Error.Println("ClusterID required") rest.Error(w, "node ClusterID required", http.StatusBadRequest) return } results, err := admindb.GetAllContainersForCluster(dbConn, ClusterID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) } nodes := make([]types.ClusterNode, len(results)) i := 0 for i = range results { nodes[i].ID = results[i].ID nodes[i].Name = results[i].Name nodes[i].ClusterID = results[i].ClusterID nodes[i].Role = results[i].Role nodes[i].Image = results[i].Image nodes[i].CreateDate = results[i].CreateDate nodes[i].ProjectID = results[i].ProjectID nodes[i].ProjectName = results[i].ProjectName nodes[i].ClusterName = results[i].ClusterName //nodes[i].Status = "UNKNOWN" i++ } w.WriteJson(&nodes) } /* TODO refactor this to share code with DeleteCluster!!!!! */ func DeleteNode(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-container") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ID := r.PathParam("ID") if ID == "" { logit.Error.Println("DeleteNode: error node ID required") rest.Error(w, "node ID required", http.StatusBadRequest) return } //go get the node we intend to delete var dbNode types.Container dbNode, err = admindb.GetContainer(dbConn, ID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } var infoResponse swarmapi.DockerInfoResponse infoResponse, err = swarmapi.DockerInfo() if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusInternalServerError) return } servers := make([]types.Server, len(infoResponse.Output)) i := 0 for i = range infoResponse.Output { servers[i].ID = infoResponse.Output[i] servers[i].Name = infoResponse.Output[i] servers[i].IPAddress = infoResponse.Output[i] i++ } var pgdatapath types.Setting pgdatapath, err = admindb.GetSetting(dbConn, "PG-DATA-PATH") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } err = admindb.DeleteContainer(dbConn, ID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } logit.Info.Println("remove 1") //it is possible that someone can remove a container //outside of us, so we let it pass that we can't remove //it request := &swarmapi.DockerRemoveRequest{} request.ContainerName = dbNode.Name _, err = swarmapi.DockerRemove(request) if err != nil { logit.Error.Println(err.Error()) } logit.Info.Println("remove 2") //send the server a deletevolume command request2 := &cpmserverapi.DiskDeleteRequest{} request2.Path = pgdatapath.Value + "/" + dbNode.Name for _, each := range servers { _, err = cpmserverapi.DiskDeleteClient(each.Name, request2) if err != nil { logit.Error.Println(err.Error()) } } logit.Info.Println("remove 3") //we should not have to delete the DNS entries because //of the dnsbridge, it should remove them when we remove //the containers via the docker api w.WriteHeader(http.StatusOK) status := types.SimpleStatus{} status.Status = "OK" w.WriteJson(&status) } // GetAllNodesForServer returns a list of all nodes on a given server func GetAllNodesForServer(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } serverID := r.PathParam("ServerID") if serverID == "" { logit.Error.Println("GetAllNodesForServer: error serverID required") rest.Error(w, "serverID required", http.StatusBadRequest) return } serverIPAddress := strings.Replace(serverID, "_", ".", -1) results, err := swarmapi.DockerPs(serverIPAddress) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } nodes := make([]types.ClusterNode, len(results.Output)) i := 0 var container types.Container for _, each := range results.Output { logit.Info.Println("got back Name:" + each.Name + " Status:" + each.Status + " Image:" + each.Image) nodes[i].Name = each.Name container, err = admindb.GetContainerByName(dbConn, each.Name) if err != nil { logit.Error.Println(err.Error()) nodes[i].ID = "unknown" nodes[i].ProjectID = "unknown" } else { nodes[i].ID = container.ID nodes[i].ProjectID = container.ProjectID } nodes[i].Status = each.Status nodes[i].Image = each.Image i++ } w.WriteJson(&nodes) } // AdminStartNode starts a container func AdminStartNode(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ID := r.PathParam("ID") if ID == "" { logit.Error.Println("AdminStartNode: error ID required") rest.Error(w, "ID required", http.StatusBadRequest) return } node, err := admindb.GetContainer(dbConn, ID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } /** server := types.Server{} server, err = admindb.GetServer(dbConn, node.ServerID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } */ var response swarmapi.DockerStartResponse request := &swarmapi.DockerStartRequest{} request.ContainerName = node.Name response, err = swarmapi.DockerStart(request) if err != nil { logit.Error.Println(err.Error()) logit.Error.Println(response.Output) } //logit.Info.Println(response.Output) w.WriteHeader(http.StatusOK) status := types.SimpleStatus{} status.Status = "OK" w.WriteJson(&status) } // AdminStopNode stops a container func AdminStopNode(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } ID := r.PathParam("ID") if ID == "" { logit.Error.Println("AdminStopNode: error ID required") rest.Error(w, "ID required", http.StatusBadRequest) return } node, err := admindb.GetContainer(dbConn, ID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } /** server := types.Server{} server, err = admindb.GetServer(dbConn, node.ServerID) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } */ request := &swarmapi.DockerStopRequest{} request.ContainerName = node.Name _, err = swarmapi.DockerStop(request) if err != nil { logit.Error.Println(err.Error()) } w.WriteHeader(http.StatusOK) status := types.SimpleStatus{} status.Status = "OK" w.WriteJson(&status) } // AdminStartServerContainers starts all containers on a given server func AdminStartServerContainers(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } //serverID serverid := r.PathParam("ID") if serverid == "" { logit.Error.Println(" error ID required") rest.Error(w, "ID required", http.StatusBadRequest) return } cleanIP := strings.Replace(serverid, "_", ".", -1) containers, err := swarmapi.DockerPs(cleanIP) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } //for each, get server, start container //use a 'best effort' approach here since containers //can be removed outside of CPM's control for _, each := range containers.Output { //start the container var response swarmapi.DockerStartResponse var err error request := &swarmapi.DockerStartRequest{} logit.Info.Println("trying to start " + each.Name) request.ContainerName = each.Name response, err = swarmapi.DockerStart(request) if err != nil { logit.Error.Println("AdminStartServerContainers: error when trying to start container " + err.Error()) logit.Error.Println(response.Output) } //logit.Info.Println(response.Output) } w.WriteHeader(http.StatusOK) status := types.SimpleStatus{} status.Status = "OK" w.WriteJson(&status) } // AdminStopServerContainers stops all containers on a given server func AdminStopServerContainers(w rest.ResponseWriter, r *rest.Request) { dbConn, err := util.GetConnection(CLUSTERADMIN_DB) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), 400) return } defer dbConn.Close() err = secimpl.Authorize(dbConn, r.PathParam("Token"), "perm-read") if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusUnauthorized) return } //serverID serverid := r.PathParam("ID") if serverid == "" { logit.Error.Println("AdminStopoServerContainers: error ID required") rest.Error(w, "ID required", http.StatusBadRequest) return } cleanIP := strings.Replace(serverid, "_", ".", -1) containers, err := swarmapi.DockerPs(cleanIP) if err != nil { logit.Error.Println(err.Error()) rest.Error(w, err.Error(), http.StatusBadRequest) return } //for each, get server, stop container for _, each := range containers.Output { if strings.HasPrefix(each.Status, "Up") { //stop container request := &swarmapi.DockerStopRequest{} request.ContainerName = each.Name logit.Info.Println("stopping " + request.ContainerName) _, err = swarmapi.DockerStop(request) if err != nil { logit.Error.Println("AdminStopServerContainers: error when trying to start container " + err.Error()) } } } w.WriteHeader(http.StatusOK) status := types.SimpleStatus{} status.Status = "OK" w.WriteJson(&status) }
CrunchyData/crunchy-postgresql-manager
adminapi/containermgmt.go
GO
apache-2.0
18,288
<?php final class DifferentialLandingActionMenuEventListener extends PhabricatorEventListener { public function register() { $this->listen(PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS); } public function handleEvent(PhutilEvent $event) { switch ($event->getType()) { case PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS: $this->handleActionsEvent($event); break; } } private function handleActionsEvent(PhutilEvent $event) { $object = $event->getValue('object'); $actions = null; if ($object instanceof DifferentialRevision) { $actions = $this->renderRevisionAction($event); } $this->addActionMenuItems($event, $actions); } private function renderRevisionAction(PhutilEvent $event) { if (!$this->canUseApplication($event->getUser())) { return null; } $revision = $event->getValue('object'); $repository = $revision->getRepository(); if ($repository === null) { return null; } $strategies = id(new PhutilSymbolLoader()) ->setAncestorClass('DifferentialLandingStrategy') ->loadObjects(); foreach ($strategies as $strategy) { $actions = $strategy->createMenuItems( $event->getUser(), $revision, $repository); $this->addActionMenuItems($event, $actions); } } }
yangming85/phabricator
src/applications/differential/landing/DifferentialLandingActionMenuEventListener.php
PHP
apache-2.0
1,348
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.cluster.routing; import com.carrotsearch.hppc.ObjectIntHashMap; import com.carrotsearch.hppc.cursors.ObjectCursor; import org.apache.lucene.util.CollectionUtil; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlocks; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Randomness; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.index.Index; import org.elasticsearch.index.shard.ShardId; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Predicate; /** * {@link RoutingNodes} represents a copy the routing information contained in * the {@link ClusterState cluster state}. */ public class RoutingNodes implements Iterable<RoutingNode> { private final MetaData metaData; private final ClusterBlocks blocks; private final RoutingTable routingTable; private final Map<String, RoutingNode> nodesToShards = new HashMap<>(); private final UnassignedShards unassignedShards = new UnassignedShards(this); private final Map<ShardId, List<ShardRouting>> assignedShards = new HashMap<>(); private final ImmutableOpenMap<String, ClusterState.Custom> customs; private final boolean readOnly; private int inactivePrimaryCount = 0; private int inactiveShardCount = 0; private int relocatingShards = 0; private final Map<String, ObjectIntHashMap<String>> nodesPerAttributeNames = new HashMap<>(); private final Map<String, Recoveries> recoveryiesPerNode = new HashMap<>(); public RoutingNodes(ClusterState clusterState) { this(clusterState, true); } public RoutingNodes(ClusterState clusterState, boolean readOnly) { this.readOnly = readOnly; this.metaData = clusterState.metaData(); this.blocks = clusterState.blocks(); this.routingTable = clusterState.routingTable(); this.customs = clusterState.customs(); Map<String, List<ShardRouting>> nodesToShards = new HashMap<>(); // fill in the nodeToShards with the "live" nodes for (ObjectCursor<DiscoveryNode> cursor : clusterState.nodes().dataNodes().values()) { nodesToShards.put(cursor.value.id(), new ArrayList<>()); } // fill in the inverse of node -> shards allocated // also fill replicaSet information for (ObjectCursor<IndexRoutingTable> indexRoutingTable : routingTable.indicesRouting().values()) { for (IndexShardRoutingTable indexShard : indexRoutingTable.value) { assert indexShard.primary != null; for (ShardRouting shard : indexShard) { // to get all the shards belonging to an index, including the replicas, // we define a replica set and keep track of it. A replica set is identified // by the ShardId, as this is common for primary and replicas. // A replica Set might have one (and not more) replicas with the state of RELOCATING. if (shard.assignedToNode()) { List<ShardRouting> entries = nodesToShards.computeIfAbsent(shard.currentNodeId(), k -> new ArrayList<>()); final ShardRouting sr = getRouting(shard, readOnly); entries.add(sr); assignedShardsAdd(sr); if (shard.relocating()) { relocatingShards++; entries = nodesToShards.computeIfAbsent(shard.relocatingNodeId(), k -> new ArrayList<>()); // add the counterpart shard with relocatingNodeId reflecting the source from which // it's relocating from. ShardRouting targetShardRouting = shard.buildTargetRelocatingShard(); addInitialRecovery(targetShardRouting); if (readOnly) { targetShardRouting.freeze(); } entries.add(targetShardRouting); assignedShardsAdd(targetShardRouting); } else if (shard.active() == false) { // shards that are initializing without being relocated if (shard.primary()) { inactivePrimaryCount++; } inactiveShardCount++; addInitialRecovery(shard); } } else { final ShardRouting sr = getRouting(shard, readOnly); assignedShardsAdd(sr); unassignedShards.add(sr); } } } } for (Map.Entry<String, List<ShardRouting>> entry : nodesToShards.entrySet()) { String nodeId = entry.getKey(); this.nodesToShards.put(nodeId, new RoutingNode(nodeId, clusterState.nodes().get(nodeId), entry.getValue())); } } private void addRecovery(ShardRouting routing) { addRecovery(routing, true, false); } private void removeRecovery(ShardRouting routing) { addRecovery(routing, false, false); } public void addInitialRecovery(ShardRouting routing) { addRecovery(routing,true, true); } private void addRecovery(final ShardRouting routing, final boolean increment, final boolean initializing) { final int howMany = increment ? 1 : -1; assert routing.initializing() : "routing must be initializing: " + routing; Recoveries.getOrAdd(recoveryiesPerNode, routing.currentNodeId()).addIncoming(howMany); final String sourceNodeId; if (routing.relocatingNodeId() != null) { // this is a relocation-target sourceNodeId = routing.relocatingNodeId(); if (routing.primary() && increment == false) { // primary is done relocating int numRecoveringReplicas = 0; for (ShardRouting assigned : assignedShards(routing)) { if (assigned.primary() == false && assigned.initializing() && assigned.relocatingNodeId() == null) { numRecoveringReplicas++; } } // we transfer the recoveries to the relocated primary recoveryiesPerNode.get(sourceNodeId).addOutgoing(-numRecoveringReplicas); recoveryiesPerNode.get(routing.currentNodeId()).addOutgoing(numRecoveringReplicas); } } else if (routing.primary() == false) { // primary without relocationID is initial recovery ShardRouting primary = findPrimary(routing); if (primary == null && initializing) { primary = routingTable.index(routing.index().getName()).shard(routing.shardId().id()).primary; } else if (primary == null) { throw new IllegalStateException("replica is initializing but primary is unassigned"); } sourceNodeId = primary.currentNodeId(); } else { sourceNodeId = null; } if (sourceNodeId != null) { Recoveries.getOrAdd(recoveryiesPerNode, sourceNodeId).addOutgoing(howMany); } } public int getIncomingRecoveries(String nodeId) { return recoveryiesPerNode.getOrDefault(nodeId, Recoveries.EMPTY).getIncoming(); } public int getOutgoingRecoveries(String nodeId) { return recoveryiesPerNode.getOrDefault(nodeId, Recoveries.EMPTY).getOutgoing(); } private ShardRouting findPrimary(ShardRouting routing) { List<ShardRouting> shardRoutings = assignedShards.get(routing.shardId()); ShardRouting primary = null; if (shardRoutings != null) { for (ShardRouting shardRouting : shardRoutings) { if (shardRouting.primary()) { if (shardRouting.active()) { return shardRouting; } else if (primary == null) { primary = shardRouting; } else if (primary.relocatingNodeId() != null) { primary = shardRouting; } } } } return primary; } private static ShardRouting getRouting(ShardRouting src, boolean readOnly) { if (readOnly) { src.freeze(); // we just freeze and reuse this instance if we are read only } else { src = new ShardRouting(src); } return src; } @Override public Iterator<RoutingNode> iterator() { return Collections.unmodifiableCollection(nodesToShards.values()).iterator(); } public RoutingTable routingTable() { return routingTable; } public RoutingTable getRoutingTable() { return routingTable(); } public MetaData metaData() { return this.metaData; } public MetaData getMetaData() { return metaData(); } public ClusterBlocks blocks() { return this.blocks; } public ClusterBlocks getBlocks() { return this.blocks; } public ImmutableOpenMap<String, ClusterState.Custom> customs() { return this.customs; } public <T extends ClusterState.Custom> T custom(String type) { return (T) customs.get(type); } public UnassignedShards unassigned() { return this.unassignedShards; } public RoutingNodesIterator nodes() { return new RoutingNodesIterator(nodesToShards.values().iterator()); } public RoutingNode node(String nodeId) { return nodesToShards.get(nodeId); } public ObjectIntHashMap<String> nodesPerAttributesCounts(String attributeName) { ObjectIntHashMap<String> nodesPerAttributesCounts = nodesPerAttributeNames.get(attributeName); if (nodesPerAttributesCounts != null) { return nodesPerAttributesCounts; } nodesPerAttributesCounts = new ObjectIntHashMap<>(); for (RoutingNode routingNode : this) { String attrValue = routingNode.node().attributes().get(attributeName); nodesPerAttributesCounts.addTo(attrValue, 1); } nodesPerAttributeNames.put(attributeName, nodesPerAttributesCounts); return nodesPerAttributesCounts; } /** * Returns <code>true</code> iff this {@link RoutingNodes} instance has any unassigned primaries even if the * primaries are marked as temporarily ignored. */ public boolean hasUnassignedPrimaries() { return unassignedShards.getNumPrimaries() + unassignedShards.getNumIgnoredPrimaries() > 0; } /** * Returns <code>true</code> iff this {@link RoutingNodes} instance has any unassigned shards even if the * shards are marked as temporarily ignored. * @see UnassignedShards#isEmpty() * @see UnassignedShards#isIgnoredEmpty() */ public boolean hasUnassignedShards() { return unassignedShards.isEmpty() == false || unassignedShards.isIgnoredEmpty() == false; } public boolean hasInactivePrimaries() { return inactivePrimaryCount > 0; } public boolean hasInactiveShards() { return inactiveShardCount > 0; } public int getRelocatingShardCount() { return relocatingShards; } /** * Returns the active primary shard for the given ShardRouting or <code>null</code> if * no primary is found or the primary is not active. */ public ShardRouting activePrimary(ShardRouting shard) { for (ShardRouting shardRouting : assignedShards(shard.shardId())) { if (shardRouting.primary() && shardRouting.active()) { return shardRouting; } } return null; } /** * Returns one active replica shard for the given ShardRouting shard ID or <code>null</code> if * no active replica is found. */ public ShardRouting activeReplica(ShardRouting shard) { for (ShardRouting shardRouting : assignedShards(shard.shardId())) { if (!shardRouting.primary() && shardRouting.active()) { return shardRouting; } } return null; } /** * Returns all shards that are not in the state UNASSIGNED with the same shard * ID as the given shard. */ public Iterable<ShardRouting> assignedShards(ShardRouting shard) { return assignedShards(shard.shardId()); } /** * Returns <code>true</code> iff all replicas are active for the given shard routing. Otherwise <code>false</code> */ public boolean allReplicasActive(ShardRouting shardRouting) { final List<ShardRouting> shards = assignedShards(shardRouting.shardId()); if (shards.isEmpty() || shards.size() < this.routingTable.index(shardRouting.index().getName()).shard(shardRouting.id()).size()) { return false; // if we are empty nothing is active if we have less than total at least one is unassigned } for (ShardRouting shard : shards) { if (!shard.active()) { return false; } } return true; } public List<ShardRouting> shards(Predicate<ShardRouting> predicate) { List<ShardRouting> shards = new ArrayList<>(); for (RoutingNode routingNode : this) { for (ShardRouting shardRouting : routingNode) { if (predicate.test(shardRouting)) { shards.add(shardRouting); } } } return shards; } public List<ShardRouting> shardsWithState(ShardRoutingState... state) { // TODO these are used on tests only - move into utils class List<ShardRouting> shards = new ArrayList<>(); for (RoutingNode routingNode : this) { shards.addAll(routingNode.shardsWithState(state)); } for (ShardRoutingState s : state) { if (s == ShardRoutingState.UNASSIGNED) { unassigned().forEach(shards::add); break; } } return shards; } public List<ShardRouting> shardsWithState(String index, ShardRoutingState... state) { // TODO these are used on tests only - move into utils class List<ShardRouting> shards = new ArrayList<>(); for (RoutingNode routingNode : this) { shards.addAll(routingNode.shardsWithState(index, state)); } for (ShardRoutingState s : state) { if (s == ShardRoutingState.UNASSIGNED) { for (ShardRouting unassignedShard : unassignedShards) { if (unassignedShard.index().equals(index)) { shards.add(unassignedShard); } } break; } } return shards; } public String prettyPrint() { StringBuilder sb = new StringBuilder("routing_nodes:\n"); for (RoutingNode routingNode : this) { sb.append(routingNode.prettyPrint()); } sb.append("---- unassigned\n"); for (ShardRouting shardEntry : unassignedShards) { sb.append("--------").append(shardEntry.shortSummary()).append('\n'); } return sb.toString(); } /** * Moves a shard from unassigned to initialize state * * @param existingAllocationId allocation id to use. If null, a fresh allocation id is generated. */ public void initialize(ShardRouting shard, String nodeId, @Nullable String existingAllocationId, long expectedSize) { ensureMutable(); assert shard.unassigned() : shard; shard.initialize(nodeId, existingAllocationId, expectedSize); node(nodeId).add(shard); inactiveShardCount++; if (shard.primary()) { inactivePrimaryCount++; } addRecovery(shard); assignedShardsAdd(shard); } /** * Relocate a shard to another node, adding the target initializing * shard as well as assigning it. And returning the target initializing * shard. */ public ShardRouting relocate(ShardRouting shard, String nodeId, long expectedShardSize) { ensureMutable(); relocatingShards++; shard.relocate(nodeId, expectedShardSize); ShardRouting target = shard.buildTargetRelocatingShard(); node(target.currentNodeId()).add(target); assignedShardsAdd(target); addRecovery(target); return target; } /** * Mark a shard as started and adjusts internal statistics. */ public void started(ShardRouting shard) { ensureMutable(); assert !shard.active() : "expected an initializing shard " + shard; if (shard.relocatingNodeId() == null) { // if this is not a target shard for relocation, we need to update statistics inactiveShardCount--; if (shard.primary()) { inactivePrimaryCount--; } } removeRecovery(shard); shard.moveToStarted(); } /** * Cancels a relocation of a shard that shard must relocating. */ public void cancelRelocation(ShardRouting shard) { ensureMutable(); relocatingShards--; shard.cancelRelocation(); } /** * swaps the status of a shard, making replicas primary and vice versa. * * @param shards the shard to have its primary status swapped. */ public void swapPrimaryFlag(ShardRouting... shards) { ensureMutable(); for (ShardRouting shard : shards) { if (shard.primary()) { shard.moveFromPrimary(); if (shard.unassigned()) { unassignedShards.primaries--; } } else { shard.moveToPrimary(); if (shard.unassigned()) { unassignedShards.primaries++; } } } } private static final List<ShardRouting> EMPTY = Collections.emptyList(); private List<ShardRouting> assignedShards(ShardId shardId) { final List<ShardRouting> replicaSet = assignedShards.get(shardId); return replicaSet == null ? EMPTY : Collections.unmodifiableList(replicaSet); } /** * Cancels the give shard from the Routing nodes internal statistics and cancels * the relocation if the shard is relocating. */ private void remove(ShardRouting shard) { ensureMutable(); if (!shard.active() && shard.relocatingNodeId() == null) { inactiveShardCount--; assert inactiveShardCount >= 0; if (shard.primary()) { inactivePrimaryCount--; } } else if (shard.relocating()) { cancelRelocation(shard); } assignedShardsRemove(shard); if (shard.initializing()) { removeRecovery(shard); } } private void assignedShardsAdd(ShardRouting shard) { if (shard.unassigned()) { // no unassigned return; } List<ShardRouting> shards = assignedShards.computeIfAbsent(shard.shardId(), k -> new ArrayList<>()); assert assertInstanceNotInList(shard, shards); shards.add(shard); } private boolean assertInstanceNotInList(ShardRouting shard, List<ShardRouting> shards) { for (ShardRouting s : shards) { assert s != shard; } return true; } private void assignedShardsRemove(ShardRouting shard) { ensureMutable(); final List<ShardRouting> replicaSet = assignedShards.get(shard.shardId()); if (replicaSet != null) { final Iterator<ShardRouting> iterator = replicaSet.iterator(); while(iterator.hasNext()) { // yes we check identity here if (shard == iterator.next()) { iterator.remove(); return; } } assert false : "Illegal state"; } } public boolean isKnown(DiscoveryNode node) { return nodesToShards.containsKey(node.getId()); } public void addNode(DiscoveryNode node) { ensureMutable(); RoutingNode routingNode = new RoutingNode(node.id(), node); nodesToShards.put(routingNode.nodeId(), routingNode); } public RoutingNodeIterator routingNodeIter(String nodeId) { final RoutingNode routingNode = nodesToShards.get(nodeId); if (routingNode == null) { return null; } return new RoutingNodeIterator(routingNode); } public RoutingNode[] toArray() { return nodesToShards.values().toArray(new RoutingNode[nodesToShards.size()]); } public void reinitShadowPrimary(ShardRouting candidate) { ensureMutable(); if (candidate.relocating()) { cancelRelocation(candidate); } candidate.reinitializeShard(); inactivePrimaryCount++; inactiveShardCount++; } /** * Returns the number of routing nodes */ public int size() { return nodesToShards.size(); } public static final class UnassignedShards implements Iterable<ShardRouting> { private final RoutingNodes nodes; private final List<ShardRouting> unassigned; private final List<ShardRouting> ignored; private int primaries = 0; private int ignoredPrimaries = 0; public UnassignedShards(RoutingNodes nodes) { this.nodes = nodes; unassigned = new ArrayList<>(); ignored = new ArrayList<>(); } public void add(ShardRouting shardRouting) { if(shardRouting.primary()) { primaries++; } unassigned.add(shardRouting); } public void sort(Comparator<ShardRouting> comparator) { CollectionUtil.timSort(unassigned, comparator); } /** * Returns the size of the non-ignored unassigned shards */ public int size() { return unassigned.size(); } /** * Returns the size of the temporarily marked as ignored unassigned shards */ public int ignoredSize() { return ignored.size(); } /** * Returns the number of non-ignored unassigned primaries */ public int getNumPrimaries() { return primaries; } /** * Returns the number of temporarily marked as ignored unassigned primaries */ public int getNumIgnoredPrimaries() { return ignoredPrimaries; } @Override public UnassignedIterator iterator() { return new UnassignedIterator(); } /** * The list of ignored unassigned shards (read only). The ignored unassigned shards * are not part of the formal unassigned list, but are kept around and used to build * back the list of unassigned shards as part of the routing table. */ public List<ShardRouting> ignored() { return Collections.unmodifiableList(ignored); } /** * Marks a shard as temporarily ignored and adds it to the ignore unassigned list. * Should be used with caution, typically, * the correct usage is to removeAndIgnore from the iterator. * @see #ignored() * @see UnassignedIterator#removeAndIgnore() * @see #isIgnoredEmpty() */ public void ignoreShard(ShardRouting shard) { if (shard.primary()) { ignoredPrimaries++; } ignored.add(shard); } public class UnassignedIterator implements Iterator<ShardRouting> { private final Iterator<ShardRouting> iterator; private ShardRouting current; public UnassignedIterator() { this.iterator = unassigned.iterator(); } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public ShardRouting next() { return current = iterator.next(); } /** * Initializes the current unassigned shard and moves it from the unassigned list. * * @param existingAllocationId allocation id to use. If null, a fresh allocation id is generated. */ public void initialize(String nodeId, @Nullable String existingAllocationId, long expectedShardSize) { innerRemove(); nodes.initialize(new ShardRouting(current), nodeId, existingAllocationId, expectedShardSize); } /** * Removes and ignores the unassigned shard (will be ignored for this run, but * will be added back to unassigned once the metadata is constructed again). * Typically this is used when an allocation decision prevents a shard from being allocated such * that subsequent consumers of this API won't try to allocate this shard again. */ public void removeAndIgnore() { innerRemove(); ignoreShard(current); } /** * Unsupported operation, just there for the interface. Use {@link #removeAndIgnore()} or * {@link #initialize(String, String, long)}. */ @Override public void remove() { throw new UnsupportedOperationException("remove is not supported in unassigned iterator, use removeAndIgnore or initialize"); } private void innerRemove() { nodes.ensureMutable(); iterator.remove(); if (current.primary()) { primaries--; } } } /** * Returns <code>true</code> iff this collection contains one or more non-ignored unassigned shards. */ public boolean isEmpty() { return unassigned.isEmpty(); } /** * Returns <code>true</code> iff any unassigned shards are marked as temporarily ignored. * @see UnassignedShards#ignoreShard(ShardRouting) * @see UnassignedIterator#removeAndIgnore() */ public boolean isIgnoredEmpty() { return ignored.isEmpty(); } public void shuffle() { Randomness.shuffle(unassigned); } /** * Drains all unassigned shards and returns it. * This method will not drain ignored shards. */ public ShardRouting[] drain() { ShardRouting[] mutableShardRoutings = unassigned.toArray(new ShardRouting[unassigned.size()]); unassigned.clear(); primaries = 0; return mutableShardRoutings; } } /** * Calculates RoutingNodes statistics by iterating over all {@link ShardRouting}s * in the cluster to ensure the book-keeping is correct. * For performance reasons, this should only be called from asserts * * @return this method always returns <code>true</code> or throws an assertion error. If assertion are not enabled * this method does nothing. */ public static boolean assertShardStats(RoutingNodes routingNodes) { boolean run = false; assert (run = true); // only run if assertions are enabled! if (!run) { return true; } int unassignedPrimaryCount = 0; int unassignedIgnoredPrimaryCount = 0; int inactivePrimaryCount = 0; int inactiveShardCount = 0; int relocating = 0; Map<Index, Integer> indicesAndShards = new HashMap<>(); for (RoutingNode node : routingNodes) { for (ShardRouting shard : node) { if (!shard.active() && shard.relocatingNodeId() == null) { if (!shard.relocating()) { inactiveShardCount++; if (shard.primary()) { inactivePrimaryCount++; } } } if (shard.relocating()) { relocating++; } Integer i = indicesAndShards.get(shard.index()); if (i == null) { i = shard.id(); } indicesAndShards.put(shard.index(), Math.max(i, shard.id())); } } // Assert that the active shard routing are identical. Set<Map.Entry<Index, Integer>> entries = indicesAndShards.entrySet(); final List<ShardRouting> shards = new ArrayList<>(); for (Map.Entry<Index, Integer> e : entries) { Index index = e.getKey(); for (int i = 0; i < e.getValue(); i++) { for (RoutingNode routingNode : routingNodes) { for (ShardRouting shardRouting : routingNode) { if (shardRouting.index().equals(index) && shardRouting.id() == i) { shards.add(shardRouting); } } } List<ShardRouting> mutableShardRoutings = routingNodes.assignedShards(new ShardId(index, i)); assert mutableShardRoutings.size() == shards.size(); for (ShardRouting r : mutableShardRoutings) { assert shards.contains(r); shards.remove(r); } assert shards.isEmpty(); } } for (ShardRouting shard : routingNodes.unassigned()) { if (shard.primary()) { unassignedPrimaryCount++; } } for (ShardRouting shard : routingNodes.unassigned().ignored()) { if (shard.primary()) { unassignedIgnoredPrimaryCount++; } } for (Map.Entry<String, Recoveries> recoveries : routingNodes.recoveryiesPerNode.entrySet()) { String node = recoveries.getKey(); final Recoveries value = recoveries.getValue(); int incoming = 0; int outgoing = 0; RoutingNode routingNode = routingNodes.nodesToShards.get(node); if (routingNode != null) { // node might have dropped out of the cluster for (ShardRouting routing : routingNode) { if (routing.initializing()) { incoming++; } else if (routing.relocating()) { outgoing++; } if (routing.primary() && (routing.initializing() && routing.relocatingNodeId() != null) == false) { // we don't count the initialization end of the primary relocation List<ShardRouting> shardRoutings = routingNodes.assignedShards.get(routing.shardId()); for (ShardRouting assigned : shardRoutings) { if (assigned.primary() == false && assigned.initializing() && assigned.relocatingNodeId() == null) { outgoing++; } } } } } assert incoming == value.incoming : incoming + " != " + value.incoming; assert outgoing == value.outgoing : outgoing + " != " + value.outgoing + " node: " + routingNode; } assert unassignedPrimaryCount == routingNodes.unassignedShards.getNumPrimaries() : "Unassigned primaries is [" + unassignedPrimaryCount + "] but RoutingNodes returned unassigned primaries [" + routingNodes.unassigned().getNumPrimaries() + "]"; assert unassignedIgnoredPrimaryCount == routingNodes.unassignedShards.getNumIgnoredPrimaries() : "Unassigned ignored primaries is [" + unassignedIgnoredPrimaryCount + "] but RoutingNodes returned unassigned ignored primaries [" + routingNodes.unassigned().getNumIgnoredPrimaries() + "]"; assert inactivePrimaryCount == routingNodes.inactivePrimaryCount : "Inactive Primary count [" + inactivePrimaryCount + "] but RoutingNodes returned inactive primaries [" + routingNodes.inactivePrimaryCount + "]"; assert inactiveShardCount == routingNodes.inactiveShardCount : "Inactive Shard count [" + inactiveShardCount + "] but RoutingNodes returned inactive shards [" + routingNodes.inactiveShardCount + "]"; assert routingNodes.getRelocatingShardCount() == relocating : "Relocating shards mismatch [" + routingNodes.getRelocatingShardCount() + "] but expected [" + relocating + "]"; return true; } public class RoutingNodesIterator implements Iterator<RoutingNode>, Iterable<ShardRouting> { private RoutingNode current; private final Iterator<RoutingNode> delegate; public RoutingNodesIterator(Iterator<RoutingNode> iterator) { delegate = iterator; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public RoutingNode next() { return current = delegate.next(); } public RoutingNodeIterator nodeShards() { return new RoutingNodeIterator(current); } @Override public void remove() { delegate.remove(); } @Override public Iterator<ShardRouting> iterator() { return nodeShards(); } } public final class RoutingNodeIterator implements Iterator<ShardRouting>, Iterable<ShardRouting> { private final RoutingNode iterable; private ShardRouting shard; private final Iterator<ShardRouting> delegate; private boolean removed = false; public RoutingNodeIterator(RoutingNode iterable) { this.delegate = iterable.mutableIterator(); this.iterable = iterable; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public ShardRouting next() { removed = false; return shard = delegate.next(); } @Override public void remove() { ensureMutable(); delegate.remove(); RoutingNodes.this.remove(shard); removed = true; } /** returns true if {@link #remove()} or {@link #moveToUnassigned(UnassignedInfo)} were called on the current shard */ public boolean isRemoved() { return removed; } @Override public Iterator<ShardRouting> iterator() { return iterable.iterator(); } public void moveToUnassigned(UnassignedInfo unassignedInfo) { ensureMutable(); if (isRemoved() == false) { remove(); } ShardRouting unassigned = new ShardRouting(shard); // protective copy of the mutable shard unassigned.moveToUnassigned(unassignedInfo); unassigned().add(unassigned); } public ShardRouting current() { return shard; } } private void ensureMutable() { if (readOnly) { throw new IllegalStateException("can't modify RoutingNodes - readonly"); } } private static final class Recoveries { private static final Recoveries EMPTY = new Recoveries(); private int incoming = 0; private int outgoing = 0; int getTotal() { return incoming + outgoing; } void addOutgoing(int howMany) { assert outgoing + howMany >= 0 : outgoing + howMany+ " must be >= 0"; outgoing += howMany; } void addIncoming(int howMany) { assert incoming + howMany >= 0 : incoming + howMany+ " must be >= 0"; incoming += howMany; } int getOutgoing() { return outgoing; } int getIncoming() { return incoming; } public static Recoveries getOrAdd(Map<String, Recoveries> map, String key) { Recoveries recoveries = map.get(key); if (recoveries == null) { recoveries = new Recoveries(); map.put(key, recoveries); } return recoveries; } } }
mapr/elasticsearch
core/src/main/java/org/elasticsearch/cluster/routing/RoutingNodes.java
Java
apache-2.0
37,917
/* * Copyright 2017 Yahoo Holdings, 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.yahoo.athenz.zms; import java.util.List; import com.yahoo.athenz.zms.store.ObjectStoreConnection; import com.yahoo.athenz.zms.utils.ZMSUtils; import com.yahoo.rdl.Timestamp; class QuotaChecker { private final Quota defaultQuota; private boolean quotaCheckEnabled; public QuotaChecker() { // first check if the quota check is enabled or not quotaCheckEnabled = Boolean.parseBoolean(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_CHECK, "true")); // retrieve default quota values int roleQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ROLE, "1000")); int roleMemberQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ROLE_MEMBER, "100")); int policyQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_POLICY, "1000")); int assertionQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ASSERTION, "100")); int serviceQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_SERVICE, "250")); int serviceHostQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_SERVICE_HOST, "10")); int publicKeyQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_PUBLIC_KEY, "100")); int entityQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_ENTITY, "100")); int subDomainQuota = Integer.parseInt(System.getProperty(ZMSConsts.ZMS_PROP_QUOTA_SUBDOMAIN, "100")); defaultQuota = new Quota().setName("server-default") .setAssertion(assertionQuota).setEntity(entityQuota) .setPolicy(policyQuota).setPublicKey(publicKeyQuota) .setRole(roleQuota).setRoleMember(roleMemberQuota) .setService(serviceQuota).setServiceHost(serviceHostQuota) .setSubdomain(subDomainQuota).setModified(Timestamp.fromCurrentTime()); } public Quota getDomainQuota(ObjectStoreConnection con, String domainName) { Quota quota = con.getQuota(domainName); return (quota == null) ? defaultQuota : quota; } void setQuotaCheckEnabled(boolean quotaCheckEnabled) { this.quotaCheckEnabled = quotaCheckEnabled; } int getListSize(List<?> list) { return (list == null) ? 0 : list.size(); } void checkSubdomainQuota(ObjectStoreConnection con, String domainName, String caller) { // if quota check is disabled we have nothing to do if (!quotaCheckEnabled) { return; } // for sub-domains we need to run the quota check against // the top level domain so let's get that first. If we are // creating a top level domain then there is no need for // quota check int idx = domainName.indexOf('.'); if (idx == -1) { return; } final String topLevelDomain = domainName.substring(0, idx); // now get the quota for the top level domain final Quota quota = getDomainQuota(con, topLevelDomain); // get the list of sub-domains for our given top level domain final String domainPrefix = topLevelDomain + "."; int objectCount = con.listDomains(domainPrefix, 0).size() + 1; if (quota.getSubdomain() < objectCount) { throw ZMSUtils.quotaLimitError("subdomain quota exceeded - limit: " + quota.getSubdomain() + " actual: " + objectCount, caller); } } void checkRoleQuota(ObjectStoreConnection con, String domainName, Role role, String caller) { // if quota check is disabled we have nothing to do if (!quotaCheckEnabled) { return; } // if our role is null then there is no quota check if (role == null) { return; } // first retrieve the domain quota final Quota quota = getDomainQuota(con, domainName); // first we're going to verify the elements that do not // require any further data from the object store int objectCount = getListSize(role.getRoleMembers()); if (quota.getRoleMember() < objectCount) { throw ZMSUtils.quotaLimitError("role member quota exceeded - limit: " + quota.getRoleMember() + " actual: " + objectCount, caller); } // now we're going to check if we'll be allowed // to create this role in the domain objectCount = con.countRoles(domainName) + 1; if (quota.getRole() < objectCount) { throw ZMSUtils.quotaLimitError("role quota exceeded - limit: " + quota.getRole() + " actual: " + objectCount, caller); } } void checkRoleMembershipQuota(ObjectStoreConnection con, String domainName, String roleName, String caller) { // if quota check is disabled we have nothing to do if (!quotaCheckEnabled) { return; } // first retrieve the domain quota final Quota quota = getDomainQuota(con, domainName); // now check to make sure we can add 1 more member // to this role without exceeding the quota int objectCount = con.countRoleMembers(domainName, roleName) + 1; if (quota.getRoleMember() < objectCount) { throw ZMSUtils.quotaLimitError("role member quota exceeded - limit: " + quota.getRoleMember() + " actual: " + objectCount, caller); } } void checkPolicyQuota(ObjectStoreConnection con, String domainName, Policy policy, String caller) { // if quota check is disabled we have nothing to do if (!quotaCheckEnabled) { return; } // if our policy is null then there is no quota check if (policy == null) { return; } // first retrieve the domain quota final Quota quota = getDomainQuota(con, domainName); // first we're going to verify the elements that do not // require any further data from the object store int objectCount = getListSize(policy.getAssertions()); if (quota.getAssertion() < objectCount) { throw ZMSUtils.quotaLimitError("policy assertion quota exceeded - limit: " + quota.getAssertion() + " actual: " + objectCount, caller); } // now we're going to check if we'll be allowed // to create this policy in the domain objectCount = con.countPolicies(domainName) + 1; if (quota.getPolicy() < objectCount) { throw ZMSUtils.quotaLimitError("policy quota exceeded - limit: " + quota.getPolicy() + " actual: " + objectCount, caller); } } void checkPolicyAssertionQuota(ObjectStoreConnection con, String domainName, String policyName, String caller) { // if quota check is disabled we have nothing to do if (!quotaCheckEnabled) { return; } // first retrieve the domain quota final Quota quota = getDomainQuota(con, domainName); // now check to make sure we can add 1 more assertion // to this policy without exceeding the quota int objectCount = con.countAssertions(domainName, policyName) + 1; if (quota.getAssertion() < objectCount) { throw ZMSUtils.quotaLimitError("policy assertion quota exceeded - limit: " + quota.getAssertion() + " actual: " + objectCount, caller); } } void checkServiceIdentityQuota(ObjectStoreConnection con, String domainName, ServiceIdentity service, String caller) { // if quota check is disabled we have nothing to do if (!quotaCheckEnabled) { return; } // if our service is null then there is no quota check if (service == null) { return; } // first retrieve the domain quota final Quota quota = getDomainQuota(con, domainName); // first we're going to verify the elements that do not // require any further data from the object store int objectCount = getListSize(service.getHosts()); if (quota.getServiceHost() < objectCount) { throw ZMSUtils.quotaLimitError("service host quota exceeded - limit: " + quota.getServiceHost() + " actual: " + objectCount, caller); } objectCount = getListSize(service.getPublicKeys()); if (quota.getPublicKey() < objectCount) { throw ZMSUtils.quotaLimitError("service public key quota exceeded - limit: " + quota.getPublicKey() + " actual: " + objectCount, caller); } // now we're going to check if we'll be allowed // to create this service in the domain objectCount = con.countServiceIdentities(domainName) + 1; if (quota.getService() < objectCount) { throw ZMSUtils.quotaLimitError("service quota exceeded - limit: " + quota.getService() + " actual: " + objectCount, caller); } } void checkServiceIdentityPublicKeyQuota(ObjectStoreConnection con, String domainName, String serviceName, String caller) { // if quota check is disabled we have nothing to do if (!quotaCheckEnabled) { return; } // first retrieve the domain quota final Quota quota = getDomainQuota(con, domainName); // now check to make sure we can add 1 more public key // to this policy without exceeding the quota int objectCount = con.countPublicKeys(domainName, serviceName) + 1; if (quota.getPublicKey() < objectCount) { throw ZMSUtils.quotaLimitError("service public key quota exceeded - limit: " + quota.getPublicKey() + " actual: " + objectCount, caller); } } void checkEntityQuota(ObjectStoreConnection con, String domainName, Entity entity, String caller) { // if quota check is disabled we have nothing to do if (!quotaCheckEnabled) { return; } // if our entity is null then there is no quota check if (entity == null) { return; } // first retrieve the domain quota final Quota quota = getDomainQuota(con, domainName); // we're going to check if we'll be allowed // to create this entity in the domain int objectCount = con.countEntities(domainName) + 1; if (quota.getEntity() < objectCount) { throw ZMSUtils.quotaLimitError("entity quota exceeded - limit: " + quota.getEntity() + " actual: " + objectCount, caller); } } }
gurleen-gks/athenz
servers/zms/src/main/java/com/yahoo/athenz/zms/QuotaChecker.java
Java
apache-2.0
12,013
#!/usr/bin/env python # Copyright JS Foundation and other contributors, http://js.foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import argparse import collections import hashlib import os import subprocess import sys import settings OUTPUT_DIR = os.path.join(settings.PROJECT_DIR, 'build', 'tests') Options = collections.namedtuple('Options', ['name', 'build_args', 'test_args']) Options.__new__.__defaults__ = ([], []) OPTIONS_PROFILE_MIN = ['--profile=minimal'] OPTIONS_PROFILE_ES51 = [] # NOTE: same as ['--profile=es5.1'] OPTIONS_PROFILE_ES2015 = ['--profile=es2015-subset'] OPTIONS_DEBUG = ['--debug'] OPTIONS_SNAPSHOT = ['--snapshot-save=on', '--snapshot-exec=on', '--jerry-cmdline-snapshot=on'] OPTIONS_UNITTESTS = ['--unittests=on', '--jerry-cmdline=off', '--error-messages=on', '--snapshot-save=on', '--snapshot-exec=on', '--vm-exec-stop=on', '--line-info=on', '--mem-stats=on'] OPTIONS_DOCTESTS = ['--doctests=on', '--jerry-cmdline=off', '--error-messages=on', '--snapshot-save=on', '--snapshot-exec=on', '--vm-exec-stop=on'] # Test options for unittests JERRY_UNITTESTS_OPTIONS = [ Options('unittests-es2015_subset', OPTIONS_UNITTESTS + OPTIONS_PROFILE_ES2015), Options('unittests-es2015_subset-debug', OPTIONS_UNITTESTS + OPTIONS_PROFILE_ES2015 + OPTIONS_DEBUG), Options('doctests-es2015_subset', OPTIONS_DOCTESTS + OPTIONS_PROFILE_ES2015), Options('doctests-es2015_subset-debug', OPTIONS_DOCTESTS + OPTIONS_PROFILE_ES2015 + OPTIONS_DEBUG), Options('unittests-es5.1', OPTIONS_UNITTESTS + OPTIONS_PROFILE_ES51), Options('unittests-es5.1-debug', OPTIONS_UNITTESTS + OPTIONS_PROFILE_ES51 + OPTIONS_DEBUG), Options('doctests-es5.1', OPTIONS_DOCTESTS + OPTIONS_PROFILE_ES51), Options('doctests-es5.1-debug', OPTIONS_DOCTESTS + OPTIONS_PROFILE_ES51 + OPTIONS_DEBUG) ] # Test options for jerry-tests JERRY_TESTS_OPTIONS = [ Options('jerry_tests-es5.1', OPTIONS_PROFILE_ES51), Options('jerry_tests-es5.1-snapshot', OPTIONS_PROFILE_ES51 + OPTIONS_SNAPSHOT, ['--snapshot']), Options('jerry_tests-es5.1-debug', OPTIONS_PROFILE_ES51 + OPTIONS_DEBUG), Options('jerry_tests-es5.1-debug-snapshot', OPTIONS_PROFILE_ES51 + OPTIONS_SNAPSHOT + OPTIONS_DEBUG, ['--snapshot']), Options('jerry_tests-es5.1-debug-cpointer_32bit', OPTIONS_PROFILE_ES51 + OPTIONS_DEBUG + ['--cpointer-32bit=on', '--mem-heap=1024']), Options('jerry_tests-es5.1-debug-external_context', OPTIONS_PROFILE_ES51 + OPTIONS_DEBUG + ['--jerry-libc=off', '--external-context=on']), Options('jerry_tests-es2015_subset-debug', OPTIONS_PROFILE_ES2015 + OPTIONS_DEBUG), ] # Test options for jerry-test-suite JERRY_TEST_SUITE_OPTIONS = JERRY_TESTS_OPTIONS[:] JERRY_TEST_SUITE_OPTIONS.extend([ Options('jerry_test_suite-minimal', OPTIONS_PROFILE_MIN), Options('jerry_test_suite-minimal-snapshot', OPTIONS_PROFILE_MIN + OPTIONS_SNAPSHOT, ['--snapshot']), Options('jerry_test_suite-minimal-debug', OPTIONS_PROFILE_MIN + OPTIONS_DEBUG), Options('jerry_test_suite-minimal-debug-snapshot', OPTIONS_PROFILE_MIN + OPTIONS_SNAPSHOT + OPTIONS_DEBUG, ['--snapshot']), Options('jerry_test_suite-es2015_subset', OPTIONS_PROFILE_ES2015), Options('jerry_test_suite-es2015_subset-snapshot', OPTIONS_PROFILE_ES2015 + OPTIONS_SNAPSHOT, ['--snapshot']), Options('jerry_test_suite-es2015_subset-debug-snapshot', OPTIONS_PROFILE_ES2015 + OPTIONS_SNAPSHOT + OPTIONS_DEBUG, ['--snapshot']), ]) # Test options for test262 TEST262_TEST_SUITE_OPTIONS = [ Options('test262_tests') ] # Test options for jerry-debugger DEBUGGER_TEST_OPTIONS = [ Options('jerry_debugger_tests', ['--debug', '--jerry-debugger=on', '--jerry-libc=off']) ] # Test options for buildoption-test JERRY_BUILDOPTIONS = [ Options('buildoption_test-lto', ['--lto=on']), Options('buildoption_test-error_messages', ['--error-messages=on']), Options('buildoption_test-all_in_one', ['--all-in-one=on']), Options('buildoption_test-valgrind', ['--valgrind=on']), Options('buildoption_test-mem_stats', ['--mem-stats=on']), Options('buildoption_test-show_opcodes', ['--show-opcodes=on']), Options('buildoption_test-show_regexp_opcodes', ['--show-regexp-opcodes=on']), Options('buildoption_test-compiler_default_libc', ['--jerry-libc=off']), Options('buildoption_test-cpointer_32bit', ['--jerry-libc=off', '--compile-flag=-m32', '--cpointer-32bit=on', '--system-allocator=on']), Options('buildoption_test-external_context', ['--jerry-libc=off', '--external-context=on']), Options('buildoption_test-shared_libs', ['--jerry-libc=off', '--shared-libs=on']), Options('buildoption_test-cmdline_test', ['--jerry-cmdline-test=on']), Options('buildoption_test-cmdline_snapshot', ['--jerry-cmdline-snapshot=on']), ] def get_arguments(): parser = argparse.ArgumentParser() parser.add_argument('--toolchain', metavar='FILE', help='Add toolchain file') parser.add_argument('-q', '--quiet', action='store_true', help='Only print out failing tests') parser.add_argument('--buildoptions', metavar='LIST', help='Add a comma separated list of extra build options to each test') parser.add_argument('--skip-list', metavar='LIST', help='Add a comma separated list of patterns of the excluded JS-tests') parser.add_argument('--outdir', metavar='DIR', default=OUTPUT_DIR, help='Specify output directory (default: %(default)s)') parser.add_argument('--check-signed-off', metavar='TYPE', nargs='?', choices=['strict', 'tolerant', 'travis'], const='strict', help='Run signed-off check (%(choices)s; default type if not given: %(const)s)') parser.add_argument('--check-cppcheck', action='store_true', help='Run cppcheck') parser.add_argument('--check-doxygen', action='store_true', help='Run doxygen') parser.add_argument('--check-pylint', action='store_true', help='Run pylint') parser.add_argument('--check-vera', action='store_true', help='Run vera check') parser.add_argument('--check-license', action='store_true', help='Run license check') parser.add_argument('--check-magic-strings', action='store_true', help='Run "magic string source code generator should be executed" check') parser.add_argument('--jerry-debugger', action='store_true', help='Run jerry-debugger tests') parser.add_argument('--jerry-tests', action='store_true', help='Run jerry-tests') parser.add_argument('--jerry-test-suite', action='store_true', help='Run jerry-test-suite') parser.add_argument('--test262', action='store_true', help='Run test262') parser.add_argument('--unittests', action='store_true', help='Run unittests (including doctests)') parser.add_argument('--buildoption-test', action='store_true', help='Run buildoption-test') parser.add_argument('--all', '--precommit', action='store_true', help='Run all tests') if len(sys.argv) == 1: parser.print_help() sys.exit(1) script_args = parser.parse_args() return script_args BINARY_CACHE = {} def create_binary(job, options): build_args = job.build_args[:] if options.buildoptions: for option in options.buildoptions.split(','): if option not in build_args: build_args.append(option) build_cmd = [settings.BUILD_SCRIPT] + build_args build_dir_path = os.path.join(options.outdir, job.name) build_cmd.append('--builddir=%s' % build_dir_path) install_dir_path = os.path.join(build_dir_path, 'local') build_cmd.append('--install=%s' % install_dir_path) if options.toolchain: build_cmd.append('--toolchain=%s' % options.toolchain) sys.stderr.write('Build command: %s\n' % ' '.join(build_cmd)) binary_key = tuple(sorted(build_args)) if binary_key in BINARY_CACHE: ret, build_dir_path = BINARY_CACHE[binary_key] sys.stderr.write('(skipping: already built at %s with returncode %d)\n' % (build_dir_path, ret)) return ret, build_dir_path try: subprocess.check_output(build_cmd) ret = 0 except subprocess.CalledProcessError as err: ret = err.returncode BINARY_CACHE[binary_key] = (ret, build_dir_path) return ret, build_dir_path def get_binary_path(build_dir_path): return os.path.join(build_dir_path, 'local', 'bin', 'jerry') def hash_binary(bin_path): blocksize = 65536 hasher = hashlib.sha1() with open(bin_path, 'rb') as bin_file: buf = bin_file.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = bin_file.read(blocksize) return hasher.hexdigest() def iterate_test_runner_jobs(jobs, options): tested_paths = set() tested_hashes = {} for job in jobs: ret_build, build_dir_path = create_binary(job, options) if ret_build: yield job, ret_build, build_dir_path, None if build_dir_path in tested_paths: sys.stderr.write('(skipping: already tested with %s)\n' % build_dir_path) continue else: tested_paths.add(build_dir_path) bin_path = get_binary_path(build_dir_path) bin_hash = hash_binary(bin_path) if bin_hash in tested_hashes: sys.stderr.write('(skipping: already tested with equivalent %s)\n' % tested_hashes[bin_hash]) continue else: tested_hashes[bin_hash] = build_dir_path test_cmd = [settings.TEST_RUNNER_SCRIPT, bin_path] yield job, ret_build, test_cmd def run_check(runnable): sys.stderr.write('Test command: %s\n' % ' '.join(runnable)) try: ret = subprocess.check_call(runnable) except subprocess.CalledProcessError as err: return err.returncode return ret def run_jerry_debugger_tests(options): ret_build = ret_test = 0 for job in DEBUGGER_TEST_OPTIONS: ret_build, build_dir_path = create_binary(job, options) if ret_build: break for test_file in os.listdir(settings.DEBUGGER_TESTS_DIR): if test_file.endswith(".cmd"): test_case, _ = os.path.splitext(test_file) test_case_path = os.path.join(settings.DEBUGGER_TESTS_DIR, test_case) test_cmd = [ settings.DEBUGGER_TEST_RUNNER_SCRIPT, get_binary_path(build_dir_path), settings.DEBUGGER_CLIENT_SCRIPT, os.path.relpath(test_case_path, settings.PROJECT_DIR) ] if job.test_args: test_cmd.extend(job.test_args) ret_test |= run_check(test_cmd) return ret_build | ret_test def run_jerry_tests(options): ret_build = ret_test = 0 for job, ret_build, test_cmd in iterate_test_runner_jobs(JERRY_TESTS_OPTIONS, options): if ret_build: break test_cmd.append(settings.JERRY_TESTS_DIR) if options.quiet: test_cmd.append("-q") skip_list = [] if '--profile=es2015-subset' in job.build_args: skip_list.append(r"es5.1\/") else: skip_list.append(r"es2015\/") if options.skip_list: skip_list.append(options.skip_list) if skip_list: test_cmd.append("--skip-list=" + ",".join(skip_list)) if job.test_args: test_cmd.extend(job.test_args) ret_test |= run_check(test_cmd) return ret_build | ret_test def run_jerry_test_suite(options): ret_build = ret_test = 0 for job, ret_build, test_cmd in iterate_test_runner_jobs(JERRY_TEST_SUITE_OPTIONS, options): if ret_build: break if '--profile=minimal' in job.build_args: test_cmd.append(settings.JERRY_TEST_SUITE_MINIMAL_LIST) elif '--profile=es2015-subset' in job.build_args: test_cmd.append(settings.JERRY_TEST_SUITE_DIR) else: test_cmd.append(settings.JERRY_TEST_SUITE_ES51_LIST) if options.quiet: test_cmd.append("-q") if options.skip_list: test_cmd.append("--skip-list=" + options.skip_list) if job.test_args: test_cmd.extend(job.test_args) ret_test |= run_check(test_cmd) return ret_build | ret_test def run_test262_test_suite(options): ret_build = ret_test = 0 for job in TEST262_TEST_SUITE_OPTIONS: ret_build, build_dir_path = create_binary(job, options) if ret_build: break test_cmd = [ settings.TEST262_RUNNER_SCRIPT, get_binary_path(build_dir_path), settings.TEST262_TEST_SUITE_DIR ] if job.test_args: test_cmd.extend(job.test_args) ret_test |= run_check(test_cmd) return ret_build | ret_test def run_unittests(options): ret_build = ret_test = 0 for job in JERRY_UNITTESTS_OPTIONS: ret_build, build_dir_path = create_binary(job, options) if ret_build: break ret_test |= run_check([ settings.UNITTEST_RUNNER_SCRIPT, os.path.join(build_dir_path, 'tests'), "-q" if options.quiet else "", ]) return ret_build | ret_test def run_buildoption_test(options): for job in JERRY_BUILDOPTIONS: ret, _ = create_binary(job, options) if ret: break return ret Check = collections.namedtuple('Check', ['enabled', 'runner', 'arg']) def main(options): checks = [ Check(options.check_signed_off, run_check, [settings.SIGNED_OFF_SCRIPT] + {'tolerant': ['--tolerant'], 'travis': ['--travis']}.get(options.check_signed_off, [])), Check(options.check_cppcheck, run_check, [settings.CPPCHECK_SCRIPT]), Check(options.check_doxygen, run_check, [settings.DOXYGEN_SCRIPT]), Check(options.check_pylint, run_check, [settings.PYLINT_SCRIPT]), Check(options.check_vera, run_check, [settings.VERA_SCRIPT]), Check(options.check_license, run_check, [settings.LICENSE_SCRIPT]), Check(options.check_magic_strings, run_check, [settings.MAGIC_STRINGS_SCRIPT]), Check(options.jerry_debugger, run_jerry_debugger_tests, options), Check(options.jerry_tests, run_jerry_tests, options), Check(options.jerry_test_suite, run_jerry_test_suite, options), Check(options.test262, run_test262_test_suite, options), Check(options.unittests, run_unittests, options), Check(options.buildoption_test, run_buildoption_test, options), ] for check in checks: if check.enabled or options.all: ret = check.runner(check.arg) if ret: sys.exit(ret) if __name__ == "__main__": main(get_arguments())
yichoi/jerryscript
tools/run-tests.py
Python
apache-2.0
16,290
/* 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 java.nio; import libcore.io.SizeOf; /** * This class wraps a byte buffer to be a char buffer. * <p> * Implementation notice: * <ul> * <li>After a byte buffer instance is wrapped, it becomes privately owned by * the adapter. It must NOT be accessed outside the adapter any more.</li> * <li>The byte buffer's position and limit are NOT linked with the adapter. * The adapter extends Buffer, thus has its own position and limit.</li> * </ul> * </p> * */ final class ByteBufferAsCharBuffer extends CharBuffer { private final ByteBuffer byteBuffer; static CharBuffer asCharBuffer(ByteBuffer byteBuffer) { ByteBuffer slice = byteBuffer.slice(); slice.order(byteBuffer.order()); return new ByteBufferAsCharBuffer(slice); } private ByteBufferAsCharBuffer(ByteBuffer byteBuffer) { super(byteBuffer.capacity() / SizeOf.CHAR); this.byteBuffer = byteBuffer; this.byteBuffer.clear(); this.effectiveDirectAddress = byteBuffer.effectiveDirectAddress; } @Override public CharBuffer asReadOnlyBuffer() { ByteBufferAsCharBuffer buf = new ByteBufferAsCharBuffer(byteBuffer.asReadOnlyBuffer()); buf.limit = limit; buf.position = position; buf.mark = mark; buf.byteBuffer.order = byteBuffer.order; return buf; } @Override public CharBuffer compact() { if (byteBuffer.isReadOnly()) { throw new ReadOnlyBufferException(); } byteBuffer.limit(limit * SizeOf.CHAR); byteBuffer.position(position * SizeOf.CHAR); byteBuffer.compact(); byteBuffer.clear(); position = limit - position; limit = capacity; mark = UNSET_MARK; return this; } @Override public CharBuffer duplicate() { ByteBuffer bb = byteBuffer.duplicate().order(byteBuffer.order()); ByteBufferAsCharBuffer buf = new ByteBufferAsCharBuffer(bb); buf.limit = limit; buf.position = position; buf.mark = mark; return buf; } @Override public char get() { if (position == limit) { throw new BufferUnderflowException(); } return byteBuffer.getChar(position++ * SizeOf.CHAR); } @Override public char get(int index) { checkIndex(index); return byteBuffer.getChar(index * SizeOf.CHAR); } @Override public CharBuffer get(char[] dst, int dstOffset, int charCount) { byteBuffer.limit(limit * SizeOf.CHAR); byteBuffer.position(position * SizeOf.CHAR); if (byteBuffer instanceof DirectByteBuffer) { ((DirectByteBuffer) byteBuffer).get(dst, dstOffset, charCount); } else { ((ByteArrayBuffer) byteBuffer).get(dst, dstOffset, charCount); } this.position += charCount; return this; } @Override public boolean isDirect() { return byteBuffer.isDirect(); } @Override public boolean isReadOnly() { return byteBuffer.isReadOnly(); } @Override public ByteOrder order() { return byteBuffer.order(); } @Override char[] protectedArray() { throw new UnsupportedOperationException(); } @Override int protectedArrayOffset() { throw new UnsupportedOperationException(); } @Override boolean protectedHasArray() { return false; } @Override public CharBuffer put(char c) { if (position == limit) { throw new BufferOverflowException(); } byteBuffer.putChar(position++ * SizeOf.CHAR, c); return this; } @Override public CharBuffer put(int index, char c) { checkIndex(index); byteBuffer.putChar(index * SizeOf.CHAR, c); return this; } @Override public CharBuffer put(char[] src, int srcOffset, int charCount) { byteBuffer.limit(limit * SizeOf.CHAR); byteBuffer.position(position * SizeOf.CHAR); if (byteBuffer instanceof DirectByteBuffer) { ((DirectByteBuffer) byteBuffer).put(src, srcOffset, charCount); } else { ((ByteArrayBuffer) byteBuffer).put(src, srcOffset, charCount); } this.position += charCount; return this; } @Override public CharBuffer slice() { byteBuffer.limit(limit * SizeOf.CHAR); byteBuffer.position(position * SizeOf.CHAR); ByteBuffer bb = byteBuffer.slice().order(byteBuffer.order()); CharBuffer result = new ByteBufferAsCharBuffer(bb); byteBuffer.clear(); return result; } @Override public CharBuffer subSequence(int start, int end) { checkStartEndRemaining(start, end); CharBuffer result = duplicate(); result.limit(position + end); result.position(position + start); return result; } }
indashnet/InDashNet.Open.UN2000
android/libcore/luni/src/main/java/java/nio/ByteBufferAsCharBuffer.java
Java
apache-2.0
5,714
import math def isPrime(num): if num < 2: return False # 0, 1不是质数 # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(num)) + 1 for i in range(2, boundary): if num % i == 0: return False return True def primeSieve(size): sieve = [True] * size # 某格一为乘积, 就置为False sieve[0] = False sieve[1] = True # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(size)) + 1 for i in range(2, boundary): pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数 while pointer < size: sieve[pointer] = False pointer += i ret = [] # contains all the prime number within "size" for i in range(size): if sieve[i] == True: ret.append(str(i)) return ret if __name__ == '__main__': primes = primeSieve(100) primesString = ", ".join(primes) print("prime : ", primesString) ''' prime : 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 '''
songzhw/Hello-kotlin
Python101/src/math/PrimeSieve.py
Python
apache-2.0
1,333