repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
airgiser/ucb
examples/python/simple/class_init.py
<filename>examples/python/simple/class_init.py #!/usr/bin/python # Filename: class_init.py class Person: def __init__(self, name): self.name = name def sayhello(self): print "hello,", self.name p = Person('python') p.sayhello()
ssf-admin/scb
bot/src/registry.js
<gh_stars>1-10 var Bot = require('./bot/Bot'); var BotModel = require('./models/BotModel'); class Registry { constructor () { this.bots = {}; this.botModel = new BotModel(); } runBot (bot) { if (!bot) return; var botId = bot.botId; if (this.bots[botId]) this.bots[botId].stop(); if (this.bots[botId]) delete this.bots[botId]; if (bot.active) { this.bots[botId] = new Bot(bot); this.bots[botId].start(); } } run (botId) { return this.botModel.get(botId) .then(function(bot) { this.runBot(bot); }.bind(this)) } bootstrap () { return this.botModel.getAllBots() .then(function(bots) { console.log('list', JSON.stringify(bots, null, ' ')); bots.each(function(bot) { this.runBot(bot); }, this); }.bind(this)) } } var registry = new Registry(); module.exports = registry;
Ruslanwww/auction_marketplace_api
app/controllers/lots_controller.rb
class LotsController < ApplicationController expose :lot def index lots = Lot.in_process.order(created_at: :desc).page(params[:page]) render json: lots, status: :ok end def my_lots lots = filtered_lot.order(created_at: :desc).page(params[:page]) check_my_lot(lots) render json: lots, check_my_lot: true, status: :ok end def current_user_info render json: { code: Digest::SHA1.hexdigest([current_user.id, lot.id].join)[0...10] } end def show check_win(lot) if lot.closed? && lot.bids.present? render json: lot, check_my_win: lot.closed?, status: :ok end def create lot = current_user.lots.new(lot_params) lot.save! render json: lot, status: :created end def update authorize lot lot.update!(lot_params) render json: lot end def destroy authorize lot lot.destroy end private def filtered_lot if params[:filter] == "created" current_user.lots elsif params[:filter] == "participation" participation_lot else participation_lot.or(Lot.where(user_id: current_user.lots.pluck(:user_id))) end end def participation_lot Lot.where(id: current_user.bids.pluck(:lot_id)) end def check_my_lot(lots) lots.map do |lot| lot.my_lot = (lot.user_id == current_user.id) end end def check_win(lot) lot.my_win = lot.winner_bid.user == current_user end def lot_params params.require(:lot).permit(:title, :description, :image, :current_price, :estimated_price, :lot_start_time, :lot_end_time) end end
dangweijian/easy-generator
src/main/java/com/dwj/generator/common/annotation/Condition.java
package com.dwj.generator.common.annotation; import com.dwj.generator.common.enums.ConditionType; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author: dangweijian * @description: 条件注解 * @create: 2020-01-15 17:24 **/ @Documented @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Condition { ConditionType type() default ConditionType.EQ; }
Kaiser-Lee/Anjoy_api
interface/interface-dms/src/main/java/com/coracle/dms/dao/mybatis/DmsOrderReturnCartMapper.java
/** * create by tanyb * @date 2017-08 */ package com.coracle.dms.dao.mybatis; import java.util.List; import com.coracle.dms.po.DmsOrderReturnCart; import com.coracle.dms.vo.DmsOrderReturnCartVo; import com.coracle.yk.xdatabase.base.mybatis.intf.IMybatisDao; public interface DmsOrderReturnCartMapper extends IMybatisDao<DmsOrderReturnCart> { List<DmsOrderReturnCartVo> getPageList(DmsOrderReturnCartVo search); void deleteByIdSoft(Object id); void batchRemove(List<Long> ids); Integer getOrderReturnCartCount(DmsOrderReturnCart paramVo); Integer selectReturnCount(DmsOrderReturnCart paramVo); }
sgholamian/log-aware-clone-detection
NLPCCd/Hive/1513_2.java
<gh_stars>0 //,temp,sample_871.java,2,9,temp,sample_870.java,2,9 //,3 public class xxx { public static Map<String, Map<String, Table>> getTempTables() { SessionState ss = SessionState.get(); if (ss == null) { log.info("no current sessionstate skipping temp tables"); } } };
arjunKumbakkara/WFM_BoilerPlate
src/main/java/com/sixdee/wfm/service/StateService.java
/** * */ package com.sixdee.wfm.service; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import com.sixdee.wfm.model.State; /** * @author <NAME> * * Date : 11-Mar-2019 */ @Service public interface StateService { public Page<State> getAllState(String page, String pageSize, String sortDirection, String sortKey, String search); public List<State> getAllState(String search); public List<State> findStateByCountryId(Integer Id); }
zhengyn0001/algorithmByXiaohui
node_modules/eslint-config-alloy/test/base/no-new-wrappers/bad.js
const s = new String('foo'); const n = new Number(1); const b = new Boolean(true);
SenseException/instantsearch.js
docgen/src/examples/getting-started-boilerplate/app.js
// Add here your javascript code
isaiah/jy3k
org.python/src/org/python/core/PyJava.java
package org.python.core; import jdk.dynalink.beans.StaticClass; import org.python.annotations.ExposedClassMethod; import org.python.annotations.ExposedType; @ExposedType(name = "Java") public class PyJava extends PyObject { public static final PyType TYPE = PyType.fromClass(PyJava.class); public PyJava() { super(TYPE); } @ExposedClassMethod public static Object type(final PyType _self, final String objTypeName) throws ClassNotFoundException { return StaticClass.forClass(Class.forName(objTypeName)); } }
FeatureToggleStudy/pam-annonsemottak
src/main/java/no/nav/pam/annonsemottak/rest/AnnonsehodeConverter.java
<filename>src/main/java/no/nav/pam/annonsemottak/rest/AnnonsehodeConverter.java<gh_stars>1-10 package no.nav.pam.annonsemottak.rest; import no.nav.pam.annonsemottak.stilling.Arbeidsgiver; import no.nav.pam.annonsemottak.stilling.Merknader; import no.nav.pam.annonsemottak.stilling.Saksbehandler; import no.nav.pam.annonsemottak.stilling.Stilling; import no.nav.pam.annonsemottak.rest.payloads.AnnonsehodePayload; import java.util.function.Function; class AnnonsehodeConverter implements Function<Stilling, AnnonsehodePayload> { @Override public AnnonsehodePayload apply(Stilling source) { return new AnnonsehodePayload.Builder() .setUuid(source.getUuid()) .setArbeidsgiver(source.getArbeidsgiver().map(Arbeidsgiver::asString).orElse(null)) .setArbeidssted(source.getPlace()) .setMerknader(source.getMerknader().map(Merknader::asString).orElse(null)) .setMottattDato(source.getCreated() == null ? null : source.getCreated().toString()) // TODO: Should never need to check for null, see PAMUTV-180. .setSaksbehandler(source.getSaksbehandler().map(Saksbehandler::asString).orElse(null)) .setStatus(source.getStatus().getKodeAsString()) .setTittel(source.getTitle()) .setKilde(source.getKilde()) .setAnnonsestatus((source.getAnnonseStatus() != null) ? source.getAnnonseStatus().getCodeAsString() : null) .setSoknadsfrist(source.getDueDate()) .setKommentarer((source.getKommentarer().isPresent()) ? source.getKommentarer().get().asString() : null) .setModifisertDato((source.getUpdated() != null) ? source.getUpdated().toString() : null) // TODO: Should never need to check for null, see PAMUTV-180. .build(); } }
ppartarr/azure-sdk-for-java
sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemSentEventData.java
<filename>sdk/eventgrid/microsoft-azure-eventgrid/src/test/java/com/microsoft/azure/eventgrid/customization/models/ContosoItemSentEventData.java<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.eventgrid.customization.models; import com.fasterxml.jackson.annotation.JsonProperty; public class ContosoItemSentEventData { @JsonProperty(value = "shippingInfo", access = JsonProperty.Access.WRITE_ONLY) private ShippingInfo shippingInfo; /** * @return the shipping info. */ public ShippingInfo shippingInfo() { return this.shippingInfo; } }
zealoussnow/chromium
tools/perf/benchmarks/desktop_ui.py
<filename>tools/perf/benchmarks/desktop_ui.py # Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from core import perf_benchmark from core import platforms from telemetry import benchmark from telemetry import story from telemetry.timeline import chrome_trace_category_filter from telemetry.web_perf import timeline_based_measurement import page_sets @benchmark.Info( emails=[ '<EMAIL>', '<EMAIL>', '<EMAIL>' ], component='UI>Browser', documentation_url= 'https://chromium.googlesource.com/chromium/src/+/main/docs/speed/benchmark/harnesses/desktop_ui.md' ) class DesktopUI(perf_benchmark.PerfBenchmark): """Desktop UI Benchmark.""" PLATFORM = 'desktop' SUPPORTED_PLATFORM_TAGS = [platforms.DESKTOP] SUPPORTED_PLATFORMS = [story.expectations.ALL_DESKTOP] def CreateStorySet(self, options): return page_sets.DesktopUIStorySet() def CreateCoreTimelineBasedMeasurementOptions(self): category_filter = chrome_trace_category_filter.ChromeTraceCategoryFilter( filter_string='uma') options = timeline_based_measurement.Options(category_filter) # Add more buffer since we are opening a lot of tabs. options.config.chrome_trace_config.SetTraceBufferSizeInKb(600 * 1024) options.SetTimelineBasedMetrics(['umaMetric']) return options def SetExtraBrowserOptions(self, options): # Make sure finch experiment is turned off for benchmarking. options.AppendExtraBrowserArgs('--enable-benchmarking') # UIDevtools is used for driving native UI. options.AppendExtraBrowserArgs('--enable-ui-devtools=0') @classmethod def Name(cls): return 'desktop_ui'
ashokr8142/phanitest
Android/app/src/main/java/com/harvard/webservicemodule/WebserviceSubscriber.java
/* * Copyright © 2017-2019 Harvard Pilgrim Health Care Institute (HPHCI) and its Contributors. * Copyright 2020 Google LLC * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * Funding Source: Food and Drug Administration (“Funding Agency”) effective 18 September 2014 as Contract no. HHSF22320140030I/HHSF22301006T (the “Prime Contract”). * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.harvard.webservicemodule; import com.harvard.R; import com.harvard.base.BaseSubscriber; import com.harvard.webservicemodule.apihelper.ApiCall; import com.harvard.webservicemodule.events.AuthServerConfigEvent; import com.harvard.webservicemodule.events.RegistrationServerConfigEvent; import com.harvard.webservicemodule.events.RegistrationServerConsentConfigEvent; import com.harvard.webservicemodule.events.RegistrationServerEnrollmentConfigEvent; import com.harvard.webservicemodule.events.ResponseServerConfigEvent; import com.harvard.webservicemodule.events.WCPConfigEvent; public class WebserviceSubscriber extends BaseSubscriber { public void onEvent(WCPConfigEvent wcpConfigEvent) { String url = ""; if (wcpConfigEvent .getmContext() .getResources() .getString(R.string.app_stage) .equalsIgnoreCase("development")) { url = wcpConfigEvent.getDevelopmentUrl() + wcpConfigEvent.getmUrl(); } else { url = wcpConfigEvent.getProductionUrl() + wcpConfigEvent.getmUrl(); } url = url.replaceAll(" ", "%20"); if (wcpConfigEvent.getmRequestType().equalsIgnoreCase("get")) { ApiCall apiCall = new ApiCall(wcpConfigEvent.getmContext()); apiCall.apiCallGet( url, wcpConfigEvent.getmHeaders(), wcpConfigEvent.gettClass(), wcpConfigEvent.getmResponseCode(), wcpConfigEvent.getV(), wcpConfigEvent.ismShowAlert(), "WCP"); } else if (wcpConfigEvent.getmRequestType().equalsIgnoreCase("post_object")) { ApiCall apiCall = new ApiCall(wcpConfigEvent.getmContext()); apiCall.apiCallPostJson( url, wcpConfigEvent.getmHeaders(), wcpConfigEvent.gettClass(), wcpConfigEvent.getmRequestParamsJson(), wcpConfigEvent.getmResponseCode(), wcpConfigEvent.getV(), wcpConfigEvent.ismShowAlert(), "WCP"); } else if (wcpConfigEvent.getmRequestType().equalsIgnoreCase("delete")) { ApiCall apiCall = new ApiCall(wcpConfigEvent.getmContext()); apiCall.apiCallDeleteHashmap( url, wcpConfigEvent.getmHeaders(), wcpConfigEvent.gettClass(), wcpConfigEvent.getmRequestParams(), wcpConfigEvent.getmResponseCode(), wcpConfigEvent.getV(), wcpConfigEvent.ismShowAlert(), "WCP"); } else if (wcpConfigEvent.getmRequestType().equalsIgnoreCase("delete_object")) { ApiCall apiCall = new ApiCall(wcpConfigEvent.getmContext()); apiCall.apiCallDeleteJson( url, wcpConfigEvent.getmHeaders(), wcpConfigEvent.gettClass(), wcpConfigEvent.getmRequestParamsJson(), wcpConfigEvent.getmResponseCode(), wcpConfigEvent.getV(), wcpConfigEvent.ismShowAlert(), "WCP"); } else { ApiCall apiCall = new ApiCall(wcpConfigEvent.getmContext()); apiCall.apiCallPostHashmap( url, wcpConfigEvent.getmHeaders(), wcpConfigEvent.gettClass(), wcpConfigEvent.getmRequestParams(), wcpConfigEvent.getmResponseCode(), wcpConfigEvent.getV(), wcpConfigEvent.ismShowAlert(), "WCP"); } } public void onEvent(RegistrationServerConfigEvent registrationServerConfigEvent) { String url = ""; if (registrationServerConfigEvent .getmContext() .getResources() .getString(R.string.app_stage) .equalsIgnoreCase("development")) { url = registrationServerConfigEvent.getDevelopmentUrl() + registrationServerConfigEvent.getmUrl(); } else { url = registrationServerConfigEvent.getProductionUrl() + registrationServerConfigEvent.getmUrl(); } url = url.replaceAll(" ", "%20"); if (registrationServerConfigEvent.getmRequestType().equalsIgnoreCase("get")) { ApiCall apiCall = new ApiCall(registrationServerConfigEvent.getmContext()); apiCall.apiCallGet( url, registrationServerConfigEvent.getmHeaders(), registrationServerConfigEvent.gettClass(), registrationServerConfigEvent.getmResponseCode(), registrationServerConfigEvent.getV(), registrationServerConfigEvent.ismShowAlert(), "RegistrationServer"); } else if (registrationServerConfigEvent.getmRequestType().equalsIgnoreCase("post_object")) { ApiCall apiCall = new ApiCall(registrationServerConfigEvent.getmContext()); apiCall.apiCallPostJson( url, registrationServerConfigEvent.getmHeaders(), registrationServerConfigEvent.gettClass(), registrationServerConfigEvent.getmRequestParamsJson(), registrationServerConfigEvent.getmResponseCode(), registrationServerConfigEvent.getV(), registrationServerConfigEvent.ismShowAlert(), "RegistrationServer"); } else if (registrationServerConfigEvent.getmRequestType().equalsIgnoreCase("delete")) { ApiCall apiCall = new ApiCall(registrationServerConfigEvent.getmContext()); apiCall.apiCallDeleteHashmap( url, registrationServerConfigEvent.getmHeaders(), registrationServerConfigEvent.gettClass(), registrationServerConfigEvent.getmRequestParams(), registrationServerConfigEvent.getmResponseCode(), registrationServerConfigEvent.getV(), registrationServerConfigEvent.ismShowAlert(), "RegistrationServer"); } else if (registrationServerConfigEvent.getmRequestType().equalsIgnoreCase("delete_object")) { ApiCall apiCall = new ApiCall(registrationServerConfigEvent.getmContext()); apiCall.apiCallDeleteJson( url, registrationServerConfigEvent.getmHeaders(), registrationServerConfigEvent.gettClass(), registrationServerConfigEvent.getmRequestParamsJson(), registrationServerConfigEvent.getmResponseCode(), registrationServerConfigEvent.getV(), registrationServerConfigEvent.ismShowAlert(), "RegistrationServer"); } else if (registrationServerConfigEvent.getmRequestType().equalsIgnoreCase("delete_array")) { ApiCall apiCall = new ApiCall(registrationServerConfigEvent.getmContext()); apiCall.apiCallDeleteJsonArray( url, registrationServerConfigEvent.getmHeaders(), registrationServerConfigEvent.gettClass(), registrationServerConfigEvent.getmRequestParamsJsonArray(), registrationServerConfigEvent.getmResponseCode(), registrationServerConfigEvent.getV(), registrationServerConfigEvent.ismShowAlert(), "RegistrationServer"); } else { ApiCall apiCall = new ApiCall(registrationServerConfigEvent.getmContext()); apiCall.apiCallPostHashmap( url, registrationServerConfigEvent.getmHeaders(), registrationServerConfigEvent.gettClass(), registrationServerConfigEvent.getmRequestParams(), registrationServerConfigEvent.getmResponseCode(), registrationServerConfigEvent.getV(), registrationServerConfigEvent.ismShowAlert(), "RegistrationServer"); } } public void onEvent(RegistrationServerConsentConfigEvent registrationServerConsentConfigEvent) { String url = ""; if (registrationServerConsentConfigEvent .getmContext() .getResources() .getString(R.string.app_stage) .equalsIgnoreCase("development")) { url = registrationServerConsentConfigEvent.getDevelopmentUrl() + registrationServerConsentConfigEvent.getmUrl(); } else { url = registrationServerConsentConfigEvent.getProductionUrl() + registrationServerConsentConfigEvent.getmUrl(); } url = url.replaceAll(" ", "%20"); if (registrationServerConsentConfigEvent.getmRequestType().equalsIgnoreCase("get")) { ApiCall apiCall = new ApiCall(registrationServerConsentConfigEvent.getmContext()); apiCall.apiCallGet( url, registrationServerConsentConfigEvent.getmHeaders(), registrationServerConsentConfigEvent.gettClass(), registrationServerConsentConfigEvent.getmResponseCode(), registrationServerConsentConfigEvent.getV(), registrationServerConsentConfigEvent.ismShowAlert(), "RegistrationServerConsent"); } else if (registrationServerConsentConfigEvent .getmRequestType() .equalsIgnoreCase("post_object")) { ApiCall apiCall = new ApiCall(registrationServerConsentConfigEvent.getmContext()); apiCall.apiCallPostJson( url, registrationServerConsentConfigEvent.getmHeaders(), registrationServerConsentConfigEvent.gettClass(), registrationServerConsentConfigEvent.getmRequestParamsJson(), registrationServerConsentConfigEvent.getmResponseCode(), registrationServerConsentConfigEvent.getV(), registrationServerConsentConfigEvent.ismShowAlert(), "RegistrationServerConsent"); } else if (registrationServerConsentConfigEvent.getmRequestType().equalsIgnoreCase("delete")) { ApiCall apiCall = new ApiCall(registrationServerConsentConfigEvent.getmContext()); apiCall.apiCallDeleteHashmap( url, registrationServerConsentConfigEvent.getmHeaders(), registrationServerConsentConfigEvent.gettClass(), registrationServerConsentConfigEvent.getmRequestParams(), registrationServerConsentConfigEvent.getmResponseCode(), registrationServerConsentConfigEvent.getV(), registrationServerConsentConfigEvent.ismShowAlert(), "RegistrationServerConsent"); } else if (registrationServerConsentConfigEvent .getmRequestType() .equalsIgnoreCase("delete_object")) { ApiCall apiCall = new ApiCall(registrationServerConsentConfigEvent.getmContext()); apiCall.apiCallDeleteJson( url, registrationServerConsentConfigEvent.getmHeaders(), registrationServerConsentConfigEvent.gettClass(), registrationServerConsentConfigEvent.getmRequestParamsJson(), registrationServerConsentConfigEvent.getmResponseCode(), registrationServerConsentConfigEvent.getV(), registrationServerConsentConfigEvent.ismShowAlert(), "RegistrationServerConsent"); } else if (registrationServerConsentConfigEvent .getmRequestType() .equalsIgnoreCase("delete_array")) { ApiCall apiCall = new ApiCall(registrationServerConsentConfigEvent.getmContext()); apiCall.apiCallDeleteJsonArray( url, registrationServerConsentConfigEvent.getmHeaders(), registrationServerConsentConfigEvent.gettClass(), registrationServerConsentConfigEvent.getmRequestParamsJsonArray(), registrationServerConsentConfigEvent.getmResponseCode(), registrationServerConsentConfigEvent.getV(), registrationServerConsentConfigEvent.ismShowAlert(), "RegistrationServerConsent"); } else { ApiCall apiCall = new ApiCall(registrationServerConsentConfigEvent.getmContext()); apiCall.apiCallPostHashmap( url, registrationServerConsentConfigEvent.getmHeaders(), registrationServerConsentConfigEvent.gettClass(), registrationServerConsentConfigEvent.getmRequestParams(), registrationServerConsentConfigEvent.getmResponseCode(), registrationServerConsentConfigEvent.getV(), registrationServerConsentConfigEvent.ismShowAlert(), "RegistrationServerConsent"); } } public void onEvent(AuthServerConfigEvent authServerConfigEvent) { String url = ""; if (authServerConfigEvent .getmContext() .getResources() .getString(R.string.app_stage) .equalsIgnoreCase("development")) { url = authServerConfigEvent.getDevelopmentUrl() + authServerConfigEvent.getmUrl(); } else { url = authServerConfigEvent.getProductionUrl() + authServerConfigEvent.getmUrl(); } url = url.replaceAll(" ", "%20"); if (authServerConfigEvent.getmRequestType().equalsIgnoreCase("get")) { ApiCall apiCall = new ApiCall(authServerConfigEvent.getmContext()); apiCall.apiCallGet( url, authServerConfigEvent.getmHeaders(), authServerConfigEvent.gettClass(), authServerConfigEvent.getmResponseCode(), authServerConfigEvent.getV(), authServerConfigEvent.ismShowAlert(), "AuthServer"); } else if (authServerConfigEvent.getmRequestType().equalsIgnoreCase("post_object")) { ApiCall apiCall = new ApiCall(authServerConfigEvent.getmContext()); apiCall.apiCallPostJson( url, authServerConfigEvent.getmHeaders(), authServerConfigEvent.gettClass(), authServerConfigEvent.getmRequestParamsJson(), authServerConfigEvent.getmResponseCode(), authServerConfigEvent.getV(), authServerConfigEvent.ismShowAlert(), "AuthServer"); } else if (authServerConfigEvent.getmRequestType().equalsIgnoreCase("delete")) { ApiCall apiCall = new ApiCall(authServerConfigEvent.getmContext()); apiCall.apiCallDeleteHashmap( url, authServerConfigEvent.getmHeaders(), authServerConfigEvent.gettClass(), authServerConfigEvent.getmRequestParams(), authServerConfigEvent.getmResponseCode(), authServerConfigEvent.getV(), authServerConfigEvent.ismShowAlert(), "AuthServer"); } else if (authServerConfigEvent.getmRequestType().equalsIgnoreCase("delete_object")) { ApiCall apiCall = new ApiCall(authServerConfigEvent.getmContext()); apiCall.apiCallDeleteJson( url, authServerConfigEvent.getmHeaders(), authServerConfigEvent.gettClass(), authServerConfigEvent.getmRequestParamsJson(), authServerConfigEvent.getmResponseCode(), authServerConfigEvent.getV(), authServerConfigEvent.ismShowAlert(), "AuthServer"); } else if (authServerConfigEvent.getmRequestType().equalsIgnoreCase("delete_array")) { ApiCall apiCall = new ApiCall(authServerConfigEvent.getmContext()); apiCall.apiCallDeleteJsonArray( url, authServerConfigEvent.getmHeaders(), authServerConfigEvent.gettClass(), authServerConfigEvent.getmRequestParamsJsonArray(), authServerConfigEvent.getmResponseCode(), authServerConfigEvent.getV(), authServerConfigEvent.ismShowAlert(), "AuthServer"); } else { ApiCall apiCall = new ApiCall(authServerConfigEvent.getmContext()); apiCall.apiCallPostHashmap( url, authServerConfigEvent.getmHeaders(), authServerConfigEvent.gettClass(), authServerConfigEvent.getmRequestParams(), authServerConfigEvent.getmResponseCode(), authServerConfigEvent.getV(), authServerConfigEvent.ismShowAlert(), "AuthServer"); } } public void onEvent(ResponseServerConfigEvent responseServerConfigEvent) { String url = ""; if (responseServerConfigEvent .getmContext() .getResources() .getString(R.string.app_stage) .equalsIgnoreCase("development")) { url = responseServerConfigEvent.getDevelopmentUrl() + responseServerConfigEvent.getmUrl(); } else { url = responseServerConfigEvent.getProductionUrl() + responseServerConfigEvent.getmUrl(); } url = url.replaceAll(" ", "%20"); if (responseServerConfigEvent.getmRequestType().equalsIgnoreCase("get")) { ApiCall apiCall = new ApiCall(responseServerConfigEvent.getmContext()); apiCall.apiCallGet( url, responseServerConfigEvent.getmHeaders(), responseServerConfigEvent.gettClass(), responseServerConfigEvent.getmResponseCode(), responseServerConfigEvent.getV(), responseServerConfigEvent.ismShowAlert(), "ResponseServer"); } else if (responseServerConfigEvent.getmRequestType().equalsIgnoreCase("post_object")) { ApiCall apiCall = new ApiCall(responseServerConfigEvent.getmContext()); apiCall.apiCallPostJson( url, responseServerConfigEvent.getmHeaders(), responseServerConfigEvent.gettClass(), responseServerConfigEvent.getmRequestParamsJson(), responseServerConfigEvent.getmResponseCode(), responseServerConfigEvent.getV(), responseServerConfigEvent.ismShowAlert(), "ResponseServer"); } else if (responseServerConfigEvent.getmRequestType().equalsIgnoreCase("delete")) { ApiCall apiCall = new ApiCall(responseServerConfigEvent.getmContext()); apiCall.apiCallDeleteHashmap( url, responseServerConfigEvent.getmHeaders(), responseServerConfigEvent.gettClass(), responseServerConfigEvent.getmRequestParams(), responseServerConfigEvent.getmResponseCode(), responseServerConfigEvent.getV(), responseServerConfigEvent.ismShowAlert(), "ResponseServer"); } else { ApiCall apiCall = new ApiCall(responseServerConfigEvent.getmContext()); apiCall.apiCallPostHashmap( url, responseServerConfigEvent.getmHeaders(), responseServerConfigEvent.gettClass(), responseServerConfigEvent.getmRequestParams(), responseServerConfigEvent.getmResponseCode(), responseServerConfigEvent.getV(), responseServerConfigEvent.ismShowAlert(), "ResponseServer"); } } public void onEvent( RegistrationServerEnrollmentConfigEvent registrationServerEnrollmentConfigEvent) { String url = ""; if (registrationServerEnrollmentConfigEvent .getmContext() .getResources() .getString(R.string.app_stage) .equalsIgnoreCase("development")) { url = registrationServerEnrollmentConfigEvent.getDevelopmentUrl() + registrationServerEnrollmentConfigEvent.getmUrl(); } else { url = registrationServerEnrollmentConfigEvent.getProductionUrl() + registrationServerEnrollmentConfigEvent.getmUrl(); } url = url.replaceAll(" ", "%20"); if (registrationServerEnrollmentConfigEvent.getmRequestType().equalsIgnoreCase("get")) { ApiCall apiCall = new ApiCall(registrationServerEnrollmentConfigEvent.getmContext()); apiCall.apiCallGet( url, registrationServerEnrollmentConfigEvent.getmHeaders(), registrationServerEnrollmentConfigEvent.gettClass(), registrationServerEnrollmentConfigEvent.getmResponseCode(), registrationServerEnrollmentConfigEvent.getV(), registrationServerEnrollmentConfigEvent.ismShowAlert(), "RegistrationServerEnrollment"); } else if (registrationServerEnrollmentConfigEvent .getmRequestType() .equalsIgnoreCase("post_object")) { ApiCall apiCall = new ApiCall(registrationServerEnrollmentConfigEvent.getmContext()); apiCall.apiCallPostJson( url, registrationServerEnrollmentConfigEvent.getmHeaders(), registrationServerEnrollmentConfigEvent.gettClass(), registrationServerEnrollmentConfigEvent.getmRequestParamsJson(), registrationServerEnrollmentConfigEvent.getmResponseCode(), registrationServerEnrollmentConfigEvent.getV(), registrationServerEnrollmentConfigEvent.ismShowAlert(), "RegistrationServerEnrollment"); } else if (registrationServerEnrollmentConfigEvent .getmRequestType() .equalsIgnoreCase("delete")) { ApiCall apiCall = new ApiCall(registrationServerEnrollmentConfigEvent.getmContext()); apiCall.apiCallDeleteHashmap( url, registrationServerEnrollmentConfigEvent.getmHeaders(), registrationServerEnrollmentConfigEvent.gettClass(), registrationServerEnrollmentConfigEvent.getmRequestParams(), registrationServerEnrollmentConfigEvent.getmResponseCode(), registrationServerEnrollmentConfigEvent.getV(), registrationServerEnrollmentConfigEvent.ismShowAlert(), "RegistrationServerEnrollment"); } else if (registrationServerEnrollmentConfigEvent .getmRequestType() .equalsIgnoreCase("delete_object")) { ApiCall apiCall = new ApiCall(registrationServerEnrollmentConfigEvent.getmContext()); apiCall.apiCallDeleteJson( url, registrationServerEnrollmentConfigEvent.getmHeaders(), registrationServerEnrollmentConfigEvent.gettClass(), registrationServerEnrollmentConfigEvent.getmRequestParamsJson(), registrationServerEnrollmentConfigEvent.getmResponseCode(), registrationServerEnrollmentConfigEvent.getV(), registrationServerEnrollmentConfigEvent.ismShowAlert(), "RegistrationServerEnrollment"); } else if (registrationServerEnrollmentConfigEvent .getmRequestType() .equalsIgnoreCase("delete_array")) { ApiCall apiCall = new ApiCall(registrationServerEnrollmentConfigEvent.getmContext()); apiCall.apiCallDeleteJsonArray( url, registrationServerEnrollmentConfigEvent.getmHeaders(), registrationServerEnrollmentConfigEvent.gettClass(), registrationServerEnrollmentConfigEvent.getmRequestParamsJsonArray(), registrationServerEnrollmentConfigEvent.getmResponseCode(), registrationServerEnrollmentConfigEvent.getV(), registrationServerEnrollmentConfigEvent.ismShowAlert(), "RegistrationServerEnrollment"); } else { ApiCall apiCall = new ApiCall(registrationServerEnrollmentConfigEvent.getmContext()); apiCall.apiCallPostHashmap( url, registrationServerEnrollmentConfigEvent.getmHeaders(), registrationServerEnrollmentConfigEvent.gettClass(), registrationServerEnrollmentConfigEvent.getmRequestParams(), registrationServerEnrollmentConfigEvent.getmResponseCode(), registrationServerEnrollmentConfigEvent.getV(), registrationServerEnrollmentConfigEvent.ismShowAlert(), "RegistrationServerEnrollment"); } } }
madusha98/hms-react-native-plugin
react-native-hms-contactshield/android/src/main/java/com/huawei/hms/rn/contactshield/utils/Utils.java
<gh_stars>100-1000 /* Copyright 2020-2021. Huawei Technologies Co., Ltd. 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 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. */ package com.huawei.hms.rn.contactshield.utils; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMapKeySetIterator; import com.facebook.react.bridge.ReadableType; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeArray; import com.facebook.react.bridge.WritableNativeMap; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.huawei.hms.contactshield.ContactDetail; import com.huawei.hms.contactshield.ContactSketch; import com.huawei.hms.contactshield.ContactWindow; import com.huawei.hms.contactshield.DailySketch; import com.huawei.hms.contactshield.DiagnosisConfiguration; import com.huawei.hms.contactshield.PeriodicKey; import com.huawei.hms.contactshield.ScanInfo; import com.huawei.hms.contactshield.SharedKeysDataMapping; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class Utils { public static WritableArray getIntArray(int[] i) { WritableArray wa = new WritableNativeArray(); for (int intArray : i) { wa.pushInt(intArray); } return wa; } public static WritableArray getByteArray(byte[] b) { WritableArray wa = new WritableNativeArray(); for (byte byteArray : b) { wa.pushInt(byteArray); } return wa; } public static WritableMap fromSharedKeysDataMappingToMap(SharedKeysDataMapping sharedKeysDataMapping) throws JSONException { WritableMap wm = new WritableNativeMap(); final JSONObject jsonObject = new JSONObject(); if (sharedKeysDataMapping == null) { return null; } wm.putInt("defaultContagiousness", sharedKeysDataMapping.getDefaultContagiousness()); wm.putInt("defaultReportType", sharedKeysDataMapping.getDefaultReportType()); jsonObject.put("daysSinceCreationToContagiousness", sharedKeysDataMapping.getDaysSinceCreationToContagiousness()); wm.putMap("daysSinceCreationToContagiousness",convertJsonToMap(jsonObject)); return wm; } public static WritableMap fromDailySketchDataToMap(DailySketch dailySketch) { WritableMap wm = new WritableNativeMap(); if (dailySketch == null) { return null; } wm.putInt("daysSinceEpoch", dailySketch.getDaysSinceEpoch()); wm.putDouble("maxScore", dailySketch.getSketchData().getMaxScore()); wm.putDouble("scoreSum", dailySketch.getSketchData().getScoreSum()); wm.putDouble("weightedDurationSum", dailySketch.getSketchData().getWeightedDurationSum()); return wm; } public static WritableArray fromDailySketchListToMap(List<DailySketch> dailySketches) { WritableArray array = new WritableNativeArray(); for (DailySketch dailySketch : dailySketches) { array.pushMap(fromDailySketchDataToMap(dailySketch)); } return array; } public static WritableMap fromContactSketchDataToMap(ContactSketch contactSketch) { WritableMap wm = new WritableNativeMap(); if (contactSketch == null) { return null; } wm.putArray("attenuationDurations", getIntArray(contactSketch.getAttenuationDurations())); wm.putInt("daysSinceLastHit", contactSketch.getDaysSinceLastHit()); wm.putInt("maxRiskValue", contactSketch.getMaxRiskValue()); wm.putInt("numberOfHits", contactSketch.getNumberOfHits()); wm.putInt("summationRiskValue", contactSketch.getSummationRiskValue()); return wm; } public static WritableArray fromContactDetailsListToMap(List<ContactDetail> contactDetailList) { WritableArray array = new WritableNativeArray(); for (ContactDetail contactDetail : contactDetailList) { array.pushMap(fromContactDetailsDataToMap(contactDetail)); } return array; } public static WritableMap fromContactDetailsDataToMap(ContactDetail contactDetail) { WritableMap wm = new WritableNativeMap(); if (contactDetail == null) { return null; } wm.putInt("attenuationRiskValue", contactDetail.getAttenuationRiskValue()); wm.putInt("durationMinutes", contactDetail.getDurationMinutes()); wm.putInt("totalRiskValue", contactDetail.getTotalRiskValue()); wm.putInt("totalRiskLevel", contactDetail.getInitialRiskLevel()); wm.putArray("attenuationDurations", getIntArray(contactDetail.getAttenuationDurations())); wm.putDouble("dayNumber", contactDetail.getDayNumber()); return wm; } public static WritableArray fromPeriodicKeyListToMap(List<PeriodicKey> periodicKeyList) { if (periodicKeyList == null) { return null; } WritableArray array = new WritableNativeArray(); for (PeriodicKey periodicKey : periodicKeyList) { array.pushMap(fromPeriodicKeyToMap(periodicKey)); } return array; } public static WritableMap fromPeriodicKeyToMap(PeriodicKey periodicKey) { WritableMap wm = new WritableNativeMap(); if (periodicKey == null) { return null; } wm.putArray("content", getByteArray(periodicKey.getContent())); wm.putInt("initialRiskLevel", periodicKey.getInitialRiskLevel()); wm.putDouble("periodicKeyLifeTime", periodicKey.getPeriodicKeyLifeTime()); wm.putDouble("periodicKeyValidTime", periodicKey.getPeriodicKeyValidTime()); wm.putInt("reportType", periodicKey.getReportType()); return wm; } public static WritableArray fromContactWindowListToMap(List<ContactWindow> contactWindowList) { if (contactWindowList == null) { return null; } WritableArray array = new WritableNativeArray(); for (ContactWindow contactWindow : contactWindowList) { array.pushMap(fromContactWindowToMap(contactWindow)); } return array; } public static WritableMap fromContactWindowToMap(ContactWindow contactWindow) { WritableMap wm = new WritableNativeMap(); WritableArray scanMap = new WritableNativeArray(); if (contactWindow == null) { return null; } wm.putInt("reportType", contactWindow.getReportType()); wm.putDouble("dateMillis", contactWindow.getDateMillis()); for (final ScanInfo scanInfo : contactWindow.getScanInfos()) { scanMap.pushMap(fromScanInfoToMap(scanInfo)); } wm.putArray("scanInfos", scanMap); return wm; } public static WritableMap fromScanInfoToMap(ScanInfo scanInfo) { WritableMap wm = new WritableNativeMap(); if (scanInfo == null) { return null; } wm.putInt("averageAttenuation", scanInfo.getAverageAttenuation()); wm.putInt("minimumAttenuation", scanInfo.getMinimumAttenuation()); wm.putInt("secondsSinceLastScan", scanInfo.getSecondsSinceLastScan()); return wm; } public static WritableMap fromDiagnosisConfigurationToMap(DiagnosisConfiguration diagnosisConfiguration){ WritableMap wm = new WritableNativeMap(); wm.putArray("attenuationDurationThresholds", getIntArray(diagnosisConfiguration.getAttenuationDurationThresholds())); wm.putArray("attenuationRiskValues", getIntArray(diagnosisConfiguration.getAttenuationRiskValues())); wm.putArray("daysAfterContactedRiskValues", getIntArray(diagnosisConfiguration.getDaysAfterContactedRiskValues())); wm.putArray("durationRiskValues", getIntArray(diagnosisConfiguration.getDurationRiskValues())); wm.putArray("initialRiskLevelRiskValues", getIntArray(diagnosisConfiguration.getInitialRiskLevelRiskValues())); wm.putInt("minimumRiskValueThreshold", diagnosisConfiguration.getMinimumRiskValueThreshold()); return wm; } public static JSONObject toJSONObject(ReadableMap readableMap) throws JSONException { JSONObject jsonObject = new JSONObject(); ReadableMapKeySetIterator iterator = readableMap.keySetIterator(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); ReadableType type = readableMap.getType(key); switch (type) { case Null: jsonObject.put(key, null); break; case Boolean: jsonObject.put(key, readableMap.getBoolean(key)); break; case Number: jsonObject.put(key, readableMap.getDouble(key)); break; case String: jsonObject.put(key, readableMap.getString(key)); break; case Map: jsonObject.put(key, Utils.toJSONObject(readableMap.getMap(key))); break; case Array: jsonObject.put(key, toJSONArray(readableMap.getArray(key))); break; default: break; } } return jsonObject; } public static Map<Integer, Integer> getMapObject(JSONObject daysSinceCreationToContagiousness) { return new Gson().fromJson( String.valueOf(daysSinceCreationToContagiousness), new TypeToken<HashMap<Integer, Integer>>() { }.getType() ); } public static JSONObject convertMapToJson(ReadableMap readableMap) throws JSONException { JSONObject object = new JSONObject(); ReadableMapKeySetIterator iterator = readableMap.keySetIterator(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); switch (readableMap.getType(key)) { case Null: object.put(key, JSONObject.NULL); break; case Boolean: object.put(key, readableMap.getBoolean(key)); break; case Number: object.put(key, readableMap.getDouble(key)); break; case String: object.put(key, readableMap.getString(key)); break; case Map: object.put(key, convertMapToJson(readableMap.getMap(key))); break; case Array: object.put(key, convertArrayToJson(readableMap.getArray(key))); break; default: break; } } return object; } public static JSONArray convertArrayToJson(ReadableArray readableArray) throws JSONException { JSONArray array = new JSONArray(); for (int i = 0; i < readableArray.size(); i++) { switch (readableArray.getType(i)) { case Null: break; case Boolean: array.put(readableArray.getBoolean(i)); break; case Number: array.put(readableArray.getDouble(i)); break; case String: array.put(readableArray.getString(i)); break; case Map: array.put(convertMapToJson(readableArray.getMap(i))); break; case Array: array.put(convertArrayToJson(readableArray.getArray(i))); break; default: break; } } return array; } public static List<String> convertJSONArrayToList(JSONArray jsonArray) throws JSONException { List<String> list = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { list.add(jsonArray.getString(i)); } return list; } public static JSONArray toJSONArray(ReadableArray readableArray) throws JSONException { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < readableArray.size(); i++) { ReadableType type = readableArray.getType(i); switch (type) { case Null: jsonArray.put(i, null); break; case Boolean: jsonArray.put(i, readableArray.getBoolean(i)); break; case Number: jsonArray.put(i, readableArray.getDouble(i)); break; case String: jsonArray.put(i, readableArray.getString(i)); break; case Map: jsonArray.put(i, toJSONObject(readableArray.getMap(i))); break; case Array: jsonArray.put(i, toJSONArray(readableArray.getArray(i))); break; default: break; } } return jsonArray; } public static WritableMap convertJsonToMap(JSONObject jsonObject) throws JSONException { WritableMap map = new WritableNativeMap(); Iterator<String> iterator = jsonObject.keys(); while (iterator.hasNext()) { String key = iterator.next(); Object value = jsonObject.get(key); if (value instanceof JSONObject) { map.putMap(key, convertJsonToMap((JSONObject) value)); } else if (value instanceof JSONArray) { map.putArray(key, convertJsonToArray((JSONArray) value)); } else if (value instanceof Boolean) { map.putBoolean(key, (Boolean) value); } else if (value instanceof Integer) { map.putInt(key, (Integer) value); } else if (value instanceof Double) { map.putDouble(key, (Double) value); } else if (value instanceof String) { map.putString(key, (String) value); } else { map.putString(key, value.toString()); } } return map; } public static WritableArray convertJsonToArray(JSONArray jsonArray) throws JSONException { WritableArray array = new WritableNativeArray(); for (int i = 0; i < jsonArray.length(); i++) { Object value = jsonArray.get(i); if (value instanceof JSONObject) { array.pushMap(convertJsonToMap((JSONObject) value)); } else if (value instanceof JSONArray) { array.pushArray(convertJsonToArray((JSONArray) value)); } else if (value instanceof Boolean) { array.pushBoolean((Boolean) value); } else if (value instanceof Integer) { array.pushInt((Integer) value); } else if (value instanceof Double) { array.pushDouble((Double) value); } else if (value instanceof String) { array.pushString((String) value); } else { array.pushString(value.toString()); } } return array; } }
solante1012/tms
src/test/java/com/lhjz/portal/util/FileUtilTest.java
package com.lhjz.portal.util; import org.apache.commons.io.FileUtils; import org.testng.Assert; import org.testng.annotations.Test; public class FileUtilTest { @Test public void test() { System.out.println(FileUtil.getName("C:\\ddfd\\dfdfdff\\etetr.txt")); System.out.println(FileUtils.getFile("C:\\ddfd\\dfdfdff\\etetr.txt") .getName()); } @Test public void joinPathsTest() { System.out.println(FileUtil.joinPaths("aa", "bb/", "cc")); Assert.assertFalse(FileUtil.joinPaths("aa", "bb/", "cc").endsWith("/")); } @Test public void joinPathsTest2() { System.out.println(FileUtil.joinPaths("aa", "bb/", "cc/")); Assert.assertTrue(FileUtil.joinPaths("aa", "bb/", "cc/").endsWith("/")); } @Test public void joinPathsTest3() { System.out.println(FileUtil.joinPaths("aa\\", "ee\\bb\\", "ff/cc/")); Assert.assertTrue(FileUtil.joinPaths("aa\\", "ee\\bb\\", "ff/cc/") .equals("aa/ee/bb/ff/cc/")); } @Test public void joinPathsTest4() { Assert.assertTrue(FileUtil .joinPaths("aa\\", "ee\\bb\\", "ff/cc/aa.txt").equals( "aa/ee/bb/ff/cc/aa.txt")); } }
smiley0907/purnacache
src/core/org/apache/hadoop/net/SocketOutputStream.java
<gh_stars>1-10 /** * 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.net; import java.io.EOFException; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.WritableByteChannel; /** * This implements an output stream that can have a timeout while writing. This * sets non-blocking flag on the socket channel. So after creating this object , * read() on {@link Socket#getInputStream()} and write() on * {@link Socket#getOutputStream()} on the associated socket will throw * llegalBlockingModeException. Please use {@link SocketInputStream} for * reading. */ public class SocketOutputStream extends OutputStream implements WritableByteChannel { private Writer writer; private static class Writer extends SocketIOWithTimeout { WritableByteChannel channel; Writer(WritableByteChannel channel, long timeout) throws IOException { super((SelectableChannel) channel, timeout); this.channel = channel; } int performIO(ByteBuffer buf) throws IOException { return channel.write(buf); } } /** * Create a new ouput stream with the given timeout. If the timeout is zero, * it will be treated as infinite timeout. The socket's channel will be * configured to be non-blocking. * * @param channel * Channel for writing, should also be a * {@link SelectableChannel}. The channel will be configured to * be non-blocking. * @param timeout * timeout in milliseconds. must not be negative. * @throws IOException */ public SocketOutputStream(WritableByteChannel channel, long timeout) throws IOException { SocketIOWithTimeout.checkChannelValidity(channel); writer = new Writer(channel, timeout); } /** * Same as SocketOutputStream(socket.getChannel(), timeout):<br> * <br> * * Create a new ouput stream with the given timeout. If the timeout is zero, * it will be treated as infinite timeout. The socket's channel will be * configured to be non-blocking. * * @see SocketOutputStream#SocketOutputStream(WritableByteChannel, long) * * @param socket * should have a channel associated with it. * @param timeout * timeout timeout in milliseconds. must not be negative. * @throws IOException */ public SocketOutputStream(Socket socket, long timeout) throws IOException { this(socket.getChannel(), timeout); } public void write(int b) throws IOException { /* * If we need to, we can optimize this allocation. probably no need to * optimize or encourage single byte writes. */ byte[] buf = new byte[1]; buf[0] = (byte) b; write(buf, 0, 1); } public void write(byte[] b, int off, int len) throws IOException { ByteBuffer buf = ByteBuffer.wrap(b, off, len); while (buf.hasRemaining()) { try { if (write(buf) < 0) { throw new IOException("The stream is closed"); } } catch (IOException e) { /* * Unlike read, write can not inform user of partial writes. So * will close this if there was a partial write. */ if (buf.capacity() > buf.remaining()) { writer.close(); } throw e; } } } public synchronized void close() throws IOException { /* * close the channel since Socket.getOuputStream().close() closes the * socket. */ writer.channel.close(); writer.close(); } /** * Returns underlying channel used by this stream. This is useful in certain * cases like channel for * {@link FileChannel#transferTo(long, long, WritableByteChannel)} */ public WritableByteChannel getChannel() { return writer.channel; } // WritableByteChannle interface public boolean isOpen() { return writer.isOpen(); } public int write(ByteBuffer src) throws IOException { return writer.doIO(src, SelectionKey.OP_WRITE); } /** * waits for the underlying channel to be ready for writing. The timeout * specified for this stream applies to this wait. * * @throws SocketTimeoutException * if select on the channel times out. * @throws IOException * if any other I/O error occurs. */ public void waitForWritable() throws IOException { writer.waitForIO(SelectionKey.OP_WRITE); } /** * Transfers data from FileChannel using * {@link FileChannel#transferTo(long, long, WritableByteChannel)}. * * Similar to readFully(), this waits till requested amount of data is * transfered. * * @param fileCh * FileChannel to transfer data from. * @param position * position within the channel where the transfer begins * @param count * number of bytes to transfer. * * @throws EOFException * If end of input file is reached before requested number of * bytes are transfered. * * @throws SocketTimeoutException * If this channel blocks transfer longer than timeout for this * stream. * * @throws IOException * Includes any exception thrown by * {@link FileChannel#transferTo(long, long, WritableByteChannel)} * . */ public void transferToFully(FileChannel fileCh, long position, int count) throws IOException { while (count > 0) { /* * Ideally we should wait after transferTo returns 0. But because of * a bug in JRE on Linux * (http://bugs.sun.com/view_bug.do?bug_id=5103988), which throws an * exception instead of returning 0, we wait for the channel to be * writable before writing to it. If you ever see IOException with * message "Resource temporarily unavailable" thrown here, please * let us know. * * Once we move to JAVA SE 7, wait should be moved to correct place. */ waitForWritable(); int nTransfered = (int) fileCh.transferTo(position, count, getChannel()); if (nTransfered == 0) { // check if end of file is reached. if (position >= fileCh.size()) { throw new EOFException("EOF Reached. file size is " + fileCh.size() + " and " + count + " more bytes left to be " + "transfered."); } // otherwise assume the socket is full. // waitForWritable(); // see comment above. } else if (nTransfered < 0) { throw new IOException("Unexpected return of " + nTransfered + " from transferTo()"); } else { position += nTransfered; count -= nTransfered; } } } }
TheMindVirus/pftf-rpi4
edk2-platforms/Silicon/Intel/CoffeelakeSiliconPkg/Pch/Library/PeiPchPolicyLib/PeiPchPolicyLibrary.h
/** @file Header file for the PeiPchPolicy library. Copyright (c) 2019 - 2020 Intel Corporation. All rights reserved. <BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef _PEI_PCH_POLICY_LIBRARY_H_ #define _PEI_PCH_POLICY_LIBRARY_H_ #include <Library/DebugLib.h> #include <Library/IoLib.h> #include <Library/BaseMemoryLib.h> #include <Library/PeiServicesLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/SiConfigBlockLib.h> #include <Library/PchInfoLib.h> #include <Library/SataLib.h> #include <Ppi/SiPolicy.h> #include <Library/PchSerialIoLib.h> #include <Library/PchPolicyLib.h> /** Adds interrupt configuration for device @param[in/out] InterruptConfig Pointer to interrupt config **/ VOID LoadDeviceInterruptConfig ( IN OUT PCH_INTERRUPT_CONFIG *InterruptConfig ); #endif // _PEI_PCH_POLICY_LIBRARY_H_
Youslam/weighing
src/main/java/com/smart/app/weighing/controller/web/PesageController.java
package com.smart.app.weighing.controller.web; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.smart.app.weighing.model.Pesage; import com.smart.app.weighing.service.PesageService; import com.smart.app.weighing.service.VehicleService; @Controller @RequestMapping("/history") public class PesageController { Logger log = LoggerFactory.getLogger(this.getClass()); @Autowired PesageService pesageService; @Autowired VehicleService vehicleService; @GetMapping("/page") public String findAll(Model model, @RequestParam(defaultValue="0") int page) { Page<Pesage> historyList = pesageService.findAll(PageRequest.of(page, 2, orderByDateDesc())); model.addAttribute("histories", historyList); model.addAttribute("actionName", "historique"); model.addAttribute("total", historyList.getTotalPages()); model.addAttribute("currentPage", page); return "pages/historique"; } private Sort orderByDateDesc() { return new Sort(Sort.Direction.DESC, "dateTime"); } @GetMapping("/search") public String searchHistory(Model model, @RequestParam("filter") String filter, @RequestParam("term") String term) { List<Pesage> historyList = pesageService.searchPesageByTerm(filter, term); model.addAttribute("histories", historyList); model.addAttribute("actionName", "historique"); model.addAttribute("total", 1); model.addAttribute("currentPage", 0); return "pages/historique"; } }
loye168/tddl5
tddl-rule/src/main/java/com/taobao/tddl/rule/enumerator/handler/NumberPartDiscontinousRangeEnumerator.java
package com.taobao.tddl.rule.enumerator.handler; import java.util.Set; import com.taobao.tddl.common.model.sqljep.Comparative; public abstract class NumberPartDiscontinousRangeEnumerator extends PartDiscontinousRangeEnumerator { protected static final int LIMIT_UNIT_OF_LONG = 1; protected static final int DEFAULT_LONG_ATOMIC_VALUE = 1; protected static final boolean isAllowNegative; static { /** * 大多数整形的ID/分库分表字段默认都是大于零的。如果有小于0的系统,那么将这个参数设为true, * 同时自己要保证要么不出现id<3这样的条件,要么算出负的dbIndex也没有问题 */ isAllowNegative = "true".equals(System.getProperty("com.taobao.tddl.rule.isAllowNegativeShardValue", "false")); } @Override protected Comparative changeGreater2GreaterOrEq(Comparative from) { if (from.getComparison() == Comparative.GreaterThan) { Number fromComparable = cast2Number(from.getValue()); return new Comparative(Comparative.GreaterThanOrEqual, (Comparable) plus(fromComparable, LIMIT_UNIT_OF_LONG)); } else { return from; } } @Override protected Comparative changeLess2LessOrEq(Comparative to) { if (to.getComparison() == Comparative.LessThan) { Number toComparable = cast2Number(to.getValue()); return new Comparative(Comparative.LessThanOrEqual, (Comparable) plus(toComparable, -1 * LIMIT_UNIT_OF_LONG)); } else { return to; } } @Override protected Comparable getOneStep(Comparable source, Comparable atomIncVal) { if (atomIncVal == null) { atomIncVal = DEFAULT_LONG_ATOMIC_VALUE; } Number sourceLong = cast2Number(source); int atomIncValInt = (Integer) atomIncVal; return (Comparable) plus(sourceLong, atomIncValInt); } @SuppressWarnings("rawtypes") protected boolean inputCloseRangeGreaterThanMaxFieldOfDifination(Comparable from, Comparable to, Integer cumulativeTimes, Comparable<?> atomIncrValue) { if (cumulativeTimes == null) { return false; } if (atomIncrValue == null) { atomIncrValue = DEFAULT_LONG_ATOMIC_VALUE; } long fromLong = ((Number) from).longValue(); long toLong = ((Number) to).longValue(); int atomIncValLong = ((Number) atomIncrValue).intValue(); int size = cumulativeTimes; if ((toLong - fromLong) > (atomIncValLong * size)) { return true; } else { return false; } } public void processAllPassableFields(Comparative begin, Set<Object> retValue, Integer cumulativeTimes, Comparable<?> atomicIncreationValue) { if (cumulativeTimes == null) { throw new IllegalStateException("在没有提供叠加次数的前提下,不能够根据当前范围条件选出对应的定义域的枚举值,sql中不要出现> < >= <="); } if (atomicIncreationValue == null) { atomicIncreationValue = DEFAULT_LONG_ATOMIC_VALUE; } // 把> < 替换为>= <= begin = changeGreater2GreaterOrEq(begin); begin = changeLess2LessOrEq(begin); // long beginInt = (Long) toPrimaryValue(begin.getValue()); Number beginInt = getNumber(begin.getValue()); int atomicIncreateValueInt = ((Number) atomicIncreationValue).intValue(); int comparasion = begin.getComparison(); if (comparasion == Comparative.GreaterThanOrEqual) { for (int i = 0; i < cumulativeTimes; i++) { retValue.add(plus(beginInt, atomicIncreateValueInt * i)); } } else if (comparasion == Comparative.LessThanOrEqual) { for (int i = 0; i < cumulativeTimes; i++) { // 这里可能出现不期望的负数 Number value = (Number) plus(beginInt, -1 * atomicIncreateValueInt * i); if (!isAllowNegative && value.longValue() < 0) { break; } retValue.add(value); } } } protected abstract Number cast2Number(Comparable begin); protected abstract Number getNumber(Comparable begin); protected abstract Number plus(Number begin, int plus); }
mavlushechka/StudentDatabase
src/main/java/com/mavlushechka/studentdatabase/config/WebSecurityConfig.java
package com.mavlushechka.studentdatabase.config; import com.mavlushechka.studentdatabase.service.CustomUserDetailsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @Autowired CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler; @Bean public UserDetailsService mongoUserDetails() { return new CustomUserDetailsService(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { UserDetailsService userDetailsService = mongoUserDetails(); auth .userDetailsService(userDetailsService) .passwordEncoder(bCryptPasswordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin-panel/**").hasAuthority("ADMIN") .anyRequest().authenticated() .and() .csrf() .disable() .formLogin() .loginPage("/authentication/login") .permitAll() .and() .logout() .logoutSuccessUrl("/") .permitAll() .and() .exceptionHandling(); } @Override public void configure(WebSecurity web) { web .ignoring() .antMatchers("/js/**", "/css/**", "/img/**", "/fonts/**"); } }
lukaszbudnik/hackaton-portal
app/security/Security.scala
<gh_stars>1-10 package security import scala.annotation.implicitNotFound import org.squeryl.PrimitiveTypeMode.inTransaction import play.api.mvc.AnyContent import play.api.mvc.Result import securesocial.core.SecuredRequest trait Security extends securesocial.core.SecureSocial { /** * general purpose ensure method */ def ensure(condition: model.User => Boolean)(f: => Result)(implicit request: SecuredRequest[AnyContent]): Result = { inTransaction { val socialUser = request.user val user = model.User.lookupByOpenId(socialUser.id.id + socialUser.id.providerId) user match { case Some(u: model.User) if condition(u) => f case _ => throw new SecurityAbuseException(socialUser) } } } /** * helper methods */ def ensureAdmin(f: => Result)(implicit request: SecuredRequest[AnyContent]): Result = { inTransaction { ensure(u => u.isAdmin)(f) } } def ensureAdmin(optionalCondition: model.User => Boolean = {u => true})(f: => Result)(implicit request: SecuredRequest[AnyContent]): Result = { inTransaction { ensure(u => optionalCondition(u) && u.isAdmin)(f) } } def ensureHackathonOrganiserOrAdmin(hackathon: model.Hackathon, optionalCondition: model.User => Boolean = {u => true})(f: => Result)(implicit request: SecuredRequest[AnyContent]): Result = { inTransaction { ensure(u => (optionalCondition(u) && (u.isAdmin || hackathon.organiserId == u.id)))(f) } } def ensureHackathonOrganiserOrTeamLeaderOrAdmin(hackathon: model.Hackathon, team: model.Team, optionalCondition: model.User => Boolean = {u => true})(f: => Result)(implicit request: SecuredRequest[AnyContent]): Result = { inTransaction { ensure(u => (optionalCondition(u) && (u.isAdmin || hackathon.organiserId == u.id || team.creatorId == u.id)))(f) } } def ensureTeamLeaderOrAdmin(team: model.Team, optionalCondition: model.User => Boolean = {u => true})(f: => Result)(implicit request: SecuredRequest[AnyContent]): Result = { inTransaction { ensure(u => (optionalCondition(u) && (u.isAdmin || team.creatorId == u.id)))(f) } } def ensureHackathonOrganiserOrProblemSubmitterOrAdmin(hackathon: model.Hackathon, problem: model.Problem, optionalCondition: model.User => Boolean = {u => true})(f: => Result)(implicit request: SecuredRequest[AnyContent]): Result = { inTransaction { ensure(u => (optionalCondition(u) && (u.isAdmin || hackathon.organiserId == u.id || problem.submitterId == u.id)))(f) } } def ensureProblemSubmitterOrAdmin(problem: model.Problem, optionalCondition: model.User => Boolean = {u => true})(f: => Result)(implicit request: SecuredRequest[AnyContent]): Result = { inTransaction { ensure(u => (optionalCondition(u) && (u.isAdmin || problem.submitterId == u.id)))(f) } } def ensureLocationSubmitterOrAdmin(location: model.Location, optionalCondition: model.User => Boolean = {u => true})(f: => Result)(implicit request: SecuredRequest[AnyContent]): Result = { inTransaction { ensure(u => (optionalCondition(u) && (u.isAdmin || location.submitterId == u.id)))(f) } } def ensureNewsAuthorOrAdmin(news: model.News, optionalCondition: model.User => Boolean = {u => true})(f: => Result)(implicit request: SecuredRequest[AnyContent]): Result = { inTransaction { ensure(u => (optionalCondition(u) && (u.isAdmin || news.authorId == u.id)))(f) } } def ensureHackathonOrganiserOrNewsAuthorOrAdmin(hackathon: model.Hackathon, news: model.News, optionalCondition: model.User => Boolean = {u => true})(f: => Result)(implicit request: SecuredRequest[AnyContent]): Result = { inTransaction { ensure(u => (optionalCondition(u) && (u.isAdmin || news.authorId == u.id || hackathon.organiserId == u.id)))(f) } } }
Mi7ai/Algoritmia
Repaso Examenes/enero2015/enero2015voraces.py
<gh_stars>0 # no coge los numeros de X, a veces def galeria(X, D): res = [X[0] + D] for nr in X: if nr > res[-1] + D: res.append(nr + D) return res def galeria2(X, D): res = [] if len(X) > 1: res.append(X[0]) else: return None for i in range(len(X)): if res[-1] + D < X[i]: res.append(X[i]) return res if __name__ == '__main__': X = [2, 3, 4, 5, 7, 8, 9, 13, 15] D = 2 print(galeria(X, D),"este no va bien") print(galeria2(X, D))
ulivz/marko
test/autotests/components-browser/rerender-same-id/test.js
var expect = require('chai').expect; module.exports = function(helpers) { var component = helpers.mount(require('./index'), { label: 'Foo' }); var oldId = component.id; component.input = { label: 'Bar' }; component.update(); expect(component.el.id).to.equal(oldId); };
twocucao/tifa
tests/functional/test_product.py
import pytest from sqlalchemy.ext.asyncio import AsyncSession from tifa.db.adal import AsyncDal from tifa.models.product import ProductType @pytest.mark.asyncio async def test_filtering_by_attribute( session: AsyncSession, product_type, # color_attribute, # size_attribute, # # category, # date_attribute, # date_time_attribute, # # boolean_attribute, ): adal = AsyncDal(session) assert len(await adal.all(ProductType)) == 1 ... # product_type_a = ProductType.objects.create( # name="New class", slug="new-class1", has_variants=True # ) # product_type_a.product_attributes.add(color_attribute) # product_type_b = ProductType.objects.create( # name="New class", slug="new-class2", has_variants=True # ) # product_type_b.variant_attributes.add(color_attribute) # product_a = Product.objects.create( # name="Test product a", # slug="test-product-a", # product_type=product_type_a, # category=category, # ) # variant_a = ProductVariant.objects.create(product=product_a, sku="1234") # # ProductVariantChannelListing.objects.create( # # variant=variant_a, # # channel=channel_USD, # # cost_price_amount=Decimal(1), # # price_amount=Decimal(10), # # currency=channel_USD.currency_code, # # ) # # product_b = Product.objects.create( # # name="Test product b", # # slug="test-product-b", # # product_type=product_type_b, # # category=category, # # ) # # variant_b = ProductVariant.objects.create(product=product_b, sku="12345")
a10501/equipment-server
equipment-admin/src/main/java/com/equipment/equipmentMan/controller/EqUseTimeController.java
<filename>equipment-admin/src/main/java/com/equipment/equipmentMan/controller/EqUseTimeController.java<gh_stars>0 package com.equipment.equipmentMan.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.equipment.equipmentMan.domain.EqDatamanage; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.equipment.common.annotation.Log; import com.equipment.common.core.controller.BaseController; import com.equipment.common.core.domain.AjaxResult; import com.equipment.common.enums.BusinessType; import com.equipment.equipmentMan.service.IEqUseTimeService; import com.equipment.common.utils.poi.ExcelUtil; import com.equipment.common.core.page.TableDataInfo; /** * 时长分析Controller * * @author cdy * @date 2022-04-09 */ @RestController @RequestMapping("/equipmentMan/usetime") public class EqUseTimeController extends BaseController { @Autowired private IEqUseTimeService eqUseTimeService; /** * 查询用户时长分析列表 */ @PreAuthorize("@ss.hasPermi('equipmentMan:usetime:list')") @GetMapping("/list") public TableDataInfo list(EqDatamanage eqDatamanage,String flag) { List<EqDatamanage> list = new ArrayList<>(); System.out.println(flag); startPage(); if(flag.equals("1")){ list = eqUseTimeService.selectEqUseTimeList(eqDatamanage); }else if(flag.equals("2")){ list = eqUseTimeService.selectEqUDataNameTimeList(eqDatamanage); }else { list = eqUseTimeService.selectEqUDataLocationList(eqDatamanage); } return getDataTable(list); } /** * 导出时长分析列表 */ @PreAuthorize("@ss.hasPermi('equipmentMan:usetime:export')") @Log(title = "时长分析", businessType = BusinessType.EXPORT) @PostMapping("/export") public void export(HttpServletResponse response, EqDatamanage eqDatamanage,String flag) { List<EqDatamanage> list = new ArrayList<>(); if(flag.equals("1")){ list = eqUseTimeService.selectEqUseTimeList(eqDatamanage); }else if(flag.equals("2")){ list = eqUseTimeService.selectEqUDataNameTimeList(eqDatamanage); }else { list = eqUseTimeService.selectEqUDataLocationList(eqDatamanage); } ExcelUtil<EqDatamanage> util = new ExcelUtil<EqDatamanage>(EqDatamanage.class); util.exportExcel(response, list, "时长分析数据"); } }
EvilMcJerkface/grappa
system/tasks/StealQueue.cpp
//////////////////////////////////////////////////////////////////////// // Copyright (c) 2010-2015, University of Washington and Battelle // Memorial Institute. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials // provided with the distribution. // * Neither the name of the University of Washington, Battelle // Memorial Institute, or the names of their contributors may be // used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // UNIVERSITY OF WASHINGTON OR BATTELLE MEMORIAL INSTITUTE BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. //////////////////////////////////////////////////////////////////////// #include "StealQueue.hpp" #include "Metrics.hpp" #include "DictOut.hpp" /* metrics */ // work steal network usage GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, stealq_reply_messages, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, stealq_reply_total_bytes, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, stealq_request_messages, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, stealq_request_total_bytes, 0); // work share network usage GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, workshare_request_messages, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, workshare_request_total_bytes, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, workshare_reply_messages, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, workshare_reply_total_bytes, 0); // work share elements transfered GRAPPA_DEFINE_METRIC(SummarizingMetric<uint64_t>, workshare_request_elements_denied, 0); GRAPPA_DEFINE_METRIC(SummarizingMetric<uint64_t>, workshare_request_elements_received, 0); GRAPPA_DEFINE_METRIC(SummarizingMetric<uint64_t>, workshare_reply_elements_sent, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, workshare_requests_client_smaller, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, workshare_requests_client_larger, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, workshare_reply_nacks, 0); // global queue data transfer network usage GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, globalq_data_pull_request_messages, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, globalq_data_pull_request_total_bytes, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, globalq_data_pull_reply_messages, 0); GRAPPA_DEFINE_METRIC(SimpleMetric<uint64_t>, globalq_data_pull_reply_total_bytes, 0); // global queue elements transfered GRAPPA_DEFINE_METRIC(SummarizingMetric<uint64_t>, globalq_data_pull_request_num_elements, 0); GRAPPA_DEFINE_METRIC(SummarizingMetric<uint64_t>, globalq_data_pull_reply_num_elements, 0); namespace Grappa { namespace impl { void StealMetrics::record_steal_reply( size_t msg_bytes ) { stealq_reply_messages += 1; stealq_reply_total_bytes += msg_bytes; } void StealMetrics::record_steal_request( size_t msg_bytes ) { stealq_request_messages += 1; stealq_request_total_bytes += msg_bytes; } void StealMetrics::record_workshare_request( size_t msg_bytes ) { workshare_request_messages += 1; workshare_request_total_bytes += msg_bytes; } void StealMetrics::record_workshare_reply( size_t msg_bytes, bool isAccepted, int num_received, int num_denying, int num_sending ) { workshare_reply_messages += 1; workshare_reply_total_bytes += msg_bytes; if ( isAccepted ) { workshare_requests_client_smaller += 1; } else { workshare_requests_client_larger += 1; } workshare_request_elements_received+=( num_received ); workshare_request_elements_denied+=( num_denying ); workshare_reply_elements_sent+=( num_sending ); } void StealMetrics::record_workshare_reply_nack( size_t msg_bytes ) { workshare_reply_messages += 1; workshare_reply_total_bytes += msg_bytes; workshare_reply_nacks += 1; } void StealMetrics::record_globalq_data_pull_request( size_t msg_bytes, uint64_t amount ) { globalq_data_pull_request_messages += 1; globalq_data_pull_request_total_bytes += msg_bytes; globalq_data_pull_request_num_elements+=amount ; } void StealMetrics::record_globalq_data_pull_reply( size_t msg_bytes, uint64_t amount ) { globalq_data_pull_reply_messages += 1; globalq_data_pull_reply_total_bytes += msg_bytes; globalq_data_pull_reply_num_elements += amount ; } } // namespace impl } // namespace Grappa
ixiDev/iris
src/runtime/HubClient.cpp
#include <brisbane/brisbane.h> #include "HubClient.h" #include "Hub.h" #include "Debug.h" #include "Message.h" #include "Scheduler.h" #include <stdlib.h> #include <unistd.h> namespace brisbane { namespace rt { HubClient::HubClient(Scheduler* scheduler) { ndevs_ = -1; if (scheduler) { scheduler_ = scheduler; ndevs_ = scheduler->ndevs(); } pid_ = getpid(); fifo_ = -1; available_ = false; stop_hub_ = false; } HubClient::~HubClient() { if (!stop_hub_) CloseMQ(); } int HubClient::Init() { int ret = OpenMQ(); if (ret == BRISBANE_OK) ret = OpenFIFO(); if (ret == BRISBANE_OK) Register(); available_ = ret == BRISBANE_OK; return ret; } int HubClient::StopHub() { if (!available_) return BRISBANE_ERR; Message msg(BRISBANE_HUB_MQ_STOP); msg.WritePID(pid_); SendMQ(msg); msg.Clear(); RecvFIFO(msg); stop_hub_ = true; return BRISBANE_OK; } int HubClient::Status() { if (!available_) return BRISBANE_ERR; Message msg(BRISBANE_HUB_MQ_STATUS); msg.WritePID(pid_); SendMQ(msg); msg.Clear(); RecvFIFO(msg); int header = msg.ReadHeader(); int ndevs = msg.ReadInt(); for (int i = 0; i < ndevs; i++) { _info("Device[%d] ntasks[%lu]", i, msg.ReadULong()); } return BRISBANE_OK; } int HubClient::OpenMQ() { #if !USE_HUB return BRISBANE_ERR; #else key_t key; if ((key = ftok(BRISBANE_HUB_MQ_PATH, BRISBANE_HUB_MQ_PID)) == -1) return BRISBANE_ERR; if ((mq_ = msgget(key, BRISBANE_HUB_PERM | IPC_CREAT)) == -1) return BRISBANE_ERR; return BRISBANE_OK; #endif } int HubClient::CloseMQ() { if (fifo_ != -1) { CloseFIFO(); Deregister(); } return BRISBANE_OK; } int HubClient::SendMQ(Message& msg) { #if !USE_HUB return BRISBANE_ERR; #else int iret = msgsnd(mq_, msg.buf(), BRISBANE_HUB_MQ_MSG_SIZE, 0); if (iret == -1) { _error("msgsnd err[%d]", iret); perror("msgsnd"); return BRISBANE_ERR; } return BRISBANE_OK; #endif } int HubClient::OpenFIFO() { char path[64]; sprintf(path, "%s.%d", BRISBANE_HUB_FIFO_PATH, pid_); int iret = mknod(path, S_IFIFO | BRISBANE_HUB_PERM, 0); if (iret == -1) { _error("iret[%d]", iret); perror("mknod"); return BRISBANE_ERR; } fifo_ = open(path, O_RDWR); if (fifo_ == -1) { _error("path[%s]", path); perror("read"); return BRISBANE_ERR; } return BRISBANE_OK; } int HubClient::CloseFIFO() { int iret = close(fifo_); if (iret == -1) { _error("iret[%d]", iret); perror("close"); } return BRISBANE_OK; } int HubClient::RecvFIFO(Message& msg) { ssize_t ssret = read(fifo_, msg.buf(), BRISBANE_HUB_FIFO_MSG_SIZE); if (ssret != BRISBANE_HUB_FIFO_MSG_SIZE) { _error("ssret[%zd]", ssret); perror("read"); return BRISBANE_ERR; } return BRISBANE_OK; } int HubClient::Register() { Message msg(BRISBANE_HUB_MQ_REGISTER); msg.WritePID(pid_); msg.WriteInt(ndevs_); SendMQ(msg); return BRISBANE_OK; } int HubClient::Deregister() { Message msg(BRISBANE_HUB_MQ_DEREGISTER); msg.WritePID(pid_); SendMQ(msg); return BRISBANE_OK; } int HubClient::TaskInc(int dev, int i) { if (!available_) return BRISBANE_OK; Message msg(BRISBANE_HUB_MQ_TASK_INC); msg.WritePID(pid_); msg.WriteInt(dev); msg.WriteInt(i); SendMQ(msg); return BRISBANE_OK; } int HubClient::TaskDec(int dev, int i) { return TaskInc(dev, -i); } int HubClient::TaskAll(size_t* ntasks, int ndevs) { Message msg(BRISBANE_HUB_MQ_TASK_ALL); msg.WritePID(pid_); msg.WriteInt(ndevs); SendMQ(msg); msg.Clear(); RecvFIFO(msg); int header = msg.ReadHeader(); if (header != BRISBANE_HUB_FIFO_TASK_ALL) { _error("header[0x%x]", header); } for (int i = 0; i < ndevs; i++) { ntasks[i] = msg.ReadULong(); _trace("dev[%d] ntasks[%lu]", i, ntasks[i]); } return BRISBANE_OK; } } /* namespace rt */ } /* namespace brisbane */
tduehr/jruby
core/src/main/java/org/jruby/ir/instructions/ReceiveClosureInstr.java
package org.jruby.ir.instructions; import org.jruby.ir.IRFlags; import org.jruby.ir.IRScope; import org.jruby.ir.IRVisitor; import org.jruby.ir.Operation; import org.jruby.ir.operands.Operand; import org.jruby.ir.operands.Variable; import org.jruby.ir.operands.WrappedIRClosure; import org.jruby.ir.transformations.inlining.InlinerInfo; /* Receive the closure argument (either implicit or explicit in Ruby source code) */ public class ReceiveClosureInstr extends Instr implements ResultInstr, FixedArityInstr { private Variable result; public ReceiveClosureInstr(Variable result) { super(Operation.RECV_CLOSURE); assert result != null: "ReceiveClosureInstr result is null"; this.result = result; } @Override public Operand[] getOperands() { return EMPTY_OPERANDS; } @Override public Variable getResult() { return result; } @Override public void updateResult(Variable v) { this.result = v; } @Override public boolean computeScopeFlags(IRScope scope) { scope.getFlags().add(IRFlags.RECEIVES_CLOSURE_ARG); return true; } @Override public Instr cloneForInlining(InlinerInfo ii) { switch (ii.getCloneMode()) { case ENSURE_BLOCK_CLONE: case NORMAL_CLONE: return new ReceiveClosureInstr(ii.getRenamedVariable(result)); case METHOD_INLINE: case CLOSURE_INLINE: // SSS FIXME: This is not strictly correct -- we have to wrap the block into an // operand type that converts the static code block to a proc which is a closure. if (ii.getCallClosure() instanceof WrappedIRClosure) return NopInstr.NOP; else return new CopyInstr(ii.getRenamedVariable(result), ii.getCallClosure()); default: // Should not get here return super.cloneForInlining(ii); } } @Override public void visit(IRVisitor visitor) { visitor.ReceiveClosureInstr(this); } }
sirfoga/pyhodl
docs/classpyhodl_1_1app_1_1_config_manager.js
var classpyhodl_1_1app_1_1_config_manager = [ [ "__init__", "classpyhodl_1_1app_1_1_config_manager.html#a04ddf6e5086e4ffa55941fe74235fdcd", null ], [ "create_config", "classpyhodl_1_1app_1_1_config_manager.html#a667736bb2b54ba26f5d110524e1b13c9", null ], [ "get", "classpyhodl_1_1app_1_1_config_manager.html#a354a62f627764b536388cfadfd6e25c2", null ], [ "save", "classpyhodl_1_1app_1_1_config_manager.html#ae995461dd7e37184e3d73ed6b02cb13c", null ], [ "config_file", "classpyhodl_1_1app_1_1_config_manager.html#a400f8de67d210ba9255eaba190a39602", null ], [ "data", "classpyhodl_1_1app_1_1_config_manager.html#a810deb5d2235764bdb63c11badd7b834", null ], [ "raw", "classpyhodl_1_1app_1_1_config_manager.html#a6620556c5c9247548e956251160146d1", null ] ];
duweiwang/java-playground
src/main/java/com/wangduwei/java_basic/string/MethodUsage.java
<reponame>duweiwang/java-playground package com.wangduwei.java_basic.string; /** * <p> * * @auther : wangduwei * @since : 2019/9/5 16:52 **/ public class MethodUsage { public static void main(String[] args) { MethodUsage.isWhite(); } public static void isWhite() { boolean a = Character.isWhitespace(Character.SPACE_SEPARATOR); boolean b = Character.isWhitespace(Character.LINE_SEPARATOR); boolean c = Character.isWhitespace(Character.PARAGRAPH_SEPARATOR); boolean d = Character.isWhitespace('\n');//换行 boolean e = Character.isWhitespace('\r');//回车 boolean f = Character.isWhitespace('\t');//tab boolean g = Character.isWhitespace(' '); boolean h = Character.isWhitespace('\f');//换页 out(" a = " + a); out(" b = " + b); out(" c = " + c); out(" d = " + d); out(" e = " + e); out(" f = " + f); out(" g = " + g); out(" h = " + h); } public static void out(String string) { System.out.println(string); } }
redhatanalytics/oshinko-cli
vendor/github.com/openshift/origin/pkg/auth/oauth/registry/registry_test.go
package registry import ( "errors" "net/http" "net/http/httptest" "testing" "time" "github.com/RangelReale/osin" "github.com/RangelReale/osincli" apierrs "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/clock" "k8s.io/apiserver/pkg/authentication/authenticator" "k8s.io/apiserver/pkg/authentication/user" clienttesting "k8s.io/client-go/testing" "github.com/openshift/origin/pkg/auth/api" "github.com/openshift/origin/pkg/auth/oauth/handlers" "github.com/openshift/origin/pkg/auth/userregistry/identitymapper" oapi "github.com/openshift/origin/pkg/oauth/apis/oauth" oauthfake "github.com/openshift/origin/pkg/oauth/generated/internalclientset/fake" oauthclient "github.com/openshift/origin/pkg/oauth/generated/internalclientset/typed/oauth/internalversion" "github.com/openshift/origin/pkg/oauth/server/osinserver" "github.com/openshift/origin/pkg/oauth/server/osinserver/registrystorage" userapi "github.com/openshift/origin/pkg/user/apis/user" usertest "github.com/openshift/origin/pkg/user/registry/test" ) type testHandlers struct { AuthorizeHandler osinserver.AuthorizeHandler User user.Info Authenticate bool Err error AuthNeed bool AuthErr error GrantNeed bool GrantErr error HandleAuthorizeReq *osin.AuthorizeRequest HandleAuthorizeResp *osin.Response HandleAuthorizeHandled bool HandleAuthorizeErr error AuthNeedHandled bool AuthNeedErr error GrantNeedGranted bool GrantNeedHandled bool GrantNeedErr error HandledErr error } func (h *testHandlers) HandleAuthorize(ar *osin.AuthorizeRequest, resp *osin.Response, w http.ResponseWriter) (handled bool, err error) { h.HandleAuthorizeReq = ar h.HandleAuthorizeResp = resp h.HandleAuthorizeHandled, h.HandleAuthorizeErr = h.AuthorizeHandler.HandleAuthorize(ar, resp, w) return h.HandleAuthorizeHandled, h.HandleAuthorizeErr } func (h *testHandlers) AuthenticationNeeded(client api.Client, w http.ResponseWriter, req *http.Request) (bool, error) { h.AuthNeed = true return h.AuthNeedHandled, h.AuthNeedErr } func (h *testHandlers) AuthenticationError(err error, w http.ResponseWriter, req *http.Request) (bool, error) { h.AuthErr = err return true, nil } func (h *testHandlers) AuthenticateRequest(req *http.Request) (user.Info, bool, error) { return h.User, h.Authenticate, h.Err } func (h *testHandlers) GrantNeeded(user user.Info, grant *api.Grant, w http.ResponseWriter, req *http.Request) (bool, bool, error) { h.GrantNeed = true return h.GrantNeedGranted, h.GrantNeedHandled, h.GrantNeedErr } func (h *testHandlers) GrantError(err error, w http.ResponseWriter, req *http.Request) (bool, error) { h.GrantErr = err return true, nil } func (h *testHandlers) HandleError(err error, w http.ResponseWriter, req *http.Request) { h.HandledErr = err } func TestRegistryAndServer(t *testing.T) { ch := make(chan *http.Request, 1) assertServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { ch <- req })) validClient := &oapi.OAuthClient{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Secret: "secret", RedirectURIs: []string{assertServer.URL + "/assert"}, } restrictedClient := &oapi.OAuthClient{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Secret: "secret", RedirectURIs: []string{assertServer.URL + "/assert"}, ScopeRestrictions: []oapi.ScopeRestriction{ {ExactValues: []string{"user:info"}}, }, } testCases := map[string]struct { Client *oapi.OAuthClient ClientAuth *oapi.OAuthClientAuthorization AuthSuccess bool AuthUser user.Info Scope string Check func(*testHandlers, *http.Request) }{ "needs auth": { Client: validClient, Check: func(h *testHandlers, _ *http.Request) { if !h.AuthNeed || h.GrantNeed || h.AuthErr != nil || h.GrantErr != nil || h.HandleAuthorizeReq.Authorized { t.Errorf("expected request to need authentication: %#v", h) } }, }, "needs grant": { Client: validClient, AuthSuccess: true, AuthUser: &user.DefaultInfo{ Name: "user", UID: "1", }, Check: func(h *testHandlers, _ *http.Request) { if h.AuthNeed || !h.GrantNeed || h.AuthErr != nil || h.GrantErr != nil || h.HandleAuthorizeReq.Authorized { t.Errorf("expected request to need to grant access: %#v", h) } }, }, "invalid scope": { Client: validClient, AuthSuccess: true, AuthUser: &user.DefaultInfo{ Name: "user", }, Scope: "some-scope", Check: func(h *testHandlers, _ *http.Request) { if h.AuthNeed || h.GrantNeed || h.AuthErr != nil || h.GrantErr != nil || h.HandleAuthorizeReq.Authorized || h.HandleAuthorizeResp.ErrorId != "invalid_scope" { t.Errorf("expected invalid_scope error: %#v, %#v, %#v", h, h.HandleAuthorizeReq, h.HandleAuthorizeResp) } }, }, "disallowed scope": { Client: restrictedClient, AuthSuccess: true, AuthUser: &user.DefaultInfo{ Name: "user", }, Scope: "user:full", Check: func(h *testHandlers, _ *http.Request) { if h.AuthNeed || h.GrantNeed || h.AuthErr != nil || h.GrantErr != nil || h.HandleAuthorizeReq.Authorized || h.HandleAuthorizeResp.ErrorId != "access_denied" { t.Errorf("expected access_denied error: %#v, %#v, %#v", h, h.HandleAuthorizeReq, h.HandleAuthorizeResp) } }, }, "has non covered grant": { Client: validClient, AuthSuccess: true, AuthUser: &user.DefaultInfo{ Name: "user", UID: "1", }, ClientAuth: &oapi.OAuthClientAuthorization{ ObjectMeta: metav1.ObjectMeta{Name: "user:test"}, UserName: "user", UserUID: "1", ClientName: "test", Scopes: []string{"user:info"}, }, Scope: "user:info user:check-access", Check: func(h *testHandlers, req *http.Request) { if h.AuthNeed || !h.GrantNeed || h.AuthErr != nil || h.GrantErr != nil || h.HandleAuthorizeReq.Authorized { t.Errorf("expected request to need to grant access because of uncovered scopes: %#v", h) } }, }, "has covered grant": { Client: validClient, AuthSuccess: true, AuthUser: &user.DefaultInfo{ Name: "user", UID: "1", }, ClientAuth: &oapi.OAuthClientAuthorization{ ObjectMeta: metav1.ObjectMeta{Name: "user:test"}, UserName: "user", UserUID: "1", ClientName: "test", Scopes: []string{"user:info", "user:check-access"}, }, Scope: "user:info user:check-access", Check: func(h *testHandlers, req *http.Request) { if h.AuthNeed || h.GrantNeed || h.AuthErr != nil || h.GrantErr != nil || !h.HandleAuthorizeReq.Authorized || h.HandleAuthorizeResp.ErrorId != "" { t.Errorf("unexpected flow: %#v, %#v, %#v", h, h.HandleAuthorizeReq, h.HandleAuthorizeResp) } }, }, "has auth and grant": { Client: validClient, AuthSuccess: true, AuthUser: &user.DefaultInfo{ Name: "user", UID: "1", }, ClientAuth: &oapi.OAuthClientAuthorization{ ObjectMeta: metav1.ObjectMeta{Name: "user:test"}, UserName: "user", UserUID: "1", ClientName: "test", Scopes: []string{"user:full"}, }, Check: func(h *testHandlers, req *http.Request) { if h.AuthNeed || h.GrantNeed || h.AuthErr != nil || h.GrantErr != nil || !h.HandleAuthorizeReq.Authorized || h.HandleAuthorizeResp.ErrorId != "" { t.Errorf("unexpected flow: %#v, %#v, %#v", h, h.HandleAuthorizeReq, h.HandleAuthorizeResp) return } if req == nil { t.Errorf("unexpected nil assertion request") return } if code := req.URL.Query().Get("code"); code == "" { t.Errorf("expected query param 'code', got: %#v", req) } }, }, "has auth with no UID, mimics impersonation": { Client: validClient, AuthSuccess: true, AuthUser: &user.DefaultInfo{ Name: "user", }, ClientAuth: &oapi.OAuthClientAuthorization{ ObjectMeta: metav1.ObjectMeta{Name: "user:test"}, UserName: "user", UserUID: "2", ClientName: "test", Scopes: []string{"user:full"}, }, Check: func(h *testHandlers, r *http.Request) { if h.AuthNeed || h.GrantNeed || h.AuthErr != nil || h.GrantErr != nil || h.HandleAuthorizeReq.Authorized || h.HandleAuthorizeResp.ErrorId != "server_error" { t.Errorf("expected server_error error: %#v, %#v, %#v", h, h.HandleAuthorizeReq, h.HandleAuthorizeResp) } }, }, "has auth and grant with different UIDs": { Client: validClient, AuthSuccess: true, AuthUser: &user.DefaultInfo{ Name: "user", UID: "1", }, ClientAuth: &oapi.OAuthClientAuthorization{ ObjectMeta: metav1.ObjectMeta{Name: "user:test"}, UserName: "user", UserUID: "2", ClientName: "test", Scopes: []string{"user:full"}, }, Check: func(h *testHandlers, _ *http.Request) { if h.AuthNeed || !h.GrantNeed || h.AuthErr != nil || h.GrantErr != nil || h.HandleAuthorizeReq.Authorized { t.Errorf("expected request to need to grant access due to UID mismatch: %#v", h) } }, }, } for _, testCase := range testCases { h := &testHandlers{} h.Authenticate = testCase.AuthSuccess h.User = testCase.AuthUser objs := []runtime.Object{} if testCase.Client != nil { objs = append(objs, testCase.Client) } if testCase.ClientAuth != nil { objs = append(objs, testCase.ClientAuth) } fakeOAuthClient := oauthfake.NewSimpleClientset(objs...) storage := registrystorage.New(fakeOAuthClient.Oauth().OAuthAccessTokens(), fakeOAuthClient.Oauth().OAuthAuthorizeTokens(), fakeOAuthClient.Oauth().OAuthClients(), NewUserConversion(), 0) config := osinserver.NewDefaultServerConfig() h.AuthorizeHandler = osinserver.AuthorizeHandlers{ handlers.NewAuthorizeAuthenticator( h, h, h, ), handlers.NewGrantCheck( NewClientAuthorizationGrantChecker(fakeOAuthClient.Oauth().OAuthClientAuthorizations()), h, h, ), } server := osinserver.New( config, storage, h, osinserver.AccessHandlers{ handlers.NewDenyAccessAuthenticator(), }, h, ) mux := http.NewServeMux() server.Install(mux, "") s := httptest.NewServer(mux) oaclientConfig := &osincli.ClientConfig{ ClientId: "test", ClientSecret: "secret", RedirectUrl: assertServer.URL + "/assert", AuthorizeUrl: s.URL + "/authorize", TokenUrl: s.URL + "/token", Scope: testCase.Scope, } oaclient, err := osincli.NewClient(oaclientConfig) if err != nil { t.Fatalf("unexpected error: %v", err) } aReq := oaclient.NewAuthorizeRequest(osincli.CODE) if _, err := http.Get(aReq.GetAuthorizeUrl().String()); err != nil { t.Fatalf("unexpected error: %v", err) } var req *http.Request select { case out := <-ch: req = out default: } testCase.Check(h, req) } } func TestAuthenticateTokenNotFound(t *testing.T) { fakeOAuthClient := oauthfake.NewSimpleClientset() userRegistry := usertest.NewUserRegistry() tokenAuthenticator := NewTokenAuthenticator(fakeOAuthClient.Oauth().OAuthAccessTokens(), userRegistry, identitymapper.NoopGroupMapper{}) userInfo, found, err := tokenAuthenticator.AuthenticateToken("token") if found { t.Error("Found token, but it should be missing!") } if err == nil { t.Error("Expected not found error") } if !apierrs.IsNotFound(err) { t.Error("Expected not found error") } if userInfo != nil { t.Errorf("Unexpected user: %v", userInfo) } } func TestAuthenticateTokenOtherGetError(t *testing.T) { fakeOAuthClient := oauthfake.NewSimpleClientset() fakeOAuthClient.PrependReactor("get", "oauthaccesstokens", func(action clienttesting.Action) (handled bool, ret runtime.Object, err error) { return true, nil, errors.New("get error") }) userRegistry := usertest.NewUserRegistry() tokenAuthenticator := NewTokenAuthenticator(fakeOAuthClient.Oauth().OAuthAccessTokens(), userRegistry, identitymapper.NoopGroupMapper{}) userInfo, found, err := tokenAuthenticator.AuthenticateToken("token") if found { t.Error("Found token, but it should be missing!") } if err == nil { t.Error("Expected error is missing!") } if err.Error() != "get error" { t.Errorf("Expected error %v, but got error %v", "get error", err) } if userInfo != nil { t.Errorf("Unexpected user: %v", userInfo) } } func TestAuthenticateTokenExpired(t *testing.T) { fakeOAuthClient := oauthfake.NewSimpleClientset( // expired token that had a lifetime of 10 minutes &oapi.OAuthAccessToken{ ObjectMeta: metav1.ObjectMeta{Name: "token1", CreationTimestamp: metav1.Time{Time: time.Now().Add(-1 * time.Hour)}}, ExpiresIn: 600, UserName: "foo", }, // non-expired token that has a lifetime of 10 minutes, but has a non-nil deletion timestamp &oapi.OAuthAccessToken{ ObjectMeta: metav1.ObjectMeta{Name: "token2", CreationTimestamp: metav1.Time{Time: time.Now()}, DeletionTimestamp: &metav1.Time{}}, ExpiresIn: 600, UserName: "foo", }, ) userRegistry := usertest.NewUserRegistry() userRegistry.GetUsers["foo"] = &userapi.User{ObjectMeta: metav1.ObjectMeta{UID: "bar"}} tokenAuthenticator := NewTokenAuthenticator(fakeOAuthClient.Oauth().OAuthAccessTokens(), userRegistry, identitymapper.NoopGroupMapper{}, NewExpirationValidator()) for _, tokenName := range []string{"token1", "token2"} { userInfo, found, err := tokenAuthenticator.AuthenticateToken(tokenName) if found { t.Error("Found token, but it should be missing!") } if err != errExpired { t.Errorf("Unexpected error: %v", err) } if userInfo != nil { t.Errorf("Unexpected user: %v", userInfo) } } } func TestAuthenticateTokenInvalidUID(t *testing.T) { fakeOAuthClient := oauthfake.NewSimpleClientset( &oapi.OAuthAccessToken{ ObjectMeta: metav1.ObjectMeta{Name: "token", CreationTimestamp: metav1.Time{Time: time.Now()}}, ExpiresIn: 600, // 10 minutes UserName: "foo", UserUID: string("bar1"), }, ) userRegistry := usertest.NewUserRegistry() userRegistry.GetUsers["foo"] = &userapi.User{ObjectMeta: metav1.ObjectMeta{UID: "bar2"}} tokenAuthenticator := NewTokenAuthenticator(fakeOAuthClient.Oauth().OAuthAccessTokens(), userRegistry, identitymapper.NoopGroupMapper{}, NewUIDValidator()) userInfo, found, err := tokenAuthenticator.AuthenticateToken("token") if found { t.Error("Found token, but it should be missing!") } if err.Error() != "user.UID (bar2) does not match token.userUID (bar1)" { t.Errorf("Unexpected error: %v", err) } if userInfo != nil { t.Errorf("Unexpected user: %v", userInfo) } } func TestAuthenticateTokenValidated(t *testing.T) { fakeOAuthClient := oauthfake.NewSimpleClientset( &oapi.OAuthAccessToken{ ObjectMeta: metav1.ObjectMeta{Name: "token", CreationTimestamp: metav1.Time{Time: time.Now()}}, ExpiresIn: 600, // 10 minutes UserName: "foo", UserUID: string("bar"), }, ) userRegistry := usertest.NewUserRegistry() userRegistry.GetUsers["foo"] = &userapi.User{ObjectMeta: metav1.ObjectMeta{UID: "bar"}} tokenAuthenticator := NewTokenAuthenticator(fakeOAuthClient.Oauth().OAuthAccessTokens(), userRegistry, identitymapper.NoopGroupMapper{}, NewExpirationValidator(), NewUIDValidator()) userInfo, found, err := tokenAuthenticator.AuthenticateToken("token") if !found { t.Error("Did not find a token!") } if err != nil { t.Errorf("Unexpected error: %v", err) } if userInfo == nil { t.Error("Did not get a user!") } } type fakeOAuthClientLister struct { clients oauthclient.OAuthClientInterface } func (f fakeOAuthClientLister) Get(name string) (*oapi.OAuthClient, error) { return f.clients.Get(name, metav1.GetOptions{}) } func (f fakeOAuthClientLister) List(selector labels.Selector) ([]*oapi.OAuthClient, error) { panic("not used") } type fakeTicker struct { clock *clock.FakeClock ch <-chan time.Time } func (t *fakeTicker) Now() time.Time { return t.clock.Now() } func (t *fakeTicker) C() <-chan time.Time { return t.ch } func (t *fakeTicker) Stop() {} func (t *fakeTicker) NewTicker(d time.Duration) { t.ch = t.clock.Tick(d) } func (t *fakeTicker) Sleep(d time.Duration) { t.clock.Sleep(d) } func checkToken(t *testing.T, name string, authf authenticator.Token, tokens oauthclient.OAuthAccessTokenInterface, current *fakeTicker, present bool) { t.Helper() userInfo, found, err := authf.AuthenticateToken(name) if present { if !found { t.Errorf("Did not find token %s!", name) } if err != nil { t.Errorf("Unexpected error checking for token %s: %v", name, err) } if userInfo == nil { t.Errorf("Did not get a user for token %s!", name) } } else { if found { token, tokenErr := tokens.Get(name, metav1.GetOptions{}) if tokenErr != nil { t.Fatal(tokenErr) } t.Errorf("Found token (created=%s, timeout=%di, now=%s), but it should be gone!", token.CreationTimestamp, token.InactivityTimeoutSeconds, current.Now()) } if err != errTimedout { t.Errorf("Unexpected error checking absence of token %s: %v", name, err) } if userInfo != nil { t.Errorf("Unexpected user checking absence of token %s: %v", name, userInfo) } } } func wait(t *testing.T, c chan struct{}) { t.Helper() select { case <-c: case <-time.After(30 * time.Second): t.Fatal("failed to see channel event") } } func TestAuthenticateTokenTimeout(t *testing.T) { stopCh := make(chan struct{}) defer close(stopCh) testClock := &fakeTicker{clock: clock.NewFakeClock(time.Time{})} defaultTimeout := int32(30) // 30 seconds clientTimeout := int32(15) // 15 seconds minTimeout := int32(10) // 10 seconds -> 10/3 = a tick per 3 seconds testClient := oapi.OAuthClient{ ObjectMeta: metav1.ObjectMeta{Name: "testClient"}, AccessTokenInactivityTimeoutSeconds: &clientTimeout, } quickClient := oapi.OAuthClient{ ObjectMeta: metav1.ObjectMeta{Name: "quickClient"}, AccessTokenInactivityTimeoutSeconds: &minTimeout, } slowClient := oapi.OAuthClient{ ObjectMeta: metav1.ObjectMeta{Name: "slowClient"}, } testToken := oapi.OAuthAccessToken{ ObjectMeta: metav1.ObjectMeta{Name: "testToken", CreationTimestamp: metav1.Time{Time: testClock.Now()}}, ClientName: "testClient", ExpiresIn: 600, // 10 minutes UserName: "foo", UserUID: string("bar"), InactivityTimeoutSeconds: clientTimeout, } quickToken := oapi.OAuthAccessToken{ ObjectMeta: metav1.ObjectMeta{Name: "quickToken", CreationTimestamp: metav1.Time{Time: testClock.Now()}}, ClientName: "quickClient", ExpiresIn: 600, // 10 minutes UserName: "foo", UserUID: string("bar"), InactivityTimeoutSeconds: minTimeout, } slowToken := oapi.OAuthAccessToken{ ObjectMeta: metav1.ObjectMeta{Name: "slowToken", CreationTimestamp: metav1.Time{Time: testClock.Now()}}, ClientName: "slowClient", ExpiresIn: 600, // 10 minutes UserName: "foo", UserUID: string("bar"), InactivityTimeoutSeconds: defaultTimeout, } emergToken := oapi.OAuthAccessToken{ ObjectMeta: metav1.ObjectMeta{Name: "emergToken", CreationTimestamp: metav1.Time{Time: testClock.Now()}}, ClientName: "quickClient", ExpiresIn: 600, // 10 minutes UserName: "foo", UserUID: string("bar"), InactivityTimeoutSeconds: 5, // super short timeout } fakeOAuthClient := oauthfake.NewSimpleClientset(&testToken, &quickToken, &slowToken, &emergToken, &testClient, &quickClient, &slowClient) userRegistry := usertest.NewUserRegistry() userRegistry.GetUsers["foo"] = &userapi.User{ObjectMeta: metav1.ObjectMeta{UID: "bar"}} accessTokenGetter := fakeOAuthClient.Oauth().OAuthAccessTokens() oauthClients := fakeOAuthClient.Oauth().OAuthClients() lister := &fakeOAuthClientLister{ clients: oauthClients, } timeouts := NewTimeoutValidator(accessTokenGetter, lister, defaultTimeout, minTimeout) // inject fake clock, which has some interesting properties // 1. A sleep will cause at most one ticker event, regardless of how long the sleep was // 2. The clock will hold one tick event and will drop the next one if something does not consume it first timeouts.ticker = testClock // decorate flush // The fake clock 1. and 2. require that we issue a wait(t, timeoutsSync) after each testClock.Sleep that causes a tick originalFlush := timeouts.flushHandler timeoutsSync := make(chan struct{}) timeouts.flushHandler = func(flushHorizon time.Time) { originalFlush(flushHorizon) timeoutsSync <- struct{}{} // signal that flush is complete so we never race against it } // decorate putToken // We must issue a wait(t, putTokenSync) after each call to checkToken that should be successful originalPutToken := timeouts.putTokenHandler putTokenSync := make(chan struct{}) timeouts.putTokenHandler = func(td *tokenData) { originalPutToken(td) putTokenSync <- struct{}{} // signal that putToken is complete so we never race against it } // add some padding to all sleep invocations to make sure we are not failing on any boundary values buffer := time.Nanosecond tokenAuthenticator := NewTokenAuthenticator(accessTokenGetter, userRegistry, identitymapper.NoopGroupMapper{}, timeouts) go timeouts.Run(stopCh) // TIME: 0 seconds have passed here // first time should succeed for all checkToken(t, "testToken", tokenAuthenticator, accessTokenGetter, testClock, true) wait(t, putTokenSync) checkToken(t, "quickToken", tokenAuthenticator, accessTokenGetter, testClock, true) wait(t, putTokenSync) wait(t, timeoutsSync) // from emergency flush because quickToken has a short enough timeout checkToken(t, "slowToken", tokenAuthenticator, accessTokenGetter, testClock, true) wait(t, putTokenSync) // this should cause an emergency flush, if not the next auth will fail, // as the token will be timed out checkToken(t, "emergToken", tokenAuthenticator, accessTokenGetter, testClock, true) wait(t, putTokenSync) wait(t, timeoutsSync) // from emergency flush because emergToken has a super short timeout // wait 6 seconds testClock.Sleep(5*time.Second + buffer) // a tick happens every 3 seconds wait(t, timeoutsSync) // TIME: 6th second // See if emergency flush happened checkToken(t, "emergToken", tokenAuthenticator, accessTokenGetter, testClock, true) wait(t, putTokenSync) wait(t, timeoutsSync) // from emergency flush because emergToken has a super short timeout // wait for timeout (minTimeout + 1 - the previously waited 6 seconds) testClock.Sleep(time.Duration(minTimeout-5)*time.Second + buffer) wait(t, timeoutsSync) // TIME: 11th second // now we change the testClient and see if the testToken will still be // valid instead of timing out changeClient, ret := oauthClients.Get("testClient", metav1.GetOptions{}) if ret != nil { t.Error("Failed to get testClient") } else { longTimeout := int32(20) changeClient.AccessTokenInactivityTimeoutSeconds = &longTimeout _, ret = oauthClients.Update(changeClient) if ret != nil { t.Error("Failed to update testClient") } } // this should fail, thus no call to wait(t, putTokenSync) checkToken(t, "quickToken", tokenAuthenticator, accessTokenGetter, testClock, false) // while this should get updated checkToken(t, "testToken", tokenAuthenticator, accessTokenGetter, testClock, true) wait(t, putTokenSync) wait(t, timeoutsSync) // wait for timeout testClock.Sleep(time.Duration(clientTimeout+1)*time.Second + buffer) // 16 seconds equals 5 more flushes, but the fake clock will only tick once during this time wait(t, timeoutsSync) // TIME: 27th second // this should get updated checkToken(t, "slowToken", tokenAuthenticator, accessTokenGetter, testClock, true) wait(t, putTokenSync) wait(t, timeoutsSync) // while this should not fail checkToken(t, "testToken", tokenAuthenticator, accessTokenGetter, testClock, true) wait(t, putTokenSync) wait(t, timeoutsSync) // and should be updated to last at least till the 31st second token, err := accessTokenGetter.Get("testToken", metav1.GetOptions{}) if err != nil { t.Error("Failed to get testToken") } else { if token.InactivityTimeoutSeconds < 31 { t.Errorf("Expected timeout in more than 31 seconds, found: %d", token.InactivityTimeoutSeconds) } } //now change testClient again, so that tokens do not expire anymore changeclient, ret := oauthClients.Get("testClient", metav1.GetOptions{}) if ret != nil { t.Error("Failed to get testClient") } else { changeclient.AccessTokenInactivityTimeoutSeconds = new(int32) _, ret = oauthClients.Update(changeclient) if ret != nil { t.Error("Failed to update testClient") } } // and wait until test token should time out, and has been flushed for sure testClock.Sleep(time.Duration(minTimeout)*time.Second + buffer) wait(t, timeoutsSync) // while this should not fail checkToken(t, "testToken", tokenAuthenticator, accessTokenGetter, testClock, true) wait(t, putTokenSync) wait(t, timeoutsSync) // and should be updated to have a ZERO timeout token, err = accessTokenGetter.Get("testToken", metav1.GetOptions{}) if err != nil { t.Error("Failed to get testToken") } else { if token.InactivityTimeoutSeconds != 0 { t.Errorf("Expected timeout of 0 seconds, found: %d", token.InactivityTimeoutSeconds) } } }
moiify/llofo
src/driver/client.c
#include <stdio.h> #include <string.h> #include "log.h" #include "client.h" #include "msg.h" #include "data.h" #include "setting.h" static int g_msgUdpProcsNum = 0; static MC_MSG_PROC *g_msgUdpProcs = NULL; int client_udp_proc(const void *m, int msgLen) { int i = 0; const MSG_HEADER *msg = (const MSG_HEADER *)m; LOG_HEX(m, msgLen); if(msgLen < MSG_HEADER_LEN) { LOG_ERROR("message length not enough: %zu(at least(%zu)", msgLen, sizeof(MSG_HEADER)); return -1; } if(_ntohs(msg->signature) != START_FLAG_UDP) { LOG_ERROR("receive message header signature error:%#x", (unsigned)_ntohs(msg->signature)); return -1; } for(i = 0; i < g_msgUdpProcsNum; i++) { if(g_msgUdpProcs[i].cmd == msg->cmd) { MSG_PROC pfn = g_msgUdpProcs[i].pfn; if(pfn) { return pfn(msg); } else { LOG_ERROR("Message %d not processed!", msg->cmd); return -1; } } } return -1; } static int g_msgProcsNum = 0; static MC_MSG_PROC *g_msgProcs = NULL; int client_handleOnePkt(const void *m, int msgLen) { MSG_HEADER *msg = (MSG_HEADER *)m; size_t i = 0; for(i = 0; i < g_msgProcsNum; i++) { if(g_msgProcs[i].cmd == msg->cmd) { MSG_PROC pfn = g_msgProcs[i].pfn; if(pfn) { return pfn(msg); } else { LOG_ERROR("Message %d not processed!", msg->cmd); return -1; } } } LOG_ERROR("unknown message %d!", msg->cmd); return -1; } static CLIENT_PROC client_procEXT = NULL; int client_proc(const void *m, int msgLen) { s16 leftLen = 0; const MSG_HEADER *msg = (const MSG_HEADER *)m; if(client_procEXT) { return client_procEXT(m, msgLen); } LOG_HEX(m, msgLen); if(msgLen < MSG_HEADER_LEN) { LOG_ERROR("message length not enough: %zu(at least(%zu)", msgLen, sizeof(MSG_HEADER)); return -1; } leftLen = msgLen; while(leftLen >= _ntohs(msg->length) + MSG_HEADER_LEN) { if (_ntohs(msg->signature) != START_FLAG) { LOG_ERROR("receive message header signature error:%#x", (unsigned)_ntohs(msg->signature)); return -1; } client_handleOnePkt(msg, _ntohs(msg->length) + MSG_HEADER_LEN); leftLen = leftLen - MSG_HEADER_LEN - _ntohs(msg->length); msg = (const MSG_HEADER *)((const char *)m + msgLen - leftLen); } return 0; } void client_initailEXT(CLIENT_PROC procHandler) { client_procEXT = procHandler; } void client_initail(void *responseArray, int responseArraySize) { g_msgProcs = responseArray; g_msgProcsNum = responseArraySize; } void client_initailUDP(void *responseArray, int responseArraySize) { g_msgUdpProcs = responseArray; g_msgUdpProcsNum = responseArraySize; }
PMSMcqut/pyleecan-of-manatee
Tests/Plot/LamHole/test_Hole_54_plot.py
# -*- coding: utf-8 -*- """ @date Created on Wed Jan 13 17:45:15 2016 @copyright (C) 2015-2016 EOMYS ENGINEERING. @author pierre_b """ from os.path import join from unittest import TestCase import matplotlib.pyplot as plt from numpy import pi from pyleecan.Classes.Frame import Frame from pyleecan.Classes.LamHole import LamHole from pyleecan.Classes.Lamination import Lamination from pyleecan.Classes.Machine import Machine from pyleecan.Classes.Magnet import Magnet from pyleecan.Classes.Shaft import Shaft from pyleecan.Classes.MatLamination import MatLamination from pyleecan.Classes.HoleM54 import HoleM54 from pyleecan.Tests.Plot import save_path class test_Hole_54_plot(TestCase): """unittest for Lamination with Hole plot""" def test_Lam_Hole_54_plot(self): """Test machine plot hole 54""" plt.close("all") test_obj = Machine() test_obj.rotor = LamHole( is_internal=True, Rint=0.1, Rext=0.2, is_stator=False, L1=0.7 ) test_obj.rotor.hole = list() test_obj.rotor.hole.append( HoleM54(Zh=8, W0=pi / 4, H0=50e-3, H1=10e-3, R1=100e-3) ) test_obj.rotor.hole.append( HoleM54(Zh=8, W0=pi / 6, H0=25e-3, H1=10e-3, R1=100e-3) ) test_obj.rotor.plot() fig = plt.gcf() fig.savefig(join(save_path, "test_Lam_Hole_s54-Rotor.png")) self.assertEqual(len(fig.axes[0].patches), 18) test_obj.rotor.hole[0].plot() fig = plt.gcf() fig.savefig(join(save_path, "test_Lam_Hole_s54-Rotor hole.png")) self.assertEqual(len(fig.axes[0].patches), 1)
oirad21/react_oirad
node_modules/@fortawesome/pro-solid-svg-icons/faDagger.js
<reponame>oirad21/react_oirad<gh_stars>0 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'fas'; var iconName = 'dagger'; var width = 384; var height = 512; var ligatures = []; var unicode = 'f6cb'; var svgPathData = 'M336 128H224V16c0-8.84-7.16-16-16-16h-32c-8.84 0-16 7.16-16 16v112H48c-26.51 0-48 21.49-48 48s21.49 48 48 48c20.87 0 38.45-13.4 45.06-32h197.88c6.61 18.6 24.19 32 45.06 32 26.51 0 48-21.49 48-48s-21.49-48-48-48zM128 428.84l50.69 76.03c6.33 9.5 20.29 9.5 26.63 0L256 428.84V224H128v204.84z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.faDagger = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;
larsvansoest/commix
tests/test_transweight_transformations.py
<reponame>larsvansoest/commix<gh_stars>1-10 import tensorflow as tf import numpy as np from models import TransWeightTransformations from tests import TestBase class TransWeightTransformationsTest(TestBase): """ This class tests the functionality of the TransWeightTransformations model. This test suite can be ran with: python -m unittest -q tests.TransWeightTransformationsTest """ def setUp(self): super(TransWeightTransformationsTest, self).setUp() self._comp_model = TransWeightTransformations(embedding_size=2, nonlinearity=tf.identity, dropout_rate=0.0, transforms=2) def test_weight(self): """ Test that the weighting is correctly performed If [[A B C] are two transformed representations and [j k] is the transformations weighting vector of [D E F]] dimension [1 x t] than the elements of the composed representation [p_0 p_1 p_2] are obtained as: p_0 = A*j + D*k p_1 = B*j + E*k p_2 = C*j + F*k """ t = np.array([[[2, 1, 0], [0, 0, 1]]], dtype='float32') W = np.array([[2], [3]], dtype='float32') b = np.full(shape=(3,), fill_value=0.0, dtype='float32') expected_p = np.array([[4, 2, 3]]) with tf.Session() as sess: p = sess.run( self.comp_model.weight( reg_uv=t, W=W, b=b)) np.testing.assert_allclose(p, expected_p) def test_composition(self): pass
jxchin/openspecimen
WEB-INF/src/com/krishagni/catissueplus/core/common/repository/impl/StarredItemDaoImpl.java
<reponame>jxchin/openspecimen package com.krishagni.catissueplus.core.common.repository.impl; import org.hibernate.criterion.Restrictions; import com.krishagni.catissueplus.core.common.domain.StarredItem; import com.krishagni.catissueplus.core.common.repository.AbstractDao; import com.krishagni.catissueplus.core.common.repository.StarredItemDao; public class StarredItemDaoImpl extends AbstractDao<StarredItem> implements StarredItemDao { @Override public Class<StarredItem> getType() { return StarredItem.class; } @Override public StarredItem getItem(String itemType, Long itemId, Long userId) { return (StarredItem) getCurrentSession().createCriteria(StarredItem.class, "si") .createAlias("si.user", "user") .add(Restrictions.eq("si.itemType", itemType)) .add(Restrictions.eq("si.itemId", itemId)) .add(Restrictions.eq("user.id", userId)) .uniqueResult(); } }
kristianmeyerr/AMICI
tests/generateTestConfig/example_events.py
#!/usr/bin/env python3 import sys import numpy as np from example import AmiciExample class ExampleEvents(AmiciExample): def __init__(self): AmiciExample.__init__( self ) self.numZ = 2 self.numX = 3 self.numP = 4 self.numK = 4 self.modelOptions['theta'] = np.log10([0.5, 2, 0.5, 0.5]) self.modelOptions['kappa'] = [4.0, 8.0, 10.0, 4.0] self.modelOptions['ts'] = np.linspace(0.0, 10.0, 20) self.modelOptions['pscale'] = 2 self.solverOptions['atol'] = 1e-16 self.solverOptions['maxsteps'] = 1e4 self.solverOptions['nmaxevent'] = 2 self.solverOptions['rtol'] = 1e-8 self.solverOptions['sens_ind'] = [] self.solverOptions['sensi'] = 0 self.solverOptions['sensi_meth'] = 1 self.data['Y'] = np.full((len(self.modelOptions['ts']), 1), np.nan) self.data['Sigma_Y'] = np.full((len(self.modelOptions['ts']), 1), np.nan) self.data['Z'] = np.full((self.solverOptions['nmaxevent'], self.numZ ), np.nan) self.data['Sigma_Z'] = np.full((self.solverOptions['nmaxevent'], self.numZ ), np.nan) self.data['condition'] = self.modelOptions['kappa'] self.data['t'] = self.modelOptions['ts'] def writeNoSensi(filename): ex = ExampleEvents() ex.writeToFile(filename, '/model_events/nosensi/') def writeSensiForward(filename): ex = ExampleEvents() ex.solverOptions['sens_ind'] = np.arange(0, ex.numP) ex.solverOptions['sensi'] = 1 ex.solverOptions['sensi_meth'] = 1 ex.writeToFile(filename, '/model_events/sensiforward/') def main(): if len(sys.argv) < 2: print("Error: Must provide output file as first and only argument.") sys.exit(1) filename = sys.argv[1] writeNoSensi(filename) writeSensiForward(filename) if __name__ == "__main__": main()
bboyxiaosong/wx_xd
mychaj/utils/util.js
var MD5 = require('./md5.js') function alert(msg, callbak) { wx.showModal({ title: '提示', content: msg, showCancel: false, confirmText: '好的', success: function (res) { if (callbak) { callbak() } } }) } function showToast(msg) { wx.showToast({ title: msg, icon: 'none', duration: 2000 }) } function loading(msg) { var title = msg ? msg : '加载中' wx.showLoading({ title: title, }) } //数据转化 function formatNumber(n) { n = n.toString() return n[1] ? n : '0' + n } function formatTime(date) { var year = date.getFullYear() var month = date.getMonth() + 1 var day = date.getDate() return [year, month, day].map(formatNumber).join('-') } //时间戳变为月-日,时间 function time(stamp) { var format; var currDate = new Date(); currDate.setHours(0); currDate.setMinutes(0); currDate.setSeconds(0); var currStamp = currDate.getTime(); var formatDate = new Date(); formatDate.setTime(stamp); if (stamp > currStamp) { var getMinutes = formatDate.getMinutes() if (getMinutes < 10) { getMinutes = '0' + getMinutes; } format = formatDate.getHours() + ":" + getMinutes; } else { var month = formatDate.getMonth() + 1; if (month < 10) { month = '0' + month; } var date = formatDate.getDate() if (date < 10) { date = '0' + date; } format = month + "-" + date; } return format; } //时间戳变为年月日 function getLocalTime(stamp, type) { var format; var formatDate = new Date(); formatDate.setTime(stamp); var month = formatDate.getMonth() + 1; var date = formatDate.getDate(); if (type) { if (type == 1) {//形式2018.3.21 if (month < 10) { month = '0' + month; } if (date < 10) { date = '0' + date; } format = formatDate.getFullYear() + "." + month + "." + date; } else if (type == 2) {//形式3月21日 format = month + "月" + date + "日"; } } else {//形式2018年3月21日 format = formatDate.getFullYear() + "年" + month + "月" + date + "日"; } return format; } function checkMobile(sMobile) { if (!(/^1[0-9][0-9]\d{8}$/.test(sMobile))) { return false; } return true; } /** * 随机字符串 */ function randomFileName(str) { var timestamp = Date.parse(new Date()); var len = 10; var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; var maxPos = $chars.length; var pwd = ''; for (var i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); } return MD5.hexMD5(str + pwd); } function checkLogin(callbak) { if (null == getApp().globalData.user) { wx.navigateTo({ url: '/pages/main/login/index', fail: function () { getApp().globalData.isClicked = false } }) } else if (callbak) { callbak() } } function checkAuth(app, callbak) { if (null == app.globalData.wxUser) { wx.getSetting({ success(res) { if (!res.authSetting['scope.userInfo']) { wx.showModal({ title: '警告', content: '您已经拒绝微信授权,请勾选开启用户信息,以进行其他操作。', // showCancel: false, success: function (res) { if (res.confirm) { wx.openSetting({ success: (res) => { // console.log('openSetting', res) if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录 wx.getUserInfo({ success: function (res) { app.setWxUserInfo(res.userInfo) // console.log('拉取用户信息', res) if (callbak) { callbak() } } }) } } }) } } }) } else { if (callbak) { callbak() } } } }) } else { if (callbak) { callbak() } } } function getLocation(app, callbak) { wx.getLocation({ type: 'wgs84', success: function (res) { app.globalData.lon = res.longitude; app.globalData.lat = res.latitude; app.globalData.locationAuth = true if (callbak) { callbak(); } }, fail: function () { app.globalData.locationAuth = true app.globalData.lon = ''; app.globalData.lat = ''; if (callbak) { callbak(); } } }) } // var numberArray = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'] var numberArray = ['零', '一', '两', '三', '四', '五', '六', '七', '八', '九'] function numberFormater(index) { return numberArray[index] } // 转换时分 的时间 function formatMinute(date) { var year = date.getFullYear() var month = date.getMonth() + 1 var day = date.getDate() var hour = date.getHours() var minute = date.getMinutes() var second = date.getSeconds() return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':') } function formatNumber(n) { n = n.toString() return n[1] ? n : '0' + n } function formatStartTime(date) { var year = date.getFullYear() var month = date.getMonth() + 1 var day = date.getDate() var date = year + '-' + month + '-' + day return date } function formatEndTime(date) { var year = date.getFullYear()+2 var month = date.getMonth() + 1 var day = date.getDate() var date = year + '-' + month + '-' + day return date } function generateContent(ageLabel, gender) { var ageStr = '' var genderStr = '' if (ageLabel == 1) { ageStr = '80前' if (gender == 1) { genderStr = "叔叔" } else if (gender == 2) { genderStr = "阿姨"; } } else if (ageLabel == 2) { ageStr = '80后' if (gender == 1) { genderStr = "小叔叔" } else if (gender == 2) { genderStr = "大姐姐" } } else if (ageLabel == 3) { ageStr = '85后' if (gender == 1) { genderStr = "大哥哥" } else if (gender == 2) { genderStr = "小姐姐" } } else if (ageLabel == 4) { ageStr = '90后' if (gender == 1) { genderStr = "小哥哥" } else if (gender == 2) { genderStr = "小姑娘" } } else if (ageLabel == 5) { ageStr = '95后' if (gender == 1) { genderStr = "小弟弟" } else if (gender == 2) { genderStr = "小妹妹" } } return ageStr + genderStr } //随机简介 var profileArray = ['等你发现时间是贼了,它早已偷光你的选择。', '便宜的不一定真便宜,不要为了省钱买16G的手机。', '努力是有惯性的,堕落和颓废亦是如此。', '不要把梦遗落在床上,不要画个月亮挂在天空。', '要努力,但是不要着急,凡事都应该有过程。', '人的本能是追逐从他身边飞走的东西,却逃避追逐他的东西。', '生命该是人类俯瞰万象的顶峰,而不是人赖以藏身的隧洞。', '你不可能要求一个没有风暴的海洋。那不是海,是泥潭。', '被安静吵醒。', '远在远方的风比远方更远。', '我不是归人,我只是个过客。', '就像水消失在水中。', '城市里应该有匹马。', '学会思考,学会倾听,学会辨别。', '控制自己的欲望。', '让自己做一个有趣的人。', '瓦上四季,檐下人生。岁月斑驳,安之若素。', '躲得过对酒当歌的夜,躲不过四下无人的街。', '光而不耀,静水流深。', '故事还长,你别失望。', '和世界交手的这许多年,你是否光彩依旧,兴趣盎然。', '故事不见得非得有个结尾。', '永远年轻,永远热泪盈眶。', '你不用很厉害的开始,但你要开始变得很厉害。', '与众不同却又令人心悦诚服。', '你要搞清楚你人生的剧本——不是你父母的续集,不是你子女的前传,更不是你朋友的外篇。对待生命不妨大胆冒险一下,因为最终你要失去它。生命中最难的阶段不是没有人懂你,而是你不懂你自己。', '不辜负自己,不委屈别人。', '不要因为别人有什么就忘了你自己有什么了,同时不要忘了自己要什么。', '因为害怕自己并非明珠而不敢刻苦琢磨,又因为有几分相信自己是明珠而不能与瓦砾碌碌为伍,遂逐渐远离时间,疏避人群,结果在内心不断地用愤懑和羞怒饲育着自己懦弱的自尊心,世上每个人都是驯兽师,而那匹猛兽,就是每个人各自的性情。', '所谓学习:你突然间对一些对之了解贯穿过去整个人生的事物有了新的发现,并且以一种全新的方式。', '走过千帆,仍能方寸不乱。', '以前总觉得时间可以任意挥霍,如今竟然对它斤斤计较起来。', '君子慎其独也。', '后来,尽管生活艰难,但再也找不到醉酒的理由。', '我们是不可能不负创伤地走出人生的竞技场的。', '桃李春风一杯酒,江湖夜雨十年灯。', '船在海上,马在山中。', '要么不做,要么就做好,把力所能及的事情做到极致。', '能力是看最后能让大家做成多大的事情,而不是看你会什么,那叫技能。', '把答应自己的事一一做到才叫酷。', '明朗坦荡钟情豁达。', '不是所有的鱼都会生活在同一片海里。', '知世故,而不世故。', '人生最棒的感觉,就是你做到别人说你做不到的事。', '实打实的娴熟,总要胜过很浮夸的捷径。', '早日完成里程碑,才能从容不迫。' ]; function randomProfile() { var i = Math.floor(Math.random() * profileArray.length) return profileArray[i] } //util.js function imageUtil(e) { var imageSize = {}; var originalWidth = e.detail.width;//图片原始宽 var originalHeight = e.detail.height;//图片原始高 var originalScale = originalHeight / originalWidth;//图片高宽比 // console.log('originalWidth: ' + originalWidth) // console.log('originalHeight: ' + originalHeight) //获取屏幕宽高 wx.getSystemInfo({ success: function (res) { var windowWidth = res.windowWidth; var windowHeight = res.windowHeight; var windowscale = windowHeight / windowWidth;//屏幕高宽比 // console.log('windowWidth: ' + windowWidth) // console.log('windowHeight: ' + windowHeight) if (originalScale < windowscale) {//图片高宽比小于屏幕高宽比 //图片缩放后的宽为屏幕宽 imageSize.imageWidth = windowWidth; imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth; } else {//图片高宽比大于屏幕高宽比 //图片缩放后的高为屏幕高 imageSize.imageHeight = windowHeight; imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight; } } }) // console.log('缩放后的宽: ' + imageSize.imageWidth) // console.log('缩放后的高: ' + imageSize.imageHeight) return imageSize; } module.exports = { imageUtil: imageUtil, alert: alert, loading: loading, showToast: showToast, formatTime: formatTime, checkMobile: checkMobile, randomFileName: randomFileName, checkAuth: checkAuth, getLocation: getLocation, time: time, getLocalTime: getLocalTime, checkLogin: checkLogin, numberFormater: numberFormater, generateContent: generateContent, randomProfile: randomProfile, formatStartTime: formatStartTime, formatEndTime: formatEndTime , formatMinute: formatMinute }
josephsavona/valuable
test/types/bool_spec.js
<filename>test/types/bool_spec.js<gh_stars>10-100 var assert = require('chai').assert, sinon = require('sinon'), _ = require('lodash'), Model = require('../../src/model'), Bool = require('../../src/bool'), rawValues = require('../mock_values'); var MyModel = Model.define({ bool: Bool }); describe('Bool', function() { var model; it('has a default value of 0', function() { var i = new MyModel(); assert.equal(i.val('bool'), false); }); it('cannot construct from non-boolean values', function() { rawValues.forEach(function(val) { if (_.isBoolean(val) || val === null || typeof val === 'undefined') { return; } assert.throws(function() { new MyModel({bool: val}); }) }); }); it('constructs with the given boolean value', function() { [true,false].forEach(function(val) { var i = new MyModel({bool: val}); assert.deepEqual(i.bool.val, val); }); }); it('cannot set to a non-boolean value', function() { rawValues.forEach(function(val) { if (_.isBoolean(val) || val === null || typeof val === 'undefined') { return; } var i = new MyModel(); assert.throws(function() { i.bool.val = val; }) }); }); it('sets to true/false', function() { [true,false].forEach(function(val) { var i = new MyModel(); i.bool.val = val; assert.deepEqual(i.val('bool'), val); }); }); it('negates the current value', function() { [true,false].forEach(function(val) { var i = new MyModel({bool: val}); i.bool.negate(); assert.deepEqual(i.val('bool'), !val); }); }); });
MachSilva/Ds
cg/include/debug/AnimatedAlgorithm.h
<gh_stars>1-10 //[]---------------------------------------------------------------[] //| | //| Copyright (C) 2016, 2022 <NAME>. | //| | //| This software is provided 'as-is', without any express or | //| implied warranty. In no event will the authors be held liable | //| for any damages arising from the use of this software. | //| | //| Permission is granted to anyone to use this software for any | //| purpose, including commercial applications, and to alter it and | //| redistribute it freely, subject to the following restrictions: | //| | //| 1. The origin of this software must not be misrepresented; you | //| must not claim that you wrote the original software. If you use | //| this software in a product, an acknowledgment in the product | //| documentation would be appreciated but is not required. | //| | //| 2. Altered source versions must be plainly marked as such, and | //| must not be misrepresented as being the original software. | //| | //| 3. This notice may not be removed or altered from any source | //| distribution. | //| | //[]---------------------------------------------------------------[] // // OVERVIEW: AnimatedAlgorithm.h // ======== // Class definition for animated algorithm. // // Author: <NAME> // Last revision: 10/02/2022 #ifndef __AnimatedAlgorithm_h #define __AnimatedAlgorithm_h #include <condition_variable> #include <memory> #include <string> #include <thread> namespace cg { // begin namespace cg namespace this_algorithm { // begin namespace this_algorithm #ifdef _DRAW_ALG /// Draws the current algorithm. void draw(bool stop = false, const char* fmt = nullptr, ...); #else inline void draw(bool, const char*, ...) { // do nothing } #endif // _DRAW_ALG } // end namespace this_algorithm ///////////////////////////////////////////////////////////////////// // // AnimatedAlgorithm: animated algorithm class // ================= class AnimatedAlgorithm { public: enum class State { CREATED, RUNNING, SLEEPING, CANCEL, RUN, TERMINATED }; enum class RunMode { CONTINUE, STEP }; RunMode runMode{RunMode::CONTINUE}; /// Destructor. virtual ~AnimatedAlgorithm() { // do nothing } /// Gets the name of this algorithm. const char* name() const { return _name.c_str(); } State state() const { return _state; } /// Starts this algorithm. void start(); /// Waits for termination of this algorithm. void join(); const std::string& stepLog() const { return _stepLog; } protected: bool _canDraw{false}; bool _stopped{false}; /// Constructor. AnimatedAlgorithm(const std::string& s): _name{s}, _state{State::CREATED} { // do nothing } /// Initializes this algorithm. virtual void initialize() { // do nothing } /// Runs this algorithm. virtual void run() = 0; /// Terminates this algorithm. virtual void terminate() { // do nothing } /// Handles mouse button event. virtual bool onMouse(double, double, int, int) { return false; } /// Handles mouse motion event. virtual bool onMotion(int, double, double) { return false; } /// Handles mouse wheel/touchpad gesture event. virtual bool onScroll(double, double) { return false; } /// Handles text input event. virtual bool onChar(unsigned int) { return false; } virtual void draw(int, int) = 0; void wait(bool); void wake(bool = false); void stop(bool stop = true) { if (!(_stopped = stop)) wake(); } void cancel(); private: using ThreadPtr = std::unique_ptr<std::thread>; std::string _name; State _state; std::mutex _lockDrawing; std::condition_variable _drawing; ThreadPtr _thread; bool _notified{true}; std::string _stepLog; static AnimatedAlgorithm* _current; void launch(); friend class GUI; friend void this_algorithm::draw(bool, const char*, ...); }; // AnimatedAlgorithm } // end namespace cg #endif // __AnimatedAlgorithm_h
beautifwhale/bowhead
packages/test-app/src/utils/constants.js
export const FIRESTORE_COLLECTIONS = { WORKSPACES: 'workspaces', USER_WORKSPACES: 'userWorkspaces', }; export const USER_ROLES = { OWNER: 'owner', MEMBER: 'member' }
horoeka-2021/argumentum
client/api/addChatUser.js
import request from 'superagent' // not finished unsure... export default function addChatUser (user) { return request.post('/api/v1/addChatUser') .send(user) .then(res => { return null }) }
VU-libtech/OLE-INST
ole-app/olefs/src/main/java/org/kuali/ole/select/document/web/struts/OleLineItemReceivingAction.java
/* * Copyright 2011 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/ecl2.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.ole.select.document.web.struts; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.ole.docstore.common.document.Bib; import org.kuali.ole.module.purap.PurapConstants; import org.kuali.ole.module.purap.PurapConstants.CorrectionReceivingDocumentStrings; import org.kuali.ole.module.purap.PurapConstants.PREQDocumentsStrings; import org.kuali.ole.module.purap.PurapKeyConstants; import org.kuali.ole.module.purap.PurapPropertyConstants; import org.kuali.ole.module.purap.document.LineItemReceivingDocument; import org.kuali.ole.module.purap.document.PurchaseOrderDocument; import org.kuali.ole.module.purap.document.ReceivingDocument; import org.kuali.ole.module.purap.document.service.PurchaseOrderService; import org.kuali.ole.module.purap.document.service.ReceivingService; import org.kuali.ole.module.purap.document.validation.event.AddReceivingItemEvent; import org.kuali.ole.module.purap.document.web.struts.LineItemReceivingAction; import org.kuali.ole.module.purap.document.web.struts.LineItemReceivingForm; import org.kuali.ole.module.purap.util.ReceivingQuestionCallback; import org.kuali.ole.pojo.OleBibRecord; import org.kuali.ole.pojo.OleEditorResponse; import org.kuali.ole.select.OleSelectConstant; import org.kuali.ole.select.bo.OLEDonor; import org.kuali.ole.select.bo.OLEEditorResponse; import org.kuali.ole.select.bo.OLELinkPurapDonor; import org.kuali.ole.select.businessobject.*; import org.kuali.ole.select.document.OleLineItemReceivingDocument; import org.kuali.ole.select.document.service.OleCopyHelperService; import org.kuali.ole.select.document.service.OleDocstoreHelperService; import org.kuali.ole.select.document.service.OleLineItemReceivingService; import org.kuali.ole.select.document.service.OleNoteTypeService; import org.kuali.ole.select.document.service.impl.OleLineItemReceivingServiceImpl; import org.kuali.ole.select.document.validation.event.OleLineItemReceivingDescEvent; import org.kuali.ole.select.service.BibInfoWrapperService; import org.kuali.ole.select.service.FileProcessingService; import org.kuali.ole.select.service.impl.BibInfoWrapperServiceImpl; import org.kuali.ole.sys.OLEConstants; import org.kuali.ole.sys.OLEKeyConstants; import org.kuali.ole.sys.OLEPropertyConstants; import org.kuali.ole.sys.context.SpringContext; import org.kuali.rice.core.api.config.property.ConfigurationService; import org.kuali.rice.core.api.datetime.DateTimeService; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.core.api.util.type.KualiInteger; import org.kuali.rice.kim.api.KimConstants; import org.kuali.rice.kim.api.services.IdentityManagementService; import org.kuali.rice.kns.service.DocumentHelperService; import org.kuali.rice.kns.web.struts.form.KualiDocumentFormBase; import org.kuali.rice.krad.exception.DocumentAuthorizationException; import org.kuali.rice.krad.service.KRADServiceLocator; import org.kuali.rice.krad.service.KRADServiceLocatorWeb; import org.kuali.rice.krad.service.KualiRuleService; import org.kuali.rice.krad.service.LookupService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.KRADConstants; import org.kuali.rice.krad.util.ObjectUtils; import org.kuali.rice.krad.util.UrlFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; /** * This class performs actions for Line Item Receiving with respect to OLE */ public class OleLineItemReceivingAction extends LineItemReceivingAction { private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OleLineItemReceivingAction.class); private static transient ConfigurationService kualiConfigurationService; private static transient OleLineItemReceivingService oleLineItemReceivingService; /** * This method sets parts received value for each item to zero. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ @Override public ActionForward clearQty(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("Inside clearQty of OleLineItemReceivingAction"); OleLineItemReceivingForm lineItemReceivingForm = (OleLineItemReceivingForm) form; OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) lineItemReceivingForm.getDocument(); for (OleLineItemReceivingItem item : (List<OleLineItemReceivingItem>) lineItemReceivingDocument.getItems()) { item.setItemReceivedTotalParts(KualiDecimal.ZERO); } LOG.debug("Leaving clearQty of OleLineItemReceivingAction"); return super.clearQty(mapping, lineItemReceivingForm, request, response); } /** * This method loads total order parts minus prior received parts into total received parts for each item. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ @Override public ActionForward loadQty(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("Inside loadQty of OleLineItemReceivingAction"); OleLineItemReceivingForm lineItemReceivingForm = (OleLineItemReceivingForm) form; OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) lineItemReceivingForm.getDocument(); for (OleLineItemReceivingItem item : (List<OleLineItemReceivingItem>) lineItemReceivingDocument.getItems()) { if (item.isOrderedItem()) { if (item.getItemOrderedParts().subtract(item.getItemReceivedPriorParts()).isGreaterEqual(KualiDecimal.ZERO)) { item.setItemReceivedTotalParts(item.getItemOrderedQuantity().subtract(item.getItemReceivedPriorParts())); } else { item.setItemReceivedTotalParts(KualiDecimal.ZERO); } } } LOG.debug("Leaving loadQty of OleLineItemReceivingAction"); return super.loadQty(mapping, form, request, response); } /** * This method is used to add an exception note to the specified item. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward addExceptionNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("Inside addExceptionNote of OleLineItemReceivingAction"); OleLineItemReceivingForm receiveForm = (OleLineItemReceivingForm) form; OleLineItemReceivingDocument receiveDocument = (OleLineItemReceivingDocument) receiveForm.getDocument(); OleLineItemReceivingItem selectedItem = (OleLineItemReceivingItem) receiveDocument.getItem(this.getSelectedLine(request)); OleReceivingLineExceptionNotes exceptionNotes = new OleReceivingLineExceptionNotes(); exceptionNotes.setExceptionTypeId(selectedItem.getExceptionTypeId()); exceptionNotes.setExceptionNotes(selectedItem.getExceptionNotes()); exceptionNotes.setReceivingLineItemIdentifier(selectedItem.getReceivingItemIdentifier()); selectedItem.addExceptionNote(exceptionNotes); ((OleLineItemReceivingItem) receiveDocument.getItem(this.getSelectedLine(request))).setExceptionTypeId(null); ((OleLineItemReceivingItem) receiveDocument.getItem(this.getSelectedLine(request))).setExceptionNotes(null); LOG.debug("Leaving addExceptionNote of OleLineItemReceivingAction"); return mapping.findForward(OLEConstants.MAPPING_BASIC); } /** * This method is used to delete an exception note from the specified item * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward deleteExceptionNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("Inside deleteExceptionNote of OleLineItemReceivingAction"); OleLineItemReceivingForm receiveForm = (OleLineItemReceivingForm) form; OleLineItemReceivingDocument receiveDocument = (OleLineItemReceivingDocument) receiveForm.getDocument(); String[] indexes = getSelectedLineForDelete(request); int itemIndex = Integer.parseInt(indexes[0]); int noteIndex = Integer.parseInt(indexes[1]); OleLineItemReceivingItem item = (OleLineItemReceivingItem) receiveDocument.getItem((itemIndex)); item.getExceptionNoteList().remove(noteIndex); LOG.debug("Leaving deleteExceptionNote of OleLineItemReceivingAction"); return mapping.findForward(OLEConstants.MAPPING_BASIC); } /** * This method is used to add a receipt note to the specified item. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward addReceiptNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("Inside addReceiptNote of OleLineItemReceivingAction"); OleLineItemReceivingForm receiveForm = (OleLineItemReceivingForm) form; OleLineItemReceivingDocument receiveDocument = (OleLineItemReceivingDocument) receiveForm.getDocument(); OleLineItemReceivingItem selectedItem = (OleLineItemReceivingItem) receiveDocument.getItem(this.getSelectedLine(request)); OleLineItemReceivingReceiptNotes receiptNotes = new OleLineItemReceivingReceiptNotes(); OleNoteType oleNoteType = SpringContext.getBean(OleNoteTypeService.class).getNoteTypeDetails(selectedItem.getNoteTypeId()); receiptNotes.setNoteTypeId(selectedItem.getNoteTypeId()); receiptNotes.setNotes(selectedItem.getReceiptNotes()); receiptNotes.setReceivingLineItemIdentifier(selectedItem.getReceivingItemIdentifier()); receiptNotes.setNoteType(oleNoteType); selectedItem.addReceiptNote(receiptNotes); selectedItem.addNote(receiptNotes); ((OleLineItemReceivingItem) receiveDocument.getItem(this.getSelectedLine(request))).setNoteTypeId(null); ((OleLineItemReceivingItem) receiveDocument.getItem(this.getSelectedLine(request))).setReceiptNotes(null); LOG.debug("Leaving addReceiptNote of OleLineItemReceivingAction"); return mapping.findForward(OLEConstants.MAPPING_BASIC); } /** * This method is used to delete a receipt note from the specified item. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward deleteReceiptNote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("Inside deleteReceiptNote of OleLineItemReceivingAction"); OleLineItemReceivingForm receiveForm = (OleLineItemReceivingForm) form; OleLineItemReceivingDocument receiveDocument = (OleLineItemReceivingDocument) receiveForm.getDocument(); String[] indexes = getSelectedLineForDelete(request); int itemIndex = Integer.parseInt(indexes[0]); int noteIndex = Integer.parseInt(indexes[1]); OleLineItemReceivingItem item = (OleLineItemReceivingItem) receiveDocument.getItem((itemIndex)); item.getReceiptNoteList().remove(noteIndex); int index = ObjectUtils.isNotNull(item.getReceiptNoteListSize()) ? item.getReceiptNoteListSize() : 0; index = index + (ObjectUtils.isNotNull(item.getSpecialHandlingNoteList()) ? item.getSpecialHandlingNoteList().size() : 0); if (ObjectUtils.isNotNull(item.getReceiptNoteListSize()) || (ObjectUtils.isNotNull(item.getSpecialHandlingNoteList()) && item.getSpecialHandlingNoteList().size() > 0)) { index = index - 1; } item.getNoteList().remove(index + noteIndex); LOG.debug("leaving deleteReceiptNote of OleLineItemReceivingAction"); return mapping.findForward(OLEConstants.MAPPING_BASIC); } /** * Will return an array of Strings containing 2 indexes, the first String is the item index and the second String is the account * index. These are obtained by parsing the method to call parameter from the request, between the word ".line" and "." The * indexes are separated by a semicolon (:) * * @param request The HttpServletRequest * @return An array of Strings containing pairs of two indices, an item index and a account index */ protected String[] getSelectedLineForDelete(HttpServletRequest request) { LOG.debug("Inside getSelectedLineForDelete of OleLineItemReceivingAction"); String accountString = new String(); String parameterName = (String) request.getAttribute(OLEConstants.METHOD_TO_CALL_ATTRIBUTE); if (StringUtils.isNotBlank(parameterName)) { accountString = StringUtils.substringBetween(parameterName, ".line", "."); } String[] result = StringUtils.split(accountString, ":"); LOG.debug("Leaving getSelectedLineForDelete of OleLineItemReceivingAction"); return result; } /** * This method is overridden to set doctype name as OLE_RCVC and to change receivingUrl to ole receiving url * * @param mapping * @param form * @param request * @param response * @return * @throws Exception * @see org.kuali.ole.module.purap.document.web.struts.LineItemReceivingAction#createReceivingCorrection(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward createReceivingCorrection(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("Inside createReceivingCorrection of OleLineItemReceivingAction"); LineItemReceivingForm rlForm = (LineItemReceivingForm) form; LineItemReceivingDocument document = (LineItemReceivingDocument) rlForm.getDocument(); String operation = "AddCorrectionNote "; ReceivingQuestionCallback callback = new ReceivingQuestionCallback() { public boolean questionComplete = false; protected String correctionDocumentnoteText; @Override public ReceivingDocument doPostQuestion(ReceivingDocument document, String noteText) throws Exception { //mark question completed this.setQuestionComplete(true); this.setCorrectionDocumentCreationNoteText(noteText); return document; } @Override public boolean isQuestionComplete() { return this.questionComplete; } @Override public void setQuestionComplete(boolean questionComplete) { this.questionComplete = questionComplete; } @Override public String getCorrectionDocumentCreationNoteText() { return correctionDocumentnoteText; } @Override public void setCorrectionDocumentCreationNoteText(String noteText) { correctionDocumentnoteText = noteText; } }; //ask question ActionForward forward = askQuestionWithInput(mapping, form, request, response, CorrectionReceivingDocumentStrings.NOTE_QUESTION, CorrectionReceivingDocumentStrings.NOTE_PREFIX, operation, PurapKeyConstants.MESSAGE_RECEIVING_CORRECTION_NOTE, callback); //if question asked is complete, then route if (callback.isQuestionComplete()) { //set parameters String basePath = getApplicationBaseUrl(); String methodToCallDocHandler = "docHandler"; String methodToCallReceivingCorrection = "initiate"; Properties parameters = new Properties(); parameters.put(OLEConstants.DISPATCH_REQUEST_PARAMETER, methodToCallDocHandler); parameters.put(OLEConstants.PARAMETER_COMMAND, methodToCallReceivingCorrection); parameters.put(OLEConstants.DOCUMENT_TYPE_NAME, "OLE_RCVC"); parameters.put("receivingLineDocId", document.getDocumentHeader().getDocumentNumber()); parameters.put(PurapConstants.CorrectionReceivingDocumentStrings.CORRECTION_RECEIVING_CREATION_NOTE_PARAMETER, callback.getCorrectionDocumentCreationNoteText()); //create url String receivingCorrectionUrl = UrlFactory.parameterizeUrl(basePath + "/" + "selectOleCorrectionReceiving.do", parameters); //create forward forward = new ActionForward(receivingCorrectionUrl, true); } LOG.debug("Leaving createReceivingCorrection of OleLineItemReceivingAction"); return forward; } /** * This method is overridden to skip intermediate page when creating OleLineItemReceivingDocument from Purchase Order page * * @see org.kuali.ole.module.purap.document.web.struts.LineItemReceivingAction#continueReceivingLine(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override public ActionForward continueReceivingLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("Inside continueReceivingLine of OleLineItemReceivingAction"); LineItemReceivingForm rlf = (LineItemReceivingForm) form; LineItemReceivingDocument rlDoc = (LineItemReceivingDocument) rlf.getDocument(); // Added for OLE-2060 to skip intermediate page when creating Receiving Document from Purchase Order page if (ObjectUtils.isNull(rlDoc.getDocumentHeader()) || ObjectUtils.isNull(rlDoc.getDocumentHeader().getDocumentNumber())) { KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form; createDocument(kualiDocumentFormBase); rlDoc = (LineItemReceivingDocument) kualiDocumentFormBase.getDocument(); rlDoc.setPurchaseOrderIdentifier(rlf.getPurchaseOrderId()); DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class); rlDoc.setShipmentReceivedDate(dateTimeService.getCurrentSqlDate()); } // Added for OLE-2060 to skip intermediate page when creating Receiving Document from Purchase Order page Ends getOleLineItemReceivingService().getInitialCollapseSections(rlDoc); GlobalVariables.getMessageMap().clearErrorPath(); GlobalVariables.getMessageMap().addToErrorPath(OLEPropertyConstants.DOCUMENT); boolean valid = true; boolean poNotNull = true; //check for a po id if (ObjectUtils.isNull(rlDoc.getPurchaseOrderIdentifier())) { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, OLEKeyConstants.ERROR_REQUIRED, PREQDocumentsStrings.PURCHASE_ORDER_ID); poNotNull = false; } if (ObjectUtils.isNull(rlDoc.getShipmentReceivedDate())) { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.SHIPMENT_RECEIVED_DATE, OLEKeyConstants.ERROR_REQUIRED, PurapConstants.LineItemReceivingDocumentStrings.VENDOR_DATE); } //exit early as the po is null, no need to proceed further until this is taken care of if (poNotNull == false) { return mapping.findForward(OLEConstants.MAPPING_BASIC); } PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class).getCurrentPurchaseOrder(rlDoc.getPurchaseOrderIdentifier()); if (ObjectUtils.isNotNull(po)) { // TODO figure out a more straightforward way to do this. ailish put this in so the link id would be set and the perm check would work rlDoc.setAccountsPayablePurchasingDocumentLinkIdentifier(po.getAccountsPayablePurchasingDocumentLinkIdentifier()); //TODO hjs-check to see if user is allowed to initiate doc based on PO sensitive data (add this to all other docs except acm doc) if (!SpringContext.getBean(DocumentHelperService.class).getDocumentAuthorizer(rlDoc).isAuthorizedByTemplate(rlDoc, KRADConstants.KNS_NAMESPACE, KimConstants.PermissionTemplateNames.OPEN_DOCUMENT, GlobalVariables.getUserSession().getPrincipalId())) { throw buildAuthorizationException("initiate document", rlDoc); } } else { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, PurapKeyConstants.ERROR_PURCHASE_ORDER_NOT_EXIST); return mapping.findForward(OLEConstants.MAPPING_BASIC); } //perform duplicate check ActionForward forward = performDuplicateReceivingLineCheck(mapping, form, request, response, rlDoc); if (forward != null) { return forward; } if (!SpringContext.getBean(ReceivingService.class).isPurchaseOrderActiveForLineItemReceivingDocumentCreation(rlDoc.getPurchaseOrderIdentifier())) { GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, PurapKeyConstants.ERROR_RECEIVING_LINE_DOCUMENT_PO_NOT_ACTIVE, rlDoc.getPurchaseOrderIdentifier().toString()); valid &= false; } if (SpringContext.getBean(ReceivingService.class).canCreateLineItemReceivingDocument(rlDoc.getPurchaseOrderIdentifier(), rlDoc.getDocumentNumber()) == false) { String inProcessDocNum = ""; List<String> inProcessDocNumbers = SpringContext.getBean(ReceivingService.class).getLineItemReceivingDocumentNumbersInProcessForPurchaseOrder(rlDoc.getPurchaseOrderIdentifier(), rlDoc.getDocumentNumber()); if (!inProcessDocNumbers.isEmpty()) { // should not be empty if we reach this point inProcessDocNum = inProcessDocNumbers.get(0); } GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, PurapKeyConstants.ERROR_RECEIVING_LINE_DOCUMENT_ACTIVE_FOR_PO, inProcessDocNum, rlDoc.getPurchaseOrderIdentifier().toString()); valid &= false; } //populate and save Receiving Line Document from Purchase Order, only if we passed all the rules if (valid) { SpringContext.getBean(ReceivingService.class).populateAndSaveLineItemReceivingDocument(rlDoc); } LOG.debug("Leaving continueReceivingLine of OleLineItemReceivingAction"); return mapping.findForward(OLEConstants.MAPPING_BASIC); } /** * Add a new item to the document. * * @param mapping An ActionMapping * @param form An ActionForm * @param request The HttpServletRequest * @param response The HttpServletResponse * @return An ActionForward * @throws Exception */ @Override public ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form; OleLineItemReceivingItem item = (OleLineItemReceivingItem) oleLineItemReceivingForm.getNewLineItemReceivingItemLine(); OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getDocument(); LOG.debug("Inside addItem >>>>>>>>>>>>>>>>>"); String documentTypeName = OLEConstants.FinancialDocumentTypeCodes.LINE_ITEM_RECEIVING; String nameSpaceCode = OLEConstants.OleLineItemReceiving.LINE_ITEM_RECEIVING_NAMESPACE; if (LOG.isDebugEnabled()) { LOG.debug("Inside addItem documentTypeName >>>>>>>>>>>>>>>>>" + documentTypeName); } LOG.debug("Inside addItem nameSpaceCode >>>>>>>>>>>>>>>>>" + nameSpaceCode); // LOG.info("Inside addItem permissionDetails >>>>>>>>>>>>>>>>>" + permissionDetails.get(documentTypeName)); boolean hasPermission = SpringContext.getBean(IdentityManagementService.class).hasPermission(GlobalVariables.getUserSession().getPerson().getPrincipalId(), nameSpaceCode, OLEConstants.OleLineItemReceiving.ADD_NEW_LINE_ITEM); if (!hasPermission) { if (LOG.isDebugEnabled()) { LOG.debug("Inside addItem hasPermission if>>>>>>>>>>>>>>>>>" + hasPermission); } throw new DocumentAuthorizationException(GlobalVariables.getUserSession().getPerson().getPrincipalName(), "add New Line Items", lineItemReceivingDocument.getDocumentNumber()); // throw new RuntimeException("User " + new String[]{GlobalVariables.getUserSession().getPerson().getPrincipalName() + "is not authorized to add New Line Items" + true}); } boolean rulePassed = SpringContext.getBean(KualiRuleService.class).applyRules(new AddReceivingItemEvent(PurapPropertyConstants.NEW_LINE_ITEM_RECEIVING_ITEM_LINE, lineItemReceivingDocument, item)); if (rulePassed) { item = (OleLineItemReceivingItem) oleLineItemReceivingForm.getAndResetNewReceivingItemLine(); //TODO: we need to set the line number correctly to match up to PO BibInfoWrapperService docStore = SpringContext.getBean(BibInfoWrapperServiceImpl.class); FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class); String titleId = null; boolean isBibFileExist = false; Iterator itemIterator = lineItemReceivingDocument.getItems().iterator(); int itemCounter = 0; while (itemIterator.hasNext()) { OleLineItemReceivingItem tempItem = (OleLineItemReceivingItem) itemIterator.next(); if (tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE) || tempItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_UNORDERED_ITEM_CODE)) { itemCounter++; } } String itemNo = String.valueOf(itemCounter); //String itemNo = String.valueOf(lineItemReceivingDocument.getItems().size() - 1); HashMap<String, String> dataMap = new HashMap<String, String>(); item.setBibInfoBean(new BibInfoBean()); if (item.getBibInfoBean().getDocStoreOperation() == null) { item.getBibInfoBean().setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF); } String fileName = lineItemReceivingDocument.getDocumentNumber() + "_" + itemNo; // Modified for jira OLE - 2437 starts setItemDescription(item, fileName); item.setStartingCopyNumber(new KualiInteger(1)); // Modified for jira OLE - 2437 ends /*dataMap.put(OleSelectConstant.FILEPATH, fileProcessingService.getMarcXMLFileDirLocation()); dataMap.put(OleSelectConstant.FILENAME, fileName); if (fileProcessingService.isCreateFileExist(dataMap)) { isBibFileExist = true; } if (isBibFileExist) { titleId = docStore.getTitleIdByMarcXMLFileProcessing(item.getBibInfoBean(), dataMap); item.setItemTitleId(titleId); BibInfoBean xmlBibInfoBean = new BibInfoBean(); dataMap.put(OleSelectConstant.TITLE_ID, titleId); dataMap.put(OleSelectConstant.DOC_CATEGORY_TYPE, OleSelectConstant.DOC_CATEGORY_TYPE_ITEMLINKS); xmlBibInfoBean = docStore.getBibInfo(dataMap); item.setBibInfoBean(xmlBibInfoBean); item.setItemDescription((item.getBibInfoBean().getTitle() != null ? item.getBibInfoBean().getTitle() : "") + (item.getBibInfoBean().getAuthor() != null ? "," + item.getBibInfoBean().getAuthor() : "") + (item.getBibInfoBean().getPublisher() != null ? "," + item.getBibInfoBean().getPublisher() : "") + (item.getBibInfoBean().getIsbn() != null ? "," + item.getBibInfoBean().getIsbn() : "")); HashMap<String,String> queryMap = new HashMap<String,String>(); queryMap.put(OleSelectConstant.DocStoreDetails.ITEMLINKS_KEY, item.getItemTitleId()); List<DocInfoBean> docStoreResult = docStore.searchBibInfo(queryMap); Iterator bibIdIterator = docStoreResult.iterator(); if(bibIdIterator.hasNext()){ DocInfoBean docInfoBean = (DocInfoBean)bibIdIterator.next(); item.setBibUUID(docInfoBean.getUniqueId()); } }*/ boolean ruleFlag = getKualiRuleService().applyRules(new OleLineItemReceivingDescEvent(lineItemReceivingDocument, item)); if (ruleFlag) { lineItemReceivingDocument.addItem(item); } } return mapping.findForward(OLEConstants.MAPPING_BASIC); } @Override public ActionForward route(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub // ActionForward forward=super.route(mapping, form, request, response); OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form; OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getDocument(); List<OleLineItemReceivingItem> items = lineItemReceivingDocument.getItems(); for (OleLineItemReceivingItem item : items) { OleLineItemReceivingService oleLineItemReceivingService = SpringContext .getBean(OleLineItemReceivingServiceImpl.class); OlePurchaseOrderItem olePurchaseOrderItem = oleLineItemReceivingService.getOlePurchaseOrderItem(item.getPurchaseOrderIdentifier()); OleLineItemReceivingDoc oleLineItemReceivingItemDoc = new OleLineItemReceivingDoc(); oleLineItemReceivingItemDoc.setReceivingLineItemIdentifier(item.getReceivingItemIdentifier()); if (item.getItemTitleId() != null) { oleLineItemReceivingItemDoc.setItemTitleId(item.getItemTitleId()); } else { oleLineItemReceivingItemDoc.setItemTitleId(olePurchaseOrderItem.getItemTitleId()); } if (olePurchaseOrderItem != null) { /* * if(item.getItemReturnedTotalQuantity().isNonZero() && item.getItemReturnedTotalParts().isNonZero()){ } */ OleCopyHelperService oleCopyHelperService = SpringContext.getBean(OleCopyHelperService.class); oleCopyHelperService.updateRequisitionAndPOItems(olePurchaseOrderItem, item, null, lineItemReceivingDocument.getIsATypeOfRCVGDoc()); // updateReceivingItemReceiptStatus(item); } // oleLineItemReceivingService.saveOleLineItemReceivingItemDoc(oleLineItemReceivingItemDoc); } return super.route(mapping, form, request, response); } @Override public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = super.save(mapping, form, request, response); OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form; OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getDocument(); List<OleLineItemReceivingItem> items = lineItemReceivingDocument.getItems(); for (OleLineItemReceivingItem item : items) { OleLineItemReceivingService oleLineItemReceivingService = SpringContext.getBean(OleLineItemReceivingServiceImpl.class); ; OleLineItemReceivingDoc oleLineItemReceivingItemDoc = new OleLineItemReceivingDoc(); oleLineItemReceivingItemDoc.setReceivingLineItemIdentifier(item.getReceivingItemIdentifier()); if (item.getItemTitleId() != null) { oleLineItemReceivingItemDoc.setItemTitleId(item.getItemTitleId()); } else { OlePurchaseOrderItem olePurchaseOrderItem = oleLineItemReceivingService.getOlePurchaseOrderItem(item.getPurchaseOrderIdentifier()); oleLineItemReceivingItemDoc.setItemTitleId(olePurchaseOrderItem.getItemTitleId()); } oleLineItemReceivingService.saveOleLineItemReceivingItemDoc(oleLineItemReceivingItemDoc); } return forward; } private void setItemDescription(OleLineItemReceivingItem item, String fileName) { if (OleDocstoreResponse.getInstance().getEditorResponse() != null) { Map<String, OLEEditorResponse> oleEditorResponses = OleDocstoreResponse.getInstance().getEditorResponse(); OLEEditorResponse oleEditorResponse = oleEditorResponses.get(fileName); Bib bib = oleEditorResponse != null ? oleEditorResponse.getBib() : null; bib = (Bib) bib.deserializeContent(bib); if (bib != null) { String title = (bib.getTitle() != null&& !bib.getTitle().isEmpty()) ? bib.getTitle() + ", " : ""; String author = (bib.getAuthor()!=null && !bib.getAuthor().isEmpty()) ? bib.getAuthor() + ", " : ""; String publisher = (bib.getPublisher()!=null && !bib.getPublisher().isEmpty()) ? bib.getPublisher() + ", " : ""; String isbn = (bib.getIsbn()!=null && !bib.getIsbn().isEmpty()) ? bib.getIsbn() + ", " : ""; String description = title + author + publisher + isbn; item.setItemDescription(description.substring(0, (description.lastIndexOf(",")))); } if (bib != null) { item.setBibUUID(bib.getId()); item.setItemTitleId(bib.getId()); OleLineItemReceivingDoc oleLineItemReceivingDoc = new OleLineItemReceivingDoc(); oleLineItemReceivingDoc.setItemTitleId(oleEditorResponse.getBib().getId()); item.getOleLineItemReceivingItemDocList().add(oleLineItemReceivingDoc); } OleDocstoreResponse.getInstance().getEditorResponse().remove(oleEditorResponse); } } public boolean checkForCopiesAndLocation(OleLineItemReceivingItem item) { boolean isValid = true; if (null == item.getItemCopies() || null == item.getLocationCopies()) { GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OLEConstants.ITEM_ITEMCOPIES_OR_LOCATIONCOPIES_SHOULDNOT_BE_NULL, new String[]{}); isValid = false; } return isValid; } public boolean checkForItemCopiesGreaterThanQuantity(OleLineItemReceivingItem item) { boolean isValid = true; if (item.getItemCopies().isGreaterThan(item.getItemReceivedTotalQuantity())) { GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OLEConstants.ITEM_COPIES_ITEMCOPIES_GREATERTHAN_ITEMCOPIESORDERED, new String[]{}); isValid = false; } return isValid; } public boolean checkForTotalCopiesGreaterThanQuantity(OleLineItemReceivingItem item) { boolean isValid = true; int copies = 0; if (item.getCopies().size() > 0) { for (int itemCopies = 0; itemCopies < item.getCopies().size(); itemCopies++) { copies = copies + item.getCopies().get(itemCopies).getItemCopies().intValue(); } if (item.getItemReceivedTotalQuantity().isLessThan(item.getItemCopies().add(new KualiDecimal(copies)))) { GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OLEConstants.TOTAL_OF_ITEM_COPIES_ITEMCOPIES_GREATERTHAN_ITEMCOPIESORDERED, new String[]{}); isValid = false; } } return isValid; } /** * This method takes RequisitionItem as parameter, it will calculate and set partEnumerations and startingCopyNumber for each * lineItem * * @param item * @return OleRequisitionCopies */ public OleRequisitionCopies setCopyValues(OleLineItemReceivingItem item) { OleRequisitionCopies itemCopy = new OleRequisitionCopies(); int parts = 0; if (null != item.getItemReceivedTotalParts()) { parts = item.getItemReceivedTotalParts().intValue(); itemCopy.setParts(new KualiInteger(parts)); } else if (null != item.getItemOrderedParts()) { parts = item.getItemOrderedParts().intValue(); itemCopy.setParts(new KualiInteger(parts)); } itemCopy.setItemCopies(item.getItemCopies()); StringBuffer enumeration = new StringBuffer(); if (item.getStartingCopyNumber() != null && item.getStartingCopyNumber().isNonZero()) { itemCopy.setStartingCopyNumber(item.getStartingCopyNumber()); } else { int startingCopies = 1; for (int copy = 0; copy < item.getCopies().size(); copy++) { startingCopies = startingCopies + item.getCopies().get(copy).getItemCopies().intValue(); } itemCopy.setStartingCopyNumber(new KualiInteger(startingCopies)); } String partEnumerationCopy = getConfigurationService().getPropertyValueAsString( OLEConstants.PART_ENUMERATION_COPY); String partEnumerationVolume = getConfigurationService().getPropertyValueAsString( OLEConstants.PART_ENUMERATION_VOLUME); int startingCopyNumber = itemCopy.getStartingCopyNumber().intValue(); for (int noOfCopies = 0; noOfCopies < item.getItemCopies().intValue(); noOfCopies++) { for (int noOfParts = 0; noOfParts < parts; noOfParts++) { int newNoOfCopies = startingCopyNumber + noOfCopies; int newNoOfParts = noOfParts + 1; if (noOfCopies + 1 == item.getItemCopies().intValue() && newNoOfParts == parts) { enumeration = enumeration.append( partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append( partEnumerationVolume + newNoOfParts); } else { enumeration = enumeration.append( partEnumerationCopy + newNoOfCopies + OLEConstants.DOT_TO_SEPARATE_COPIES_PARTS).append( partEnumerationVolume + newNoOfParts + OLEConstants.COMMA_TO_SEPARATE_ENUMERATION); } } } itemCopy.setPartEnumeration(enumeration.toString()); itemCopy.setLocationCopies(item.getLocationCopies()); return itemCopy; } /** * Receive a Copy for the selected Item . * * @param mapping An ActionMapping * @param form An ActionForm * @param request The HttpServletRequest * @param response The HttpServletResponse * @return An ActionForward * @throws Exception */ public ActionForward receiveCopy(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("Inside receiveCopy Method of OLELineItemReceivingAction"); OleLineItemReceivingForm lineItemReceivingForm = (OleLineItemReceivingForm) form; String[] indexes = getSelectedLineForAccounts(request); int itemIndex = Integer.parseInt(indexes[0]); OleLineItemReceivingItem item = (OleLineItemReceivingItem) ((LineItemReceivingDocument) lineItemReceivingForm .getDocument()).getItem((itemIndex)); OleCopy oleCopy = null; if(item.getCopyList().size()==1){ oleCopy = item.getCopyList().get(0); }else { int copyIndex = Integer.parseInt(indexes[1]); oleCopy = item.getCopyList().get(copyIndex); } oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.RECEIVED_STATUS); LOG.debug("Selected Copy is Received"); LOG.debug("Leaving receiveCopy Method of OLELineItemReceivingAction"); return mapping.findForward(OLEConstants.MAPPING_BASIC); } public static ConfigurationService getConfigurationService() { if (kualiConfigurationService == null) { kualiConfigurationService = SpringContext.getBean(ConfigurationService.class); } return kualiConfigurationService; } /** * Will return an array of Strings containing 2 indexes, the first String is the item index and the second String is the account * index. These are obtained by parsing the method to call parameter from the request, between the word ".line" and "." The * indexes are separated by a semicolon (:) * * @param request The HttpServletRequest * @return An array of Strings containing pairs of two indices, an item index and a account index */ protected String[] getSelectedLineForAccounts(HttpServletRequest request) { String accountString = new String(); String parameterName = (String) request.getAttribute(OLEConstants.METHOD_TO_CALL_ATTRIBUTE); if (StringUtils.isNotBlank(parameterName)) { accountString = StringUtils.substringBetween(parameterName, ".line", "."); } String[] result = StringUtils.split(accountString, ":"); return result; } @Override public ActionForward blanketApprove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form; OleLineItemReceivingDocument lineItemReceivingDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm .getDocument(); List<OleLineItemReceivingItem> items = lineItemReceivingDocument.getItems(); for (OleLineItemReceivingItem item : items) { OleLineItemReceivingService oleLineItemReceivingService = SpringContext .getBean(OleLineItemReceivingServiceImpl.class); OlePurchaseOrderItem olePurchaseOrderItem = oleLineItemReceivingService.getOlePurchaseOrderItem(item .getPurchaseOrderIdentifier()); OleLineItemReceivingDoc oleLineItemReceivingItemDoc = new OleLineItemReceivingDoc(); oleLineItemReceivingItemDoc.setReceivingLineItemIdentifier(item.getReceivingItemIdentifier()); if (item.getItemTitleId() != null) { oleLineItemReceivingItemDoc.setItemTitleId(item.getItemTitleId()); } else { oleLineItemReceivingItemDoc.setItemTitleId(olePurchaseOrderItem.getItemTitleId()); } if (olePurchaseOrderItem != null) { OleCopyHelperService oleCopyHelperService = SpringContext.getBean(OleCopyHelperService.class); oleCopyHelperService.updateRequisitionAndPOItems(olePurchaseOrderItem, item, null, lineItemReceivingDocument.getIsATypeOfRCVGDoc()); // updateReceivingItemReceiptStatus(item); } // oleLineItemReceivingService.saveOleLineItemReceivingItemDoc(oleLineItemReceivingItemDoc); } return super.blanketApprove(mapping, form, request, response); } public static OleLineItemReceivingService getOleLineItemReceivingService() { if (oleLineItemReceivingService == null) { oleLineItemReceivingService = SpringContext.getBean(OleLineItemReceivingService.class); } return oleLineItemReceivingService; } public ActionForward addDonor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { boolean flag = true; OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form; OleLineItemReceivingDocument receiveDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getDocument(); OleLineItemReceivingItem item = (OleLineItemReceivingItem) receiveDocument.getItem(this.getSelectedLine(request)); Map map = new HashMap(); if (item.getDonorCode() != null) { map.put(OLEConstants.DONOR_CODE, item.getDonorCode()); List<OLEDonor> oleDonorList = (List<OLEDonor>) getLookupService().findCollectionBySearch(OLEDonor.class, map); if (oleDonorList != null && oleDonorList.size() > 0) { OLEDonor oleDonor = oleDonorList.get(0); if (oleDonor != null) { for (OLELinkPurapDonor oleLinkPurapDonor : item.getOleDonors()) { if (oleLinkPurapDonor.getDonorCode().equalsIgnoreCase(item.getDonorCode())) { flag = false; GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OLEConstants.DONOR_CODE_EXISTS, new String[]{}); return mapping.findForward(OLEConstants.MAPPING_BASIC); } } if (flag) { OLELinkPurapDonor donor = new OLELinkPurapDonor(); donor.setDonorId(oleDonor.getDonorId()); donor.setDonorCode(oleDonor.getDonorCode()); item.getOleDonors().add(donor); item.setDonorCode(null); } } } else { GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OLEConstants.ERROR_DONOR_CODE, new String[]{}); } } return mapping.findForward(OLEConstants.MAPPING_BASIC); } private LookupService getLookupService() { return KRADServiceLocatorWeb.getLookupService(); } public ActionForward deleteDonor(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { OleLineItemReceivingForm oleLineItemReceivingForm = (OleLineItemReceivingForm) form; OleLineItemReceivingDocument receiveDocument = (OleLineItemReceivingDocument) oleLineItemReceivingForm.getDocument(); String[] indexes = getSelectedLineForAccounts(request); int itemIndex = Integer.parseInt(indexes[0]); int donorIndex = Integer.parseInt(indexes[1]); OleLineItemReceivingItem item = (OleLineItemReceivingItem) receiveDocument.getItem((itemIndex)); item.getOleDonors().remove(donorIndex); return mapping.findForward(OLEConstants.MAPPING_BASIC); } }
jbreck/duet-jbreck
test/chora/benchmarks/icrasuite/frankenstein/relational/AGHKTW2017_loginSafe.c
<gh_stars>1-10 #include "assert.h" /* Source: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>: Decomposition Instead of Self-Composition for Proving the Absence of Timing Channels. PLDI 2017 */ int loginSafe(char *password, int password_len, char* guess, int guess_len) { int matches = 1; int tick = 0; for (int i = 0; i < guess_len; i++) { tick++; if (i < password_len) { if (password[i] != guess[i]) { matches = 0; } } } // return matches; return tick; } void main() { int password_len1 = __VERIFIER_nondet_int();; int password_len2 = __VERIFIER_nondet_int();; int guess_len = __VERIFIER_nondet_int();; __VERIFIER_assume(password_len1 >= 0); __VERIFIER_assume(password_len2 >= 0); __VERIFIER_assume(guess_len >= 0); char* password1 = malloc(password_len1); char* password2 = malloc(password_len2); char* guess = malloc(guess_len); __VERIFIER_assert(loginSafe(password1,password_len1,guess,guess_len) == loginSafe(password2,password_len2,guess,guess_len)); }
jeroen/homebrew-core
Formula/autojump.rb
<gh_stars>1-10 class Autojump < Formula desc "Shell extension to jump to frequently used directories" homepage "https://github.com/wting/autojump" url "https://github.com/wting/autojump/archive/release-v22.5.1.tar.gz" sha256 "765fabda130eb4df70d1c1e5bc172e1d18f8ec22c6b89ff98f1674335292e99f" head "https://github.com/wting/autojump.git" bottle do cellar :any_skip_relocation # sha256 "80aef4fa4699bad12cae0c1a6d6db2632d15c13b503796db5c9889f7b43a3279" => :mojave sha256 "8e302e0a90b898349749c4b83b3c758f4af76ad415f6ac5e245cc0df9c2c90e6" => :high_sierra sha256 "29d37b9fc31a978d0767c4925e88fa9fe3cebf4a9f9278fa82a96baf5caa0db4" => :sierra sha256 "29d37b9fc31a978d0767c4925e88fa9fe3cebf4a9f9278fa82a96baf5caa0db4" => :el_capitan sha256 "29d37b9fc31a978d0767c4925e88fa9fe3cebf4a9f9278fa82a96baf5caa0db4" => :yosemite end def install system "./install.py", "-d", prefix, "-z", zsh_completion # Backwards compatibility for users that have the old path in .bash_profile # or .zshrc (prefix/"etc").install_symlink prefix/"etc/profile.d/autojump.sh" libexec.install bin bin.write_exec_script libexec/"bin/autojump" end def caveats; <<~EOS Add the following line to your ~/.bash_profile or ~/.zshrc file (and remember to source the file to update your current session): [ -f #{etc}/profile.d/autojump.sh ] && . #{etc}/profile.d/autojump.sh If you use the Fish shell then add the following line to your ~/.config/fish/config.fish: [ -f #{HOMEBREW_PREFIX}/share/autojump/autojump.fish ]; and source #{HOMEBREW_PREFIX}/share/autojump/autojump.fish EOS end test do path = testpath/"foo/bar" path.mkpath output = ` source #{etc}/profile.d/autojump.sh j -a "#{path.relative_path_from(testpath)}" j foo >/dev/null pwd `.strip assert_equal path.realpath.to_s, output end end
yashpatil/GTAS
gtas-parent/gtas-loader/src/test/java/gov/gtas/services/PnrGen.java
<filename>gtas-parent/gtas-loader/src/test/java/gov/gtas/services/PnrGen.java<gh_stars>10-100 /* * All GTAS code is Copyright 2016, The Department of Homeland Security (DHS), U.S. Customs and Border Protection (CBP). * * Please see LICENSE.txt for details. */ package gov.gtas.services; import gov.gtas.dto.FlightDto; import gov.gtas.dto.PaxDto; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PnrGen { private static final Logger logger = LoggerFactory.getLogger(PnrGen.class); private static String newline = System.getProperty("line.separator"); // private static StringBuilder sb=new StringBuilder(); private static String mNum = "0" + GenUtil.getRandomNumber(999) + "A" + GenUtil.getRandomNumber(999); // private static List<FlightDto> flights=new ArrayList<FlightDto>(); private static LoaderUtils lu = new LoaderUtils(); public static void buildHeader(String code, StringBuilder sb) { sb.append("UNA:+.?*'" + newline); sb.append("UNB+IATA:1+"); sb.append(code); sb.append("++"); sb.append(GenUtil.getDate()); sb.append("+" + mNum + "'" + newline); sb.append("UNH+1+PNRGOV:10:1:IA+F6C2C268'"); } public static void buildMessage(String code, StringBuilder sb) { if (code.equals("22")) { sb.append("MSG+:22'"); } else { sb.append("MSG+:" + code); sb.append("'"); } } public static void buildOrigDestinations(String carrier, String orig, String dest, String flightNumber, String date, StringBuilder sb) { sb.append("ORG+"); sb.append(carrier + ":"); sb.append(orig); sb.append("+52519950'" + newline); sb.append("TVL+"); sb.append(GenUtil.getDepArlTime(6) + ":" + GenUtil.getDepArlTime(2) + "+"); sb.append(orig + "+" + dest + "+" + carrier + "+" + flightNumber + "'"); } public static void buildEqn(int numPax, StringBuilder sb) { sb.append("EQN+" + numPax + "'"); } public static void buildPassenger(String carrier, String orig, String dest, String flightNumber, String date, int numPax, StringBuilder sb, FlightDto dto) { String add = GenUtil.getSponsorAddress(); String ph = GenUtil.getPhoneNumber(); String lName = GenUtil.getLastName(); List<String> ssrs = new ArrayList<>(); PaxDto pDto = new PaxDto(); String bDate = GenUtil.getBirthDate(); String fName = GenUtil.getFirstName(); for (int i = 1; i <= numPax; i++) { if (numPax == 1) { pDto = (PaxDto) GenUtil.getPaxDto(); pDto.setEmbark(orig); pDto.setDebark(dest); bDate = pDto.getDob(); lName = pDto.getLastName(); fName = pDto.getFirstName(); // logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>------"+lName); // logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>------"+fName); } String id = "" + GenUtil.getRandomNumber(9999); pDto.setFirstName(fName); pDto.setLastName(lName); pDto.setEmbark(orig); pDto.setDebark(dest); // TIF+DYE+KAYLAMS:A:43578:1' sb.append("TIF+" + lName + "+" + fName + ":A:" + id + ":" + i + "'" + newline); sb.append("FTI+" + carrier + ":8" + GenUtil.getRandomNumber(999999) + ":::ELITE'" + newline); sb.append("IFT+4:15:9+" + orig + " " + carrier + " X/" + dest + " " + carrier + " GBP/IT END ROE0." + GenUtil.getRandomNumber(999) + "'" + newline); sb.append("REF+:" + GenUtil.getRandomNumber(999999999) + "P'" + newline); sb.append("FAR+N+++++MIL24'" + newline); String country = GenUtil.getCountryCode(); pDto.setDocNumber(GenUtil.getRandomNumber(9999999)); sb.append("SSR+DOCS:HK::" + carrier + ":::::/P/" + country + "/" + pDto.getDocNumber() + "/" + country + "/" + bDate + "/" + GenUtil.getGender() + "/" + GenUtil.getExpiryDate() + "/" + lName + "/" + fName + "'" + newline); String s = "SSR+SEAT:HK:" + i + ":" + carrier + ":::" + orig + ":" + dest + "+" + GenUtil.getRandomNumber(99) + "A" + "::" + id + ":N'" + newline; ssrs.add(s); sb.append("SSR+AVML:HK:" + i + ":" + carrier + "'" + newline); sb.append("TKT+30" + GenUtil.getRandomNumber(999999999) + ":T:1'" + newline); sb.append("MON+B:" + GenUtil.getRandomNumber(9999) + ".00:USD+T:" + GenUtil.getRandomNumber(9999) + ".94:USD'" + newline); sb.append("PTK+NR++" + date + "+" + carrier + "+006+" + orig + "'" + newline); sb.append("TXD++6.10::USD'" + newline); sb.append("DAT+710:" + date + "'" + newline); sb.append("FOP+CC:::" + GenUtil.getCcNum() + newline); sb.append("IFT+4:43+" + lName + " " + fName + "+" + add + "+" + ph + "'" + newline); dto.getPaxList().add(pDto); } dto.setStartDate(GenUtil.getDepArlTime(1)); dto.setEndDate(GenUtil.getDepArlTime(6)); sb.append("TVL+" + dto.getStartDate() + ":" + dto.getEndDate() + "+" + orig + "+" + dest + "+" + carrier + "+" + flightNumber + ":B'" + newline); sb.append("RPI+" + numPax + "HK'" + newline); sb.append("APD+7" + GenUtil.getRandomNumber(9) + "7'" + newline); for (String s : ssrs) { sb.append(s); } } public static void buildPaxRecord(FlightDto dto, PaxDto pax, StringBuilder sb) { String add = GenUtil.getSponsorAddress(); String ph = GenUtil.getPhoneNumber(); List<String> ssrs = new ArrayList<>(); pax.setEmbark(dto.getEmbark()); pax.setDebark(dto.getDebark()); pax.setDocNumber(GenUtil.getRandomNumber(9999999)); String id = "" + GenUtil.getRandomNumber(9999); sb.append( "TIF+" + pax.getLastName() + "+" + pax.getFirstName() + ":A:" + id + ":" + pax.getId() + "'" + newline); sb.append("FTI+" + dto.getCarrier() + ":8" + GenUtil.getRandomNumber(999999) + ":::ELITE'" + newline); sb.append("IFT+4:28+" + dto.getCarrier() + "+CTCT ATL " + ph + " STA TRAVEL'" + newline); sb.append("IFT+4:15:9+" + dto.getEmbark() + " " + dto.getCarrier() + " X/" + dto.getDebark() + " " + dto.getCarrier() + " GBP/IT END ROE0." + GenUtil.getRandomNumber(999) + "'" + newline); sb.append("REF+:" + GenUtil.getRandomNumber(999999999) + "P'" + newline); sb.append("FAR+N+++++MIL24'" + newline); String country = GenUtil.getCountryCode(); sb.append("SSR+DOCS:HK::" + dto.getCarrier() + ":::::/P/" + country + "/" + pax.getDocNumber() + "/" + country + "/" + pax.getDob() + "/" + GenUtil.getGender() + "/" + GenUtil.getExpiryDate() + "/" + pax.getLastName() + "/" + pax.getFirstName() + "'" + newline); String s = "SSR+SEAT:HK:" + pax.getId() + ":" + dto.getCarrier() + ":::" + dto.getEmbark() + ":" + dto.getDebark() + "+" + GenUtil.getRandomNumber(300) + "A" + "::" + id + ":N'" + newline; ssrs.add(s); sb.append("SSR+AVML:HK:" + pax.getId() + ":" + dto.getCarrier() + "'" + newline); sb.append("TKT+30" + GenUtil.getRandomNumber(999999999) + ":T:1'" + newline); sb.append("MON+B:" + GenUtil.getRandomNumber(9999) + ".00:USD+T:" + GenUtil.getRandomNumber(9999) + ".94:USD'" + newline); sb.append("PTK+NR++" + dto.getToDay() + "+" + dto.getCarrier() + "+006+" + dto.getEmbark() + "'" + newline); sb.append("TXD++6.10::USD'" + newline); sb.append("DAT+710:" + dto.getToDay() + "'" + newline); sb.append("FOP+CC:::" + GenUtil.getCcNum() + newline); sb.append("IFT+4:28+" + dto.getCarrier() + "+CTCT ATL " + ph + " STA TRAVEL'" + newline); // sb.append("IFT+4:43+"+pax.getLastName()+" // "+pax.getFirstName()+"+"+add+"+"+ph+"'"+newline); dto.setStartDate(GenUtil.getDepArlTime(1)); dto.setEndDate(GenUtil.getDepArlTime(6)); sb.append("TVL+" + dto.getStartDate() + ":" + dto.getEndDate() + "+" + dto.getEmbark() + "+" + dto.getDebark() + "+" + dto.getCarrier() + "+" + dto.getFlightNum() + ":B'" + newline); sb.append("RPI+" + 1 + "HK'" + newline); sb.append("APD+7" + GenUtil.getRandomNumber(9) + "7'" + newline); for (String ss : ssrs) { sb.append(ss); } } public static void buildPnrSrcData(FlightDto dto, PaxDto pax, StringBuilder sb) { String add = GenUtil.getAddress(); String ph = GenUtil.getPhoneNumber(); sb.append("SRC'" + newline); // RCI+TZ:W9TEND::230513:181348' // RCI+UJ:GCJ9936::071116:094236' sb.append("RCI+" + dto.getCarrier() + ":" + GenUtil.getRecordLocator() + "::" + GenUtil.getPnrCreateDate() + "'" + newline); sb.append("SSR+AVML:HK:2:" + dto.getCarrier() + "'" + newline); sb.append("DAT+700:" + GenUtil.getDate() + "+710:" + GenUtil.getTicketDate() + "'" + newline); // sb.append("IFT+4:28::"+dto.getCarrier()+"+THIS PASSENGER IS A VIP'"+newline); sb.append("IFT+4:28::" + dto.getCarrier() + "+CTCR " + ph + "'" + newline); // IFT+4:28+TN CTCT AKL 64 9 309 9723 STA TRAVEL sb.append("IFT+4:28::" + dto.getCarrier() + "+CTCT ATL " + ph + " STA TRAVEL'" + newline); sb.append("ORG+" + dto.getCarrier() + ":" + dto.getEmbark() + "+52519950:LON+++A+GB:GBP+D050517'" + newline); sb.append("ADD++" + add + "'" + newline); sb.append("EBD+USD:40.00+1::N'" + newline); buildPaxRecord(dto, pax, sb); } public static void buildSrc(String carrier, String orig, String dest, String flightNumber, String date, int numPax, FlightDto dto, StringBuilder sb) { String add = GenUtil.getAddress(); String ph = GenUtil.getPhoneNumber(); sb.append("SRC'" + newline); sb.append("RCI+" + carrier + ":" + GenUtil.getRecordLocator() + "'" + newline); sb.append("SSR+AVML:HK:2:" + carrier + "'" + newline); sb.append("DAT+700:" + GenUtil.getDate() + "+710:" + GenUtil.getTicketDate() + "'" + newline); // sb.append("IFT+4:28::"+carrier+"+THIS PASSENGER IS A VIP'"+newline); // sb.append("IFT+4:28::"+carrier+"+CTCR "+ph+"'"+newline); sb.append("ORG+" + carrier + ":" + orig + "+52519950:LON+++A+GB:GBP+D050517'" + newline); sb.append("ADD++" + add + "'" + newline); sb.append("EBD+USD:40.00+1::N'" + newline); buildPassenger(carrier, orig, dest, flightNumber, date, numPax, sb, dto); } public static void buildFooter(StringBuilder sb) { sb.append("UNT+135+1'" + newline); sb.append("UNZ+1+" + mNum + "'" + newline); } public static void writeToFile(int num, StringBuilder sb) { String fileName = "C:\\PNR" + "\\pnr" + num + ".txt"; logger.info("Writing to file" + fileName); try { String content = sb.toString(); File pnrFile = new File(fileName); if (!pnrFile.exists()) { pnrFile.createNewFile(); } FileWriter fw = new FileWriter(pnrFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } catch (Exception e) { logger.info("Exception writing test to file", e); } } public static StringBuilder buildApisHeader(StringBuilder sb, FlightDto fd) { sb.append("UNA:+.? '" + newline); // UNB+UNOA:4+SHARES:UA+USCSAPIS+140201:1500+1402011500++APIS' sb.append("UNB+UNOA:4+SHARES:"); sb.append(fd.getEmbarkCountry() + "+USCSAPIS+140201:1500+1402011500++APIS'" + newline);// YYMMDD // UNG+PAXLST+UNITED AIRLINES INC:UA+USCSAPIS+140201:1500+1402011500+UN+D:02B' // UNG *PAXLST*AMERICAN AIRLINES:ZZ*JMAPIS:ZZ*140211:1800*1402111800*UN*D:02B$ sb.append("UNG+PAXLST+UNITED AIRLINES INC:UA+USCSAPIS+140201:1500+1402011500+UN+D:02B'" + newline); // UNH+UA0138-140201C+PAXLST:D:02B:UN:IATA++02:F' sb.append("UNH+1402111800+PAXLST:D:02B:UN:IATA++02:F'" + newline); // BGM+250+C'NAD+MS+++UNITED HELP DESK' // BGM*745$""" sb.append("BGM+745'" + newline); return sb; } public static StringBuilder buildApisReportingParty(StringBuilder sb) { // NAD+MS+++UNITED HELP DESK' // COM*918-833-3535:TE*918-292-7090:FX$""" // COM+832-235-1556:TE+281-553-1491:FX' sb.append("NAD+MS+++UNITED HELP DESK'" + newline); sb.append("COM+832-235-1556:TE+281-553-1491:FX'" + newline); return sb; } public static StringBuilder buildApisFlight(StringBuilder sb, FlightDto fd) { // TDT*20*{0}{1}$ // TDT+20+UA0138' sb.append("TDT+20+"); sb.append(fd.getCarrier() + fd.getFlightNum() + "'" + newline); // LOC+125+NRT' // LOC+125+LAS'DTM+189:1401312330:201'LOC+87+YYZ' sb.append("LOC+125+" + fd.getEmbark() + "'"); sb.append("DTM+189:" + GenUtil.getYYMMDD(-1) + ":201'" + newline); // DTM+189:1401312330:201' // DTM+232:1401310642:201' sb.append("LOC+87+" + fd.getDebark() + "'" + newline); sb.append("DTM+232:" + GenUtil.getYYMMDD(5) + ":201'" + newline); return sb; } public static StringBuilder buildPaxList(StringBuilder sb, PaxDto pd, FlightDto fd) { // NAD NAD+FL+++DOE:JOHN:WAYNE+20 MAIN STREET+ANYCITY+VA+10053+USA // NAD*FL***{0}:{1}:$ String mName = ""; if (StringUtils.isNotEmpty(pd.getMiddleName())) { mName = pd.getMiddleName(); } sb.append("NAD+FL+++" + pd.getLastName() + ":" + pd.getFirstName() + ":" + mName + "+" + GenUtil.getPaxAddress() + "'" + newline); // ATT // ATT*2**M$ ATT+2++M sb.append("ATT+2++" + GenUtil.getGender() + "'" + newline); // DTM DTM*329:541016$ sb.append("DTM+329:" + GenUtil.getApisPaxBirthday(pd.getDob()) + "'" + newline); // LOC LOC*178*{2}$ // LOC*179*{3}$ sb.append("LOC+178+" + fd.getEmbark() + "'" + newline); sb.append("LOC+179+" + fd.getDebark() + "'" + newline); sb.append("LOC+174+" + fd.getEmbarkCountry() + "'" + newline); // NAT NAT*2*USA$ sb.append("NAT+2+USA'" + newline); // RFF*AVF:QXGYLO$ sb.append("RFF+AVF:" + "QXGYLO" + GenUtil.getRandomNumber(999) + "'" + newline); // DOC DOC+P:110:111+MB140241 DOC*P:110:111*{4}$ sb.append("DOC+P:110:111+" + pd.getDocNumber() + "'" + newline); // DTM DTM*36:180221$ DTM+36:081021 sb.append("DTM+36:181022'" + newline); // LOC LOC*91*USA$""" sb.append("LOC+91+" + fd.getEmbarkCountry() + "'" + newline); return sb; } public static void buildApisFooter(StringBuilder sb) { sb.append("CNT+42:136'" + newline); sb.append("UNT+121+1402111800'" + newline); sb.append("UNE+1+1402111800'" + newline); sb.append("UNZ+1+1402111800'" + newline); } public static void buildApisMessages(List<FlightDto> flights, int counter) { counter = 1; int j = 0; for (FlightDto fd : flights) { j++; for (int i = 0; i < fd.getPaxList().size(); i++) { PaxDto pd = (PaxDto) fd.getPaxList().get(i); counter = counter * j + i; StringBuilder sb = new StringBuilder(); buildApisHeader(sb, fd); buildApisReportingParty(sb); buildApisFlight(sb, fd); buildPaxList(sb, pd, fd); buildApisFooter(sb); writeToApisFile(counter, sb); sb = null; } } } public static void writeToApisFile(int num, StringBuilder sb) { String fileName = "C:\\PNR" + "\\apis" + num + ".txt"; logger.info("Writing to file" + fileName); try { String content = sb.toString(); File apisFile = new File(fileName); if (!apisFile.exists()) { apisFile.createNewFile(); } FileWriter fw = new FileWriter(apisFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } catch (Exception e) { logger.info("Exception writing APIS to file", e); } } // run it from MessageGeneratorIT classs // public static void main(String[] args) { // for(int i=56;i <=57;i++){ // FlightDto dto = new FlightDto(); // StringBuilder sb = new StringBuilder(); // String carrier=GenUtil.getCarrier(); // String origin=GenUtil.getAirport(); // String dest=GenUtil.getAirport(); // String fNumber=GenUtil.getFlightNumber(); // String dString=GenUtil.getPnrDate(); // int numPax=GenUtil.getRandomNumber(3)+2; // dto.setCarrier(carrier); // dto.setDebark(dest); // dto.setEmbark(origin); // dto.setFlightNum(fNumber); // // buildHeader(carrier,sb); // buildMessage("22", sb); // buildOrigDestinations(carrier, origin,dest,fNumber,dString, sb); // buildEqn(numPax,sb); // buildSrc(carrier, origin,dest,fNumber,dString,numPax,dto,sb); // buildFooter(sb); // //flights.add(dto); // logger.info(sb.toString()); // //writeToFile(i,sb); // sb=null; // } // //buildApisMessages(); // } }
pramodbiligiri/datahub
li-utils/src/main/javaPegasus/com/linkedin/common/urn/AzkabanFlowUrn.java
package com.linkedin.common.urn; import com.linkedin.data.template.Custom; import com.linkedin.data.template.DirectCoercer; import com.linkedin.data.template.TemplateOutputCastException; import java.net.URISyntaxException; public final class AzkabanFlowUrn extends Urn { public static final String ENTITY_TYPE = "azkabanFlow"; private final String _cluster; private final String _project; private final String _flowId; public AzkabanFlowUrn(String cluster, String project, String flowId) { super(ENTITY_TYPE, TupleKey.create(cluster, project, flowId)); this._cluster = cluster; this._project = project; this._flowId = flowId; } public String getClusterEntity() { return _cluster; } public String getProjectEntity() { return _project; } public String getFlowIdEntity() { return _flowId; } public static AzkabanFlowUrn createFromString(String rawUrn) throws URISyntaxException { return createFromUrn(Urn.createFromString(rawUrn)); } public static AzkabanFlowUrn createFromUrn(Urn urn) throws URISyntaxException { if (!"li".equals(urn.getNamespace())) { throw new URISyntaxException(urn.toString(), "Urn namespace type should be 'li'."); } else if (!ENTITY_TYPE.equals(urn.getEntityType())) { throw new URISyntaxException(urn.toString(), "Urn entity type should be 'azkabanFlow'."); } else { TupleKey key = urn.getEntityKey(); if (key.size() != 3) { throw new URISyntaxException(urn.toString(), "Invalid number of keys."); } else { try { return new AzkabanFlowUrn((String) key.getAs(0, String.class), (String) key.getAs(1, String.class), (String) key.getAs(2, String.class)); } catch (Exception e) { throw new URISyntaxException(urn.toString(), "Invalid URN Parameter: '" + e.getMessage()); } } } } public static AzkabanFlowUrn deserialize(String rawUrn) throws URISyntaxException { return createFromString(rawUrn); } static { Custom.registerCoercer(new DirectCoercer<AzkabanFlowUrn>() { public Object coerceInput(AzkabanFlowUrn object) throws ClassCastException { return object.toString(); } public AzkabanFlowUrn coerceOutput(Object object) throws TemplateOutputCastException { try { return AzkabanFlowUrn.createFromString((String) object); } catch (URISyntaxException e) { throw new TemplateOutputCastException("Invalid URN syntax: " + e.getMessage(), e); } } }, AzkabanFlowUrn.class); } }
hitjl/trino
testing/trino-product-tests/src/main/java/io/trino/tests/product/deltalake/TestDeltaLakeAlterTableCompatibility.java
<filename>testing/trino-product-tests/src/main/java/io/trino/tests/product/deltalake/TestDeltaLakeAlterTableCompatibility.java /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.tests.product.deltalake; import org.testng.annotations.Test; import static io.trino.tests.product.TestGroups.DELTA_LAKE_DATABRICKS; import static io.trino.tests.product.TestGroups.DELTA_LAKE_OSS; import static io.trino.tests.product.TestGroups.PROFILE_SPECIFIC_TESTS; import static io.trino.tests.product.deltalake.util.DeltaLakeTestUtils.getColumnCommentOnDelta; import static io.trino.tests.product.deltalake.util.DeltaLakeTestUtils.getColumnCommentOnTrino; import static io.trino.tests.product.hive.util.TemporaryHiveTable.randomTableSuffix; import static io.trino.tests.product.utils.QueryExecutors.onTrino; import static java.lang.String.format; import static org.testng.Assert.assertEquals; public class TestDeltaLakeAlterTableCompatibility extends BaseTestDeltaLakeS3Storage { @Test(groups = {DELTA_LAKE_DATABRICKS, DELTA_LAKE_OSS, PROFILE_SPECIFIC_TESTS}) public void testAddColumnWithCommentOnTrino() { String tableName = "test_dl_add_column_with_comment_" + randomTableSuffix(); String tableDirectory = "databricks-compatibility-test-" + tableName; onTrino().executeQuery(format("CREATE TABLE delta.default.%s (col INT) WITH (location = 's3://%s/%s')", tableName, bucketName, tableDirectory)); try { onTrino().executeQuery("ALTER TABLE delta.default." + tableName + " ADD COLUMN new_col INT COMMENT 'new column comment'"); assertEquals(getColumnCommentOnTrino("default", tableName, "new_col"), "new column comment"); assertEquals(getColumnCommentOnDelta("default", tableName, "new_col"), "new column comment"); } finally { onTrino().executeQuery("DROP TABLE delta.default." + tableName); } } }
IndexXuan/JobBest
public/bower_components/avalon/src/12 scanText.js
<gh_stars>1-10 var rfilters = /\|\s*(\w+)\s*(\([^)]*\))?/g, r11a = /\|\|/g, r11b = /U2hvcnRDaXJjdWl0/g, rlt = /&lt;/g, rgt = /&gt;/g function trimFilter(value, leach) { if (value.indexOf("|") > 0) { // 抽取过滤器 先替换掉所有短路与 value = value.replace(r11a, "U2hvcnRDaXJjdWl0") //btoa("ShortCircuit") value = value.replace(rfilters, function(c, d, e) { leach.push(d + (e || "")) return "" }) value = value.replace(r11b, "||") //还原短路与 } return value } function scanExpr(str) { var tokens = [], value, start = 0, stop do { stop = str.indexOf(openTag, start) if (stop === -1) { break } value = str.slice(start, stop) if (value) { // {{ 左边的文本 tokens.push({ value: value, expr: false }) } start = stop + openTag.length stop = str.indexOf(closeTag, start) if (stop === -1) { break } value = str.slice(start, stop) if (value) { //处理{{ }}插值表达式 var leach = [] value = trimFilter(value, leach) tokens.push({ value: value, expr: true, filters: leach.length ? leach : void 0 }) } start = stop + closeTag.length } while (1) value = str.slice(start) if (value) { //}} 右边的文本 tokens.push({ value: value, expr: false }) } return tokens } function scanText(textNode, vmodels) { var bindings = [] if (textNode.nodeType === 8) { var leach = [] var value = trimFilter(textNode.nodeValue, leach) var token = { expr: true, value: value } if (leach.length) { token.filters = leach } var tokens = [token] } else { tokens = scanExpr(textNode.data) } if (tokens.length) { for (var i = 0, token; token = tokens[i++]; ) { var node = DOC.createTextNode(token.value) //将文本转换为文本节点,并替换原来的文本节点 if (token.expr) { var filters = token.filters var binding = { type: "text", element: node, value: token.value, filters: filters } if (filters && filters.indexOf("html") !== -1) { avalon.Array.remove(filters, "html") binding.type = "html" binding.group = 1 if (!filters.length) { delete bindings.filters } } bindings.push(binding) //收集带有插值表达式的文本 } hyperspace.appendChild(node) } textNode.parentNode.replaceChild(hyperspace, textNode) if (bindings.length) executeBindings(bindings, vmodels) } }
hipstersmoothie/saasify
examples/typescript/meta-stock/lib/images.js
<filename>examples/typescript/meta-stock/lib/images.js<gh_stars>1000+ 'use strict' const pexels = require('./services/pexels') const pixabay = require('./services/pixabay') const unsplash = require('./services/unsplash') const multiProvider = require('./multi-provider') module.exports = multiProvider({ label: 'image', limit: 25, providers: [ { label: 'pexels', func: pexels }, { label: 'pixabay', func: pixabay.searchImages }, { label: 'unsplash', func: unsplash } ] })
kneubert/seqan
apps/alf/alf.cpp
// ========================================================================== // ALF - Alignment free sequence comparison // ========================================================================== // Copyright (c) 2006-2016, <NAME>, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== // Author: <NAME> <<EMAIL>> // ========================================================================== // Alignment free sequence comparison. // // This application can be used to calculate pairwise scores of DNA Sequences // without alignments. // // The following scores are implemented: N2, D2, D2Star, D2z. // ========================================================================== #include <iostream> #include <seqan/basic.h> #include <seqan/sequence.h> #include <seqan/seq_io.h> #include <seqan/misc/edit_environment.h> #include <seqan/arg_parse.h> #include <seqan/alignment_free.h> using namespace seqan; using namespace std; // TODO(holtgrew): Adapt parameters to naming conventions, i.e. use --parameter-name. int main(int argc, const char * argv[]) { // ----------------------------------------------------------------------- // Setup argument parser // ----------------------------------------------------------------------- seqan::ArgumentParser parser("alf"); // Set short description, version, date. setShortDescription(parser, "Alignment free sequence comparison"); setVersion(parser, SEQAN_APP_VERSION " [" SEQAN_REVISION "]"); setDate(parser, SEQAN_DATE); setCategory(parser, "Sequence Comparison"); // Usage line and description. addUsageLine(parser, "[\\fIOPTIONS\\fP] \\fB-i\\fP \\fIIN.FASTA\\fP [\\fB-o\\fP \\fIOUT.TXT\\fP]"); addDescription(parser, "Compute pairwise similarity of sequences using alignment-free methods in \\fIIN.FASTA\\fP and write out tab-delimited matrix with pairwise scores to \\fIOUT.TXT\\fP."); addOption(parser, seqan::ArgParseOption("v", "verbose", "When given, details about the progress are printed to the screen.")); // Options Section: Input / Output parameters. addSection(parser, "Input / Output"); addOption(parser, seqan::ArgParseOption("i", "input-file", "Name of the multi-FASTA input file.", seqan::ArgParseArgument::INPUT_FILE)); setValidValues(parser, "input-file", "fa fasta"); setRequired(parser, "input-file"); addOption(parser, seqan::ArgParseOption("o", "output-file", "Name of the file to which the tab-delimtied matrix with pairwise scores will be written to. Default is to write to stdout.", seqan::ArgParseArgument::OUTPUT_FILE)); setValidValues(parser, "output-file", "alf.tsv"); addSection(parser, "General Algorithm Parameters"); addOption(parser, seqan::ArgParseOption("m", "method", "Select method to use.", seqan::ArgParseArgument::STRING, "METHOD")); setValidValues(parser, "method", "N2 D2 D2Star D2z"); setDefaultValue(parser, "method", "N2"); addOption(parser, seqan::ArgParseOption("k", "k-mer-size", "Size of the k-mers.", seqan::ArgParseArgument::INTEGER, "K")); setDefaultValue(parser, "k-mer-size", "4"); addOption(parser, seqan::ArgParseOption("mo", "bg-model-order", "Order of background Markov Model.", seqan::ArgParseArgument::INTEGER, "ORDER")); setDefaultValue(parser, "bg-model-order", "1"); addSection(parser, "N2 Algorithm Parameters"); // addText(parser, "The following parameters are only used in the N2 algorithm."); addOption(parser, seqan::ArgParseOption("rc", "reverse-complement", "Which strand to score. Use \\fIboth_strands\\fP to score both strands simultaneously.", seqan::ArgParseArgument::STRING, "MODE")); setValidValues(parser, "reverse-complement", "input both_strands mean min max"); setDefaultValue(parser, "reverse-complement", "input"); addOption(parser, seqan::ArgParseOption("mm", "mismatches", "Number of mismatches, one of \\fI0\\fP and \\fI1\\fP. When \\fI1\\fP is used, N2 uses the k-mer-neighbour with one mismatch.", seqan::ArgParseArgument::INTEGER, "MISMATCHES")); setDefaultValue(parser, "mismatches", "0"); addOption(parser, seqan::ArgParseOption("mmw", "mismatch-weight", "Real-valued weight of counts for words with mismatches.", seqan::ArgParseArgument::DOUBLE, "WEIGHT")); setDefaultValue(parser, "mismatch-weight", "0.1"); addOption(parser, seqan::ArgParseOption("kwf", "k-mer-weights-file", "Print k-mer weights for every sequence to this file if given.", seqan::ArgParseArgument::OUTPUT_FILE, "FILE.TXT")); setValidValues(parser, "k-mer-weights-file", "txt"); addTextSection(parser, "Contact and References"); addListItem(parser, "For questions or comments, contact:", "<NAME> <<EMAIL>>"); addListItem(parser, "Please reference the following publication if you used ALF or the N2 method for your analysis:", "<NAME>, <NAME>, <NAME>, and <NAME>. Estimation of Pairwise Sequence Similarity of Mammalian Enhancers with Word Neighbourhood Counts. Bioinformatics (2012)."); addListItem(parser, "Project Homepage:", "http://www.seqan.de/projects/alf"); // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // Only extract options if the program will continue after parseCommandLine() if (res != seqan::ArgumentParser::PARSE_OK) return (res == seqan::ArgumentParser::PARSE_ERROR); // Declare all parameters String<char> kmerWeightsFileTmp; String<char> inFileTmp; String<char> outFileTmp; getOptionValue(inFileTmp, parser, "input-file"); String<char, CStyle> inFile = inFileTmp; getOptionValue(outFileTmp, parser, "output-file"); String<char, CStyle> outFile = outFileTmp; String<char> method; getOptionValue(method, parser, "method"); int kmerSize = 0; getOptionValue(kmerSize, parser, "k-mer-size"); int bgModelOrder = 1; getOptionValue(bgModelOrder, parser, "bg-model-order"); String<char> revComp; getOptionValue(revComp, parser, "reverse-complement"); if (revComp == "input") clear(revComp); unsigned mismatches = 0; getOptionValue(mismatches, parser, "mm"); double mismatchWeight = 0.1; getOptionValue(mismatchWeight, parser, "mmw"); String<char, CStyle> kmerWeightsFile; getOptionValue(kmerWeightsFileTmp, parser, "k-mer-weights-file"); kmerWeightsFile = kmerWeightsFileTmp; bool verbose = isSet(parser, "verbose"); // Definition of type DNA string sets typedef String<Dna5> TText; typedef StringSet<TText> TStringSet; // Definition of mxn two-dimensional matrix typedef Matrix<double, 2> TMatrix; TMatrix myMatrix; // myMatrix stores pairwise kmerScores TStringSet mySequenceSet; // mySequenceSet stores all sequences from the multi-fasta file if (inFile != "") // read in file { SeqFileIn seqFile; open(seqFile, toCString(inFile)); StringSet<CharString> seqIDs; readRecords(seqIDs, mySequenceSet, seqFile); } // Dispatch to alignment free comparisons with different scores. if (method == "D2") { AFScore<D2> myScoreD2(kmerSize, verbose); alignmentFreeComparison(myMatrix, mySequenceSet, myScoreD2); } else if (method == "D2z") { AFScore<D2z> myScoreD2z(kmerSize, bgModelOrder, verbose); alignmentFreeComparison(myMatrix, mySequenceSet, myScoreD2z); } else if (method == "D2Star") { AFScore<D2Star> myScoreD2Star(kmerSize, bgModelOrder, verbose); alignmentFreeComparison(myMatrix, mySequenceSet, myScoreD2Star); } else if (method == "N2") { AFScore<N2> myScoreN2(kmerSize, bgModelOrder, revComp, mismatches, mismatchWeight, kmerWeightsFile, verbose); alignmentFreeComparison(myMatrix, mySequenceSet, myScoreN2); } // Write out resulting matrix; to file if file name was given, to stdout otherwise. if (!empty(outFile)) { ofstream myfile(outFile, std::ios::binary | std::ios::out); myfile << myMatrix; myfile.close(); } else { std::cout << "\n" << myMatrix; } return 0; }
huaweicodelabs/SocialMediaApp
src/app/src/main/java/com/huawei/hms/socialappsharing/friends/FriendsSuggestionsListFragment.java
/* * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. 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.huawei.hms.socialappsharing.friends; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.huawei.agconnect.cloud.database.AGConnectCloudDB; import com.huawei.agconnect.cloud.database.CloudDBZone; import com.huawei.agconnect.cloud.database.CloudDBZoneConfig; import com.huawei.agconnect.cloud.database.CloudDBZoneObjectList; import com.huawei.agconnect.cloud.database.CloudDBZoneQuery; import com.huawei.agconnect.cloud.database.CloudDBZoneSnapshot; import com.huawei.agconnect.cloud.database.exceptions.AGConnectCloudDBException; import com.huawei.hmf.tasks.Task; import com.huawei.hms.socialappsharing.R; import com.huawei.hms.socialappsharing.main.PageViewModel; import com.huawei.hms.socialappsharing.models.Users; import com.huawei.hms.socialappsharing.utils.ObjectTypeInfoHelper; import com.huawei.hms.socialappsharing.utils.PreferenceHandler; import com.huawei.hms.socialappsharing.videoplayer.utils.LogUtil; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import static com.huawei.hms.socialappsharing.utils.CommonMember.networkStatusAlert; import static com.huawei.hms.socialappsharing.utils.CommonMember.dismissDialog; import static com.huawei.hms.socialappsharing.utils.CommonMember.isNetworkConnected; import static com.huawei.hms.socialappsharing.utils.CommonMember.showDialog; import static com.huawei.hms.socialappsharing.utils.Constants.DBNAME; import static com.huawei.hms.socialappsharing.utils.Constants.FRIENDS_LIST; import static com.huawei.hms.socialappsharing.utils.Constants.FRIENDS_REQUESTED_LIST; import static com.huawei.hms.socialappsharing.utils.Constants.NAME_VALUE_PAIRS; import static com.huawei.hms.socialappsharing.utils.Constants.USER_EMAIL; import static com.huawei.hms.socialappsharing.utils.Constants.VALUES; /** * This class loads the Friends Suggestion list of the user */ @SuppressLint("StaticFieldLeak") public class FriendsSuggestionsListFragment extends Fragment { private static final String ARG_SECTION_NUMBER = "section_number"; private static AGConnectCloudDB mCloudDB; private static CloudDBZone mCloudDBZone; private static String mCurrentUser; private static Context mContext; private static Activity mActivity; private static RecyclerView recyclerView; private static SwipeRefreshLayout swipeContainer; private static int mUserTotalListFromServer; private static ArrayList<UserModel> mUserModelArraylist; private static ArrayList<String> mFriendArraylist; private static ArrayList<String> mFriendRequestedArraylist; public static void sendData() { if (isNetworkConnected(mContext)) { showDialog(mActivity); cloudDBZoneCreation(); } else { dismissDialog(); networkStatusAlert(mContext); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PageViewModel pageViewModel = new ViewModelProvider(this).get(PageViewModel.class); int index = 1; if (getArguments() != null) { index = getArguments().getInt(ARG_SECTION_NUMBER); } pageViewModel.setIndex(index); } @Override public View onCreateView( @NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.feed_fragment, container, false); mContext = getContext(); mActivity = getActivity(); mCurrentUser = PreferenceHandler.getInstance(mContext).getEmailId(); recyclerView = view.findViewById(R.id.feed_recyclerView); LinearLayout createpostlayout = view.findViewById(R.id.create_post_layout); createpostlayout.setVisibility(View.GONE); recyclerView = view.findViewById(R.id.feed_recyclerView); // Lookup the swipe container view swipeContainer = view.findViewById(R.id.swipeContainer); // Setup refresh listener which triggers new data loading swipeContainer.setOnRefreshListener(() -> { if (isNetworkConnected(mContext)) { CloudDBZoneQuery<Users> mUserQuery = CloudDBZoneQuery.where(Users.class).equalTo(USER_EMAIL, mCurrentUser); queryUser(mUserQuery); } else { swipeContainer.setRefreshing(false); networkStatusAlert(mContext); } }); // Configure the refreshing colors swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); return view; } private void initiateTheCloud() { if (isNetworkConnected(mContext)) { AGConnectCloudDB.initialize(requireContext()); mCloudDB = AGConnectCloudDB.getInstance(); try { mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo()); } catch (AGConnectCloudDBException e) { dismissDialog(); LogUtil.e("Res error : ", e.getMessage()); } cloudDBZoneCreation(); } else { dismissDialog(); networkStatusAlert(mContext); } } private static void cloudDBZoneCreation() { CloudDBZoneConfig mConfig = new CloudDBZoneConfig(DBNAME, CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE, CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC); mConfig.setPersistenceEnabled(true); Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true); openDBZoneTask.addOnSuccessListener(cloudDBZone -> { mCloudDBZone = cloudDBZone; CloudDBZoneQuery<Users> mUserQuery = CloudDBZoneQuery.where(Users.class).equalTo(USER_EMAIL, mCurrentUser); queryUser(mUserQuery); }).addOnFailureListener(e -> { dismissDialog(); swipeContainer.setRefreshing(false); }); } private static void queryUser(CloudDBZoneQuery<Users> query) { if (mCloudDBZone == null) { dismissDialog(); return; } Task<CloudDBZoneSnapshot<Users>> queryTask = mCloudDBZone.executeQuery(query, CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY); queryTask.addOnSuccessListener(FriendsSuggestionsListFragment::processQueryResult).addOnFailureListener(e -> { dismissDialog(); swipeContainer.setRefreshing(false); }); } private static void processQueryResult(CloudDBZoneSnapshot<Users> snapshot) { CloudDBZoneObjectList<Users> userInfoCursor = snapshot.getSnapshotObjects(); try { while (userInfoCursor.hasNext()) { Users mUsers = userInfoCursor.next(); mFriendArraylist = new ArrayList<>(); mFriendRequestedArraylist = new ArrayList<>(); String mFriendList = mUsers.getFriendsList(); if (mFriendList != null) { JSONObject jsonRootObject = new JSONObject(mFriendList); JSONObject jobj = jsonRootObject.getJSONObject(NAME_VALUE_PAIRS); JSONObject jobj1 = jobj.getJSONObject(FRIENDS_LIST); JSONArray jobj2 = jobj1.getJSONArray(VALUES); // Iterate the jsonArray and print the info of JSONObjects for (int i = 0; i < jobj2.length(); i++) { String mFriend = jobj2.getString(i); mFriendArraylist.add(mFriend); } } String mFriendRequestedList = mUsers.getFriendRequestedList(); if (mFriendRequestedList != null) { JSONObject jsonRootObject = new JSONObject(mFriendRequestedList); JSONObject jobj = jsonRootObject.getJSONObject(NAME_VALUE_PAIRS); JSONObject jobj1 = jobj.getJSONObject(FRIENDS_REQUESTED_LIST); JSONArray jobj2 = jobj1.getJSONArray(VALUES); // Iterate the jsonArray and print the info of JSONObjects for (int i = 0; i < jobj2.length(); i++) { String mFriend = jobj2.getString(i); mFriendRequestedArraylist.add(mFriend); } } queryAllUser(); } } catch (JSONException | AGConnectCloudDBException jsonException) { dismissDialog(); swipeContainer.setRefreshing(false); jsonException.printStackTrace(); } } private static void queryAllUser() { if (mCloudDBZone == null) { return; } Task<CloudDBZoneSnapshot<Users>> queryTask = mCloudDBZone.executeQuery(CloudDBZoneQuery.where(Users.class), CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY); queryTask.addOnSuccessListener(snapshot -> { mUserModelArraylist = new ArrayList<>(); mUserTotalListFromServer = snapshot.getSnapshotObjects().size(); for (int i = 0; i < mUserTotalListFromServer; i++) { try { String mUserEmail = snapshot.getSnapshotObjects().get(i).getUserEmail(); String mUserName = snapshot.getSnapshotObjects().get(i).getUserName(); String mProfileImage = snapshot.getSnapshotObjects().get(i).getUserImage(); String mFriendList = snapshot.getSnapshotObjects().get(i).getFriendsList(); String mFriendRequest = snapshot.getSnapshotObjects().get(i).getFriendRequestList(); String mToken = snapshot.getSnapshotObjects().get(i).getToken(); String mUserId = snapshot.getSnapshotObjects().get(i).getUserId(); String mNoOfFriends = snapshot.getSnapshotObjects().get(i).getNoOfFriends(); String mFriendRequested = snapshot.getSnapshotObjects().get(i).getFriendRequestedList(); String mCreatedDate = snapshot.getSnapshotObjects().get(i).getCreatedDate(); if (mFriendArraylist.size() == 0) { if (!mUserEmail.equals(mCurrentUser)) { if (!mUserId.equals(PreferenceHandler.getInstance(mContext).getUserId())) { mUserModelArraylist.add(new UserModel(mUserEmail, mUserName, mProfileImage, mFriendList, mFriendRequest, mToken, mUserId, mNoOfFriends, mFriendRequested, mCreatedDate)); } } } else { for (int j = 0; j < mFriendArraylist.size(); j++) { String mFriend = mFriendArraylist.get(j); if (!mUserEmail.equals(mFriend) && !mUserEmail.equals(mCurrentUser)) { if (!mUserId.equals(PreferenceHandler.getInstance(mContext).getUserId())) { mUserModelArraylist.add(new UserModel(mUserEmail, mUserName, mProfileImage, mFriendList, mFriendRequest, mToken, mUserId, mNoOfFriends, mFriendRequested, mCreatedDate)); } } } } } catch (AGConnectCloudDBException e) { dismissDialog(); LogUtil.e("Res error : ", e.getMessage()); } } dismissDialog(); swipeContainer.setRefreshing(false); LinearLayoutManager layoutManager = new LinearLayoutManager(mContext); FriendsSuggestionsListAdapter mItemAdapter = new FriendsSuggestionsListAdapter(mContext, mActivity, mUserModelArraylist, mCloudDBZone, mFriendRequestedArraylist); recyclerView.setAdapter(mItemAdapter); recyclerView.setLayoutManager(layoutManager); }).addOnFailureListener(e -> { swipeContainer.setRefreshing(false); }); } @Override public void onResume() { super.onResume(); if (isNetworkConnected(mContext)) { showDialog(getActivity()); if (mCloudDB == null) { initiateTheCloud(); } else { cloudDBZoneCreation(); } } else { dismissDialog(); networkStatusAlert(mContext); } } }
school-engagements/pikater-vaadin
src/org/pikater/web/experiment/IBoxInfoCommon.java
<reponame>school-engagements/pikater-vaadin package org.pikater.web.experiment; /** * Interface common for both client and server box definitions. * * @author SkyCrawl * * @param <I> The type for IDs. Typically Integers or Strings. */ public interface IBoxInfoCommon<I extends Object> { I getID(); void setID(I id); /** * Returns the box's X position in the experiment canvas. */ int getPosX(); /** * Sets the box's X position in the experiment canvas. */ void setPosX(int posX); /** * Returns the box's Y position in the experiment canvas. */ int getPosY(); /** * Sets the box's Y position in the experiment canvas. */ void setPosY(int posY); }
dram/metasfresh
backend/de.metas.business.rest-api-impl/src/main/java/de/metas/rest_api/v2/attachment/AttachmentRestService.java
/* * #%L * de.metas.business.rest-api-impl * %% * Copyright (C) 2021 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.rest_api.v2.attachment; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import de.metas.attachments.AttachmentEntry; import de.metas.attachments.AttachmentEntryCreateRequest; import de.metas.attachments.AttachmentEntryService; import de.metas.attachments.AttachmentTags; import de.metas.common.rest_api.v2.attachment.JsonAttachment; import de.metas.common.rest_api.v2.attachment.JsonAttachmentRequest; import de.metas.common.rest_api.v2.attachment.JsonAttachmentResponse; import de.metas.common.rest_api.v2.attachment.JsonExternalReferenceTarget; import de.metas.common.rest_api.v2.attachment.JsonTag; import de.metas.externalreference.ExternalIdentifier; import de.metas.externalreference.ExternalReferenceTypes; import de.metas.externalreference.IExternalReferenceType; import de.metas.externalreference.rest.ExternalReferenceRestControllerService; import de.metas.rest_api.utils.MetasfreshId; import de.metas.util.Check; import de.metas.util.Services; import de.metas.util.web.exception.InvalidIdentifierException; import de.metas.util.web.exception.MissingResourceException; import lombok.NonNull; import org.adempiere.ad.trx.api.ITrxManager; import org.adempiere.exceptions.AdempiereException; import org.adempiere.util.lang.impl.TableRecordReference; import org.compiere.util.MimeType; import org.springframework.stereotype.Service; import javax.annotation.Nullable; import java.util.Base64; import java.util.List; @Service public class AttachmentRestService { private final ITrxManager trxManager = Services.get(ITrxManager.class); private final AttachmentEntryService attachmentEntryService; private final ExternalReferenceRestControllerService externalReferenceService; private final ExternalReferenceTypes externalReferenceTypes; public AttachmentRestService( @NonNull final AttachmentEntryService attachmentEntryService, @NonNull final ExternalReferenceRestControllerService externalReferenceService, @NonNull final ExternalReferenceTypes externalReferenceTypes) { this.attachmentEntryService = attachmentEntryService; this.externalReferenceService = externalReferenceService; this.externalReferenceTypes = externalReferenceTypes; } @NonNull public JsonAttachmentResponse createAttachment(@NonNull final JsonAttachmentRequest jsonAttachmentRequest) { return trxManager.callInNewTrx(() -> createAttachmentWithTrx(jsonAttachmentRequest)); } @NonNull private JsonAttachmentResponse createAttachmentWithTrx(@NonNull final JsonAttachmentRequest jsonAttachmentRequest) { final String orgCode = jsonAttachmentRequest.getOrgCode(); final JsonAttachment attachment = jsonAttachmentRequest.getAttachment(); final AttachmentTags attachmentTags = extractAttachmentTags(attachment.getTags()); final byte[] data = Base64.getDecoder().decode(attachment.getData().getBytes()); final String contentType = attachment.getMimeType() != null ? attachment.getMimeType() : MimeType.getMimeType(attachment.getFileName()); final AttachmentEntryCreateRequest request = AttachmentEntryCreateRequest.builder() .type(AttachmentEntry.Type.Data) .filename(attachment.getFileName()) .contentType(contentType) .tags(attachmentTags) .data(data) .build(); final List<TableRecordReference> references = jsonAttachmentRequest.getTargets() .stream() .map(target -> extractTableRecordReference(orgCode, target)) .collect(ImmutableList.toImmutableList()); final AttachmentEntry entry = attachmentEntryService.createNewAttachment(references, request); return JsonAttachmentResponse.builder() .target(jsonAttachmentRequest.getTargets()) .attachmentId(String.valueOf(entry.getId().getRepoId())) .filename(entry.getFilename()) .mimeType(entry.getMimeType()) .build(); } @NonNull private TableRecordReference extractTableRecordReference( @NonNull final String orgCode, @NonNull final JsonExternalReferenceTarget target) { final IExternalReferenceType targetType = extractTargetType(target.getExternalReferenceType()); final MetasfreshId metasfreshId = extractTargetIdentifier(orgCode, target.getExternalReferenceIdentifier(), targetType); return TableRecordReference.of(targetType.getTableName(), metasfreshId.getValue()); } private MetasfreshId extractTargetIdentifier( @NonNull final String orgCode, @NonNull final String externalTargetIdentifier, @NonNull final IExternalReferenceType externalReferenceType) { final ExternalIdentifier targetIdentifier = ExternalIdentifier.of(externalTargetIdentifier); switch (targetIdentifier.getType()) { case METASFRESH_ID: return targetIdentifier.asMetasfreshId(); case EXTERNAL_REFERENCE: return externalReferenceService .getJsonMetasfreshIdFromExternalReference(orgCode, targetIdentifier, externalReferenceType) .map(MetasfreshId::of) .orElseThrow(() -> MissingResourceException.builder() .resourceIdentifier(targetIdentifier.getRawValue()) .resourceName(externalReferenceType.getTableName()) .build()); default: throw new InvalidIdentifierException(targetIdentifier.getRawValue()); } } @NonNull private IExternalReferenceType extractTargetType(@NonNull final String externalReferenceType) { return externalReferenceTypes.ofCode(externalReferenceType) .orElseThrow(() -> new AdempiereException("Unknown Type=") .appendParametersToMessage() .setParameter("externalReferenceType", externalReferenceType)); } @NonNull private AttachmentTags extractAttachmentTags(@Nullable final List<JsonTag> tags) { if (tags == null || Check.isEmpty(tags)) { return AttachmentTags.EMPTY; } final ImmutableMap<String, String> tagName2Value = tags.stream() .collect(ImmutableMap.toImmutableMap(JsonTag::getName, JsonTag::getValue)); return AttachmentTags.ofMap(tagName2Value); } }
vazir/go-m3ua
messages/params/status.go
<filename>messages/params/status.go // Copyright 2018-2020 go-m3ua authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package params // Status Type definitions. const ( AsStateChange uint16 = iota + 1 Other ) // Status Information definitions (StatusType==AsStateChange). // Note that this contains the type. const ( _ uint32 = uint32((0x01 << 16) | iota + 1) AsStateInactive AsStateActive AsStatePending ) // Status Information definitions (StatusType==Other). // Note that this contains the type. const ( InsufficientAspResources uint32 = uint32((0x02 << 16) | iota + 1) AlternateAspActive AspFailure ) // NewStatus creates the Status Parameter. // Note that this returns *Param, as no specific structure in this parameter. // The argument typeInfo can be chosen from Status Information definitions above. func NewStatus(typeInfo uint32) *Param { return newUint32ValParam(Status, typeInfo) } // Status returns multiple Status from Param. func (p *Param) Status() uint32 { if p.Tag != Status { return 0 } return p.decodeUint32ValData() } // StatusType returns multiple StatusType from Param. func (p *Param) StatusType() uint16 { if p.Tag != Status { return 0 } return uint16(p.decodeUint32ValData() >> 16) } // StatusInfo returns multiple StatusInfo from Param. func (p *Param) StatusInfo() uint16 { if p.Tag != Status { return 0 } return uint16(p.decodeUint32ValData() & 0xffff) }
rpiaggio/gsp-math
modules/tests/shared/src/test/scala/lucuma/core/model/PartnerSuite.scala
// Copyright (c) 2016-2021 Association of Universities for Research in Astronomy, Inc. (AURA) // For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause package lucuma.core.model import lucuma.core.util.arb._ import lucuma.core.util.laws.EnumeratedTests import munit._ final class PartnerSuite extends DisciplineSuite { import ArbEnumerated._ // Laws checkAll("Partner", EnumeratedTests[Partner].enumerated) }
CoderSong2015/Apache-Trafodion
core/sql/arkcmp/CmpErrLog.h
<reponame>CoderSong2015/Apache-Trafodion // *************************************************************************** // @@@ START COPYRIGHT @@@ // // 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. // // @@@ END COPYRIGHT @@@ // -*-C++-*- // *************************************************************************** // // File: CmpErrLog.h // Description: This file contains the definition of the CmpErrLog class. // This class is used for logging information to a file when // certain types of errors occur. It is used primarily for // logging memory errors, but may be used for other types of // errors too. // // This class is used by simply constructing a CmpErrLog // object. // // Created: 9/19/2008 // Language: C++ // // *************************************************************************** #ifndef _CMP_ERR_LOG_H #define _CMP_ERR_LOG_H #include "Platform.h" #include <sys/types.h> // Forward declarations class NAMemory; class NAHeap; typedef NAMemory CollHeap; class CmpErrLog { public: // CmpErrLog constructor. The "failedHeap" field below is a pointer // to the heap where a failure occurred. CmpErrLog(const char *failureTxt, CollHeap *failedHeap = 0, size_t size = 0); ~CmpErrLog(); // This function may be passed to NAMemory::setErrorCallback() to // allow logging to occur when a memory allocation failure occurs // in the NAMemory code. static void CmpErrLogCallback(NAHeap *heap, size_t userSize); private: void renameBigLogFile(const char *fileName); void openLogFile(); void closeLogFile(); void writeHeader(const char *failureTxt, CollHeap *failedHeap, size_t size); void writeMemoryStats(); void writeHeapInfo(CollHeap *heap); void writeAllHeapInfo(CollHeap *failedHeap); void writeCQDInfo(); void writeQueryInfo(); void writeStackTrace(); // Output file pointer FILE *fp; // Pointer to memory buffer that can be freed to allow memory needed // during logging to be allocated. static void *memPtr; }; #endif // _CMP_ERR_LOG_H
javipedrajo/uneat-c
materiales-clase/seccion_critica_threads_sem.c
<reponame>javipedrajo/uneat-c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <sys/types.h> #include <unistd.h> #include <semaphore.h> #include <fcntl.h> #define LIMITE 1000000 void *incrementa(); void *decrementa(); static int global_var=0; sem_t *mutex; int main() { pthread_t suma, resta; mutex=sem_open("/semaforo", O_CREAT, S_IRUSR | S_IWUSR, 1); pthread_create(&suma, NULL, &incrementa, NULL); pthread_create(&resta, NULL, &decrementa, NULL); pthread_join(resta, NULL); pthread_join(suma, NULL); printf("El valor final de la variable es %d\n", global_var); sem_close(mutex); sem_unlink("/semaforo"); return 0; } void *incrementa() { int i; puts("Comienza hilo suma\n"); for (i=0;i<LIMITE;i++) { sem_wait(mutex); global_var=global_var+1; sem_post(mutex); } printf("Suma: el valor final de la variable es %d\n", global_var); return 0; } void *decrementa() { int i; puts("Comienza hilo resta\n"); for (i=0;i<LIMITE;i++) { sem_wait(mutex); global_var=global_var-1; sem_post(mutex); } printf("resta:valor final de la variable es %d\n", global_var); return 0; }
Eshy10/health-app
src/components/measureCard/MeasureCard.styles.js
<filename>src/components/measureCard/MeasureCard.styles.js import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles({ root: { minWidth: 275, marginTop: '5em', }, bullet: { display: 'inline-block', margin: '0 2px', transform: 'scale(0.8)', }, title: { fontSize: 16, color: '#1c85d0', fontWeight: 'bold', textAlign: 'center', }, pos: { marginBottom: 12, }, }); export default useStyles;
kuldeepkeshwar/cosmos
core/components/molecules/pagination-toolbar/pagination-toolbar.story.js
import React from 'react' import { storiesOf } from '@storybook/react' import { Example } from '@auth0/cosmos/_helpers/story-helpers' import { PaginationToolbar } from '@auth0/cosmos' storiesOf('Pagination Toolbar', module).add('default', () => ( <Example> <PaginationToolbar items={20372} perPage={10} page={3} /> </Example> )) storiesOf('Pagination Toolbar', module).add('first page', () => ( <Example> <PaginationToolbar items={20372} perPage={10} page={1} /> </Example> )) storiesOf('Pagination Toolbar', module).add('last page', () => ( <Example> <PaginationToolbar items={20372} perPage={10} page={2038} /> </Example> )) storiesOf('Pagination Toolbar', module).add('not enough items', () => ( <Example> <div>toolbar should not be visible if there are not enough items for multiple pages</div> <PaginationToolbar items={5} perPage={10} /> <PaginationToolbar items={0} perPage={10} /> </Example> ))
cmbkoko1989/cloud-pipeline
client/src/components/billing/reports/filters/runner-filter.js
/* * Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.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. */ import React from 'react'; import {observer, inject} from 'mobx-react'; import {Select} from 'antd'; import UserName from '../../../special/UserName'; const RunnerType = { user: 'user', group: 'group' }; function runnerFilter ( { billingCenters: billingCentersRequest, onChange, filter, users: usersRequest } ) { const changeRunner = (key) => { if (key) { const [type, ...rest] = key.split('_'); onChange && onChange({id: rest.join('_'), type}); } else { onChange && onChange(null); } }; let users = []; if (usersRequest && usersRequest.loaded) { users = (usersRequest.value || []).map(u => u); } let centers = []; if (billingCentersRequest && billingCentersRequest.loaded) { centers = (billingCentersRequest.value || []).map(c => c); } let currentRunner; if (filter) { const {type, id} = filter; currentRunner = `${type}_${id}`; } return ( <Select allowClear style={{width: 200}} placeholder="All users / groups" value={currentRunner} onChange={changeRunner} > <Select.OptGroup label="Users"> { users.map((user) => ( <Select.Option key={`${RunnerType.user}_${user.id}`} value={`${RunnerType.user}_${user.id}`} > <UserName userName={user.userName} /> </Select.Option> )) } </Select.OptGroup> <Select.OptGroup label="Billing centers"> { centers.map((center) => ( <Select.Option key={`${RunnerType.group}_${center}`} value={`${RunnerType.group}_${center}`} > {center} </Select.Option> )) } </Select.OptGroup> </Select> ); } export default inject('billingCenters', 'users')(observer(runnerFilter)); export {RunnerType};
kj84park/armeria
oauth2/src/main/java/com/linecorp/armeria/server/auth/oauth2/OAuth2AuthorizationFailureHandler.java
/* * Copyright 2020 LINE Corporation * * LINE Corporation 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: * * 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. */ package com.linecorp.armeria.server.auth.oauth2; import static com.linecorp.armeria.server.auth.oauth2.OAuth2AuthorizationErrorReporter.badRequest; import static com.linecorp.armeria.server.auth.oauth2.OAuth2AuthorizationErrorReporter.forbidden; import static com.linecorp.armeria.server.auth.oauth2.OAuth2AuthorizationErrorReporter.unauthorized; import static com.linecorp.armeria.server.auth.oauth2.OAuth2TokenIntrospectionAuthorizer.ERROR_CODE; import static com.linecorp.armeria.server.auth.oauth2.OAuth2TokenIntrospectionAuthorizer.ERROR_TYPE; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.linecorp.armeria.common.HttpRequest; import com.linecorp.armeria.common.HttpResponse; import com.linecorp.armeria.common.HttpStatus; import com.linecorp.armeria.common.MediaType; import com.linecorp.armeria.server.HttpService; import com.linecorp.armeria.server.ServiceRequestContext; import com.linecorp.armeria.server.auth.AuthFailureHandler; import com.linecorp.armeria.server.auth.AuthServiceBuilder; import com.linecorp.armeria.server.auth.Authorizer; /** * A callback which is invoked to handle OAuth 2.0 authorization failure indicated by {@link Authorizer}. * Composes OAuth 2.0 authorization error response in one of the following ways: * <ul> * <li> * invalid_request * <p>The request is missing a required parameter, includes an * unsupported parameter or parameter value, repeats the same * parameter, uses more than one method for including an access * token, or is otherwise malformed. The resource server SHOULD * respond with the HTTP 400 (Bad Request) status code.</p> * Example: * <pre>{@code * HTTP/1.1 400 Bad Request * Content-Type: application/json;charset=UTF-8 * {"error":"unsupported_token_type"} * }</pre> * </li> * <li> * invalid_token * <p>The access token provided is expired, revoked, malformed, or * invalid for other reasons. The resource SHOULD respond with * the HTTP 401 (Unauthorized) status code. The client MAY * request a new access token and retry the protected resource * request.</p> * Example: * <pre>{@code * HTTP/1.1 401 Unauthorized * WWW-Authenticate: Bearer realm="example", * error="invalid_token", * scope="read write" * }</pre> * </li> * <li> * insufficient_scope * <p>The request requires higher privileges than provided by the * access token. The resource server SHOULD respond with the HTTP * 403 (Forbidden) status code and MAY include the "scope" * attribute with the scope necessary to access the protected * resource.</p> * Example: * <pre>{@code * HTTP/1.1 403 Forbidden * Content-Type: application/json;charset=UTF-8 * {"error":"insufficient_scope"} * }</pre> * </li> * </ul> * * @see AuthServiceBuilder#onFailure(AuthFailureHandler) */ class OAuth2AuthorizationFailureHandler implements AuthFailureHandler { static final Logger logger = LoggerFactory.getLogger(OAuth2AuthorizationFailureHandler.class); @Nullable private final String accessTokenType; @Nullable private final String realm; @Nullable private final String scope; /** * Constructs {@link OAuth2AuthorizationFailureHandler}. * @param accessTokenType type of the access token, {@code Bearer} used by default * @param realm optional security realm of an application or a service * @param scope optional JSON string containing a space-separated list of scopes associated with this token, * in the format described at * <a href="https://datatracker.ietf.org/doc/html/rfc6749#section-3.3">[RFC6749], Section 3.3</a>. * */ OAuth2AuthorizationFailureHandler(@Nullable String accessTokenType, @Nullable String realm, @Nullable String scope) { this.accessTokenType = accessTokenType; this.realm = realm; this.scope = scope; } /** * Invoked when the authorization of the specified {@link HttpRequest} has failed. * Composes OAuth 2.0 authorization error response of the following types: * <ul> * <li>invalid_request - 400 Bad Request</li> * <li>invalid_token - 401 Unauthorized</li> * <li>insufficient_scope - 403 Forbidden</li> * </ul> * as per <a href="https://datatracker.ietf.org/doc/html/rfc6750#rfc.section.3.1"> * The OAuth 2.0 Authorization Framework: Bearer Token Usage</a> */ @Override public HttpResponse authFailed(HttpService delegate, ServiceRequestContext ctx, HttpRequest req, @Nullable Throwable cause) throws Exception { if (cause != null) { if (logger.isWarnEnabled()) { logger.warn("Unexpected exception during OAuth 2 authorization.", cause); } return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR, MediaType.PLAIN_TEXT_UTF_8, "Unexpected exception during OAuth 2 authorization."); } // obtain ERROR_CODE and ERROR_TYPE from the context set by OAuth2TokenIntrospectionAuthorizer final Integer errorCode = ctx.attr(ERROR_CODE); final String errorType = ctx.attr(ERROR_TYPE); if (errorCode == null) { // something else happened - do not authorize // we may omit the expected scope for the generic response return unauthorized(errorType, accessTokenType, realm, scope); } switch (errorCode) { case 400: return badRequest(errorType); case 401: return unauthorized(errorType, accessTokenType, realm, scope); case 403: return forbidden(errorType); default: return HttpResponse.of(errorCode); } } }
kstepanmpmg/mldb
sql/table_expression_operations.h
/** table_expression_operations.h -*- C++ -*- <NAME>, 27 July 2015 Copyright (c) 2015 mldb.ai inc. All rights reserved. This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. Operations on tables (implementations of a table expression). */ #pragma once #include "mldb/sql/sql_expression.h" namespace MLDB { enum JoinQualification { JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, JOIN_FULL }; DECLARE_ENUM_DESCRIPTION(JoinQualification); /*****************************************************************************/ /* NAMED DATASET EXPRESSION */ /*****************************************************************************/ struct NamedDatasetExpression : public TableExpression { NamedDatasetExpression(const Utf8String& asName); void setDatasetAlias(const Utf8String& newAlias) { asName = newAlias; } virtual Utf8String getAs() const { return asName; } Utf8String asName; }; /*****************************************************************************/ /* DATASET EXPRESSION */ /*****************************************************************************/ /** Used when selecting directly from a dataset. */ struct DatasetExpression: public NamedDatasetExpression { DatasetExpression(Utf8String datasetName, Utf8String asName); DatasetExpression(Any config, Utf8String asName); virtual ~DatasetExpression(); virtual BoundTableExpression bind(SqlBindingScope & context, const ProgressFunc & onProgress) const; virtual Utf8String print() const; virtual void printJson(JsonPrintingContext & context); virtual std::string getType() const; virtual Utf8String getOperation() const; virtual std::set<Utf8String> getTableNames() const; virtual UnboundEntities getUnbound() const; Any config; Utf8String datasetName; }; /*****************************************************************************/ /* JOIN EXPRESSION */ /*****************************************************************************/ /** Used when joining datasets */ struct JoinExpression: public TableExpression { JoinExpression(std::shared_ptr<TableExpression> left, std::shared_ptr<TableExpression> right, std::shared_ptr<SqlExpression> on, JoinQualification qualification); virtual ~JoinExpression(); virtual BoundTableExpression bind(SqlBindingScope & context, const ProgressFunc & onProgress) const; virtual Utf8String print() const; virtual std::string getType() const; virtual Utf8String getOperation() const; virtual std::set<Utf8String> getTableNames() const; virtual UnboundEntities getUnbound() const; std::shared_ptr<TableExpression> left; std::shared_ptr<TableExpression> right; std::shared_ptr<SqlExpression> on; JoinQualification qualification; }; /*****************************************************************************/ /* NO TABLE */ /*****************************************************************************/ /** Used when there is no dataset */ struct NoTable: public TableExpression { virtual ~NoTable(); virtual BoundTableExpression bind(SqlBindingScope & context, const ProgressFunc & onProgress) const; virtual Utf8String print() const; virtual void printJson(JsonPrintingContext & context); virtual std::string getType() const; virtual Utf8String getOperation() const; virtual std::set<Utf8String> getTableNames() const; virtual UnboundEntities getUnbound() const; }; /*****************************************************************************/ /* SELECT SUBTABLE EXPRESSION */ /*****************************************************************************/ /** Used when doing a select inside a FROM clause **/ struct SelectSubtableExpression: public NamedDatasetExpression { SelectSubtableExpression(SelectStatement statement, Utf8String asName); virtual ~SelectSubtableExpression(); virtual BoundTableExpression bind(SqlBindingScope & context, const ProgressFunc & onProgress) const; virtual Utf8String print() const; virtual std::string getType() const; virtual Utf8String getOperation() const; virtual std::set<Utf8String> getTableNames() const; virtual UnboundEntities getUnbound() const; SelectStatement statement; }; /*****************************************************************************/ /* DATASET FUNCTION EXPRESSION */ /*****************************************************************************/ /** Used when doing a select inside a FROM clause **/ struct DatasetFunctionExpression: public NamedDatasetExpression { DatasetFunctionExpression(Utf8String functionName, std::vector<std::shared_ptr<TableExpression>>& args, std::shared_ptr<SqlExpression> options); virtual ~DatasetFunctionExpression(); virtual BoundTableExpression bind(SqlBindingScope & context, const ProgressFunc & onProgress) const; virtual Utf8String print() const; virtual std::string getType() const; virtual Utf8String getOperation() const; virtual std::set<Utf8String> getTableNames() const; virtual UnboundEntities getUnbound() const; Utf8String functionName; std::vector<std::shared_ptr<TableExpression> > args; std::shared_ptr<SqlExpression> options; }; /*****************************************************************************/ /* ROW / ATOM DATASET */ /*****************************************************************************/ /** Used when we want to treat a row expression as a table: select * from row table ({x: 1}) will return a table rowName value x 1 There are two variants: ATOMS creates one row per atom, where as COLUMNS creates one row per column. */ struct RowTableExpression: public TableExpression { enum Style { ATOMS, COLUMNS }; RowTableExpression(std::shared_ptr<SqlExpression> expr, Utf8String asName, Style style); virtual ~RowTableExpression(); virtual BoundTableExpression bind(SqlBindingScope & context, const ProgressFunc & onProgress) const; virtual Utf8String print() const; virtual void printJson(JsonPrintingContext & context); virtual std::string getType() const; virtual Utf8String getOperation() const; virtual std::set<Utf8String> getTableNames() const; virtual UnboundEntities getUnbound() const; virtual Utf8String getAs() const { return asName; } std::shared_ptr<SqlExpression> expr; Utf8String asName; Style style; }; } // namespace MLDB
EitanGayor/augur
tests-unit/input/benchmark-git2json-exec/node_modules/git2json/src/gitprocessor-plugin-relations.js
<filename>tests-unit/input/benchmark-git2json-exec/node_modules/git2json/src/gitprocessor-plugin-relations.js /* module to link commits to each other */ module.exports = function(commits) { Object.keys(commits).forEach(function(hash) { var commit = commits[hash]; commit.parents = []; commit.children = []; }); Object.keys(commits).forEach(function(hash) { var commit = commits[hash]; commit.parenthashes.forEach(function(parenthash) { var parentCommit = commits[parenthash]; if(parentCommit != undefined) { parentCommit.children.push(hash); } }); }); }
saasha05/Map-Implementation
params/RasterResult.java
package huskymaps.params; import huskymaps.server.logic.Rasterer; import java.util.Arrays; /** The computed rastering result in response to a browser request. */ public class RasterResult { /** The 2-dimensional string grid of map tilenames. */ public final Rasterer.Tile[][] grid; /** The bounding upper-left, lower-right latitudes and longitudes of the final image. */ public final double ullat; public final double ullon; public final double lrlat; public final double lrlon; /** Return a new RasterResult with the given grid. */ public RasterResult(Rasterer.Tile[][] grid) { if (grid == null || grid.length == 0 || grid[0].length == 0) { this.grid = null; this.ullat = 0; this.ullon = 0; this.lrlat = 0; this.lrlon = 0; } else { this.grid = grid; Rasterer.Tile gridUl = grid[0][0]; Rasterer.Tile gridLr = grid[grid.length - 1][grid[0].length - 1].offset(); this.ullat = gridUl.lat(); this.ullon = gridUl.lon(); this.lrlat = gridLr.lat(); this.lrlon = gridLr.lon(); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RasterResult that = (RasterResult) o; return Arrays.deepEquals(grid, that.grid); } @Override public int hashCode() { return Arrays.deepHashCode(grid); } @Override public String toString() { return "RasterResult{" + "grid=" + Arrays.deepToString(grid) + '}'; } }
egovernments/iFix-Dev
domain-services/fiscal-event-post-processor/src/main/java/org/egov/service/FiscalEventDereferenceEnrichmentService.java
package org.egov.service; import lombok.extern.slf4j.Slf4j; import org.egov.common.contract.request.RequestHeader; import org.egov.util.MasterDataConstants; import org.egov.web.models.FiscalEvent; import org.egov.web.models.FiscalEventDeReferenced; import org.egov.web.models.FiscalEventRequest; import org.springframework.stereotype.Service; @Service @Slf4j public class FiscalEventDereferenceEnrichmentService { public void enrich(FiscalEventRequest fiscalEventRequest, FiscalEventDeReferenced fiscalEventDeReferenced) { RequestHeader requestHeader = fiscalEventRequest.getRequestHeader(); FiscalEvent fiscalEvent = fiscalEventRequest.getFiscalEvent(); fiscalEventDeReferenced.setIngestionTime(fiscalEvent.getIngestionTime()); fiscalEventDeReferenced.setEventTime(fiscalEvent.getEventTime()); fiscalEventDeReferenced.setEventType(fiscalEvent.getEventType().name()); fiscalEventDeReferenced.setParentReferenceId(fiscalEvent.getParentReferenceId()); fiscalEventDeReferenced.setParentEventId(fiscalEvent.getParentEventId()); fiscalEventDeReferenced.setReferenceId(fiscalEvent.getReferenceId()); fiscalEventDeReferenced.setAttributes(fiscalEvent.getAttributes()); fiscalEventDeReferenced.setVersion(MasterDataConstants.FISCAL_EVENT_VERSION); fiscalEventDeReferenced.setAuditDetails(fiscalEvent.getAuditDetails()); fiscalEventDeReferenced.setId(fiscalEvent.getId()); } }
jonestimd/swing-extensions
src/main/java/io/github/jonestimd/lang/Comparables.java
<reponame>jonestimd/swing-extensions // The MIT License (MIT) // // Copyright (c) 2017 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package io.github.jonestimd.lang; import java.util.List; /** * Utility methods for {@link Comparable}s. */ public class Comparables { /** * Find the minimum value of a group of items. * @param c1 the first item * @param others the remaining items * @return the minimum item */ @SafeVarargs public static <T extends Comparable<? super T>> T min(T c1, T... others) { T min = c1; for (T other : others) { min = min.compareTo(other) > 0 ? other : min; } return min; } /** * Compare two possibly null objects. A {@code null} is considered "less than" any non-{@code null} value. * @return the comparison result */ public static <T extends Comparable<? super T>> int nullFirst(T c1, T c2) { if (c1 == null) { return c2 == null ? 0 : -1; } return c2 == null ? 1 : c1.compareTo(c2); } /** * Compare two possibly null objects. A {@code null} is considered "greater than" any non-{@code null} value. * @return the comparison result */ public static <T extends Comparable<? super T>> int nullLast(T c1, T c2) { if (c1 == null) { return c2 == null ? 0 : 1; } return c2 == null ? -1 : c1.compareTo(c2); } /** * Compare each element in {@code list1} to the corresponding element in {@code list2} until a difference is found. * If one list contains the leading elements of the other then the comparison result is the difference in the list sizes. * @return the result of tne first non-zero comparison of the list elements or the comparison of the list sizes */ public static int compareIgnoreCase(List<String> list1, List<String> list2) { for (int i = 0; i < Math.min(list1.size(), list2.size()); i++) { int diff = list1.get(i).compareToIgnoreCase(list2.get(i)); if (diff != 0) { return diff; } } return list1.size() - list2.size(); } }
mohdab98/cmps252_hw4.2
src/cmps252/HW4_2/UnitTesting/record_4764.java
<reponame>mohdab98/cmps252_hw4.2<filename>src/cmps252/HW4_2/UnitTesting/record_4764.java package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("11") class Record_4764 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 4764: FirstName is Brain") void FirstNameOfRecord4764() { assertEquals("Brain", customers.get(4763).getFirstName()); } @Test @DisplayName("Record 4764: LastName is Ptaschinski") void LastNameOfRecord4764() { assertEquals("Ptaschinski", customers.get(4763).getLastName()); } @Test @DisplayName("Record 4764: Company is National Society Archl Engrs") void CompanyOfRecord4764() { assertEquals("National Society Archl Engrs", customers.get(4763).getCompany()); } @Test @DisplayName("Record 4764: Address is 2943 Daylight Way") void AddressOfRecord4764() { assertEquals("2943 Daylight Way", customers.get(4763).getAddress()); } @Test @DisplayName("Record 4764: City is San Jose") void CityOfRecord4764() { assertEquals("San Jose", customers.get(4763).getCity()); } @Test @DisplayName("Record 4764: County is Santa Clara") void CountyOfRecord4764() { assertEquals("Santa Clara", customers.get(4763).getCounty()); } @Test @DisplayName("Record 4764: State is CA") void StateOfRecord4764() { assertEquals("CA", customers.get(4763).getState()); } @Test @DisplayName("Record 4764: ZIP is 95111") void ZIPOfRecord4764() { assertEquals("95111", customers.get(4763).getZIP()); } @Test @DisplayName("Record 4764: Phone is 408-227-8418") void PhoneOfRecord4764() { assertEquals("408-227-8418", customers.get(4763).getPhone()); } @Test @DisplayName("Record 4764: Fax is 408-227-5751") void FaxOfRecord4764() { assertEquals("408-227-5751", customers.get(4763).getFax()); } @Test @DisplayName("Record 4764: Email is <EMAIL>") void EmailOfRecord4764() { assertEquals("<EMAIL>", customers.get(4763).getEmail()); } @Test @DisplayName("Record 4764: Web is http://www.brainptaschinski.com") void WebOfRecord4764() { assertEquals("http://www.brainptaschinski.com", customers.get(4763).getWeb()); } }
s-nase/vanilla
Source/Rendering/Shaders/vaShaderCore.h
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Original work Copyright (C) 2016-2021, Intel Corporation // Modified work Copyright (C) 2022, Vanilla Blue team // // SPDX-License-Identifier: MIT /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Author(s): <NAME> (<EMAIL>) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef VA_SHADER_CORE_H #define VA_SHADER_CORE_H #ifndef VA_COMPILED_AS_SHADER_CODE namespace Vanilla { #define VA_SATURATE vaMath::Saturate #define VA_MIN vaComponentMin #define VA_MAX vaComponentMax #define VA_LENGTH vaLength #define VA_INLINE inline #define VA_REFERENCE & #define VA_OUTREF #define VA_CONST const #define VA_POW std::pow } #else #define VA_SATURATE saturate #define VA_MIN min #define VA_MAX max #define VA_LENGTH length #define VA_INLINE #define VA_REFERENCE #define VA_OUTREF out #define VA_CONST #define VA_POW pow #endif #ifndef VA_COMPILED_AS_SHADER_CODE #include "Core/vaCoreIncludes.h" #else // Vanilla-specific; this include gets intercepted and macros are provided through it to allow for some macro // shenanigans that don't work through the normal macro string pairs (like #include macros!). #include "MagicMacrosMagicFile.h" // Vanilla defaults to column-major matrices in shaders because that is the DXC default with no arguments, and it // seems to be more common* in general. (*AFAIK) // This is in contrast to the C++ side, which is row-major, so the ordering of matrix operations in shaders needs // to be inverted, which is fine, for ex., "projectedPos = mul( g_globals.ViewProj, worldspacePos )" // One nice side-effect is that it's easy to drop the 4th column for 4x3 matrix (on c++ side), which becomes 3x4 // (on the shader side), which is useful for reducing memory traffic for affine transforms. // See https://github.com/microsoft/DirectXShaderCompiler/blob/master/docs/SPIR-V.rst#appendix-a-matrix-representation // and http://www.mindcontrol.org/~hplus/graphics/matrix-layout.html for more detail. #define vaMatrix4x4 column_major float4x4 #define vaMatrix4x3 column_major float3x4 #define vaMatrix3x3 column_major float3x3 #define vaVector4 float4 #define vaVector3 float3 #define vaVector2 float2 #define vaVector2i int2 #define vaVector2ui uint2 #define vaVector4i int4 #define vaVector4ui uint4 #define CONCATENATE_HELPER(a, b) a##b #define CONCATENATE(a, b) CONCATENATE_HELPER(a, b) #define B_CONCATENATER(x) CONCATENATE(b,x) #define S_CONCATENATER(x) CONCATENATE(s,x) #define T_CONCATENATER(x) CONCATENATE(t,x) #define U_CONCATENATER(x) CONCATENATE(u,x) #define ShaderMin( x, y ) min( x, y ) #endif #endif // VA_SHADER_CORE_H
pradeepkarki/JavaBasicPrograms
src/main/java/com/java/programs/faq/FactorialOfNumber.java
package com.java.programs.faq; /** * * write a program to find the factorial of a number * */ public class FactorialOfNumber { public static void main(String[] args) { int number =6; int fact=1; for(int i=1;i<=number;i++) { fact = fact * i; } System.out.println("Factorial of a number - "+fact); } }
CeH9/intellij-community
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/j2me/MultiplyOrDivideByPowerOfTwoInspection.java
<filename>plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/j2me/MultiplyOrDivideByPowerOfTwoInspection.java /* * Copyright 2003-2018 <NAME>, <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.siyeh.ig.j2me; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.tree.IElementType; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.PsiReplacementUtil; import com.siyeh.ig.psiutils.ClassUtils; import com.siyeh.ig.psiutils.CommentTracker; import com.siyeh.ig.psiutils.ParenthesesUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class MultiplyOrDivideByPowerOfTwoInspection extends BaseInspection { /** * @noinspection PublicField */ public boolean checkDivision = false; @Override @Nullable public JComponent createOptionsPanel() { return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message( "multiply.or.divide.by.power.of.two.divide.option"), this, "checkDivision"); } @Override @NotNull public String buildErrorString(Object... infos) { return InspectionGadgetsBundle.message("expression.can.be.replaced.problem.descriptor", calculateReplacementShift((PsiExpression)infos[0], new CommentTracker())); } static String calculateReplacementShift(PsiExpression expression, CommentTracker commentTracker) { final PsiExpression lhs; final PsiExpression rhs; final String operator; if (expression instanceof PsiAssignmentExpression) { final PsiAssignmentExpression exp = (PsiAssignmentExpression)expression; lhs = exp.getLExpression(); rhs = exp.getRExpression(); final IElementType tokenType = exp.getOperationTokenType(); if (tokenType.equals(JavaTokenType.ASTERISKEQ)) { operator = "<<="; } else { operator = ">>="; } } else { final PsiBinaryExpression exp = (PsiBinaryExpression)expression; lhs = exp.getLOperand(); rhs = exp.getROperand(); final IElementType tokenType = exp.getOperationTokenType(); if (tokenType.equals(JavaTokenType.ASTERISK)) { operator = "<<"; } else { operator = ">>"; } } if (!(rhs instanceof PsiLiteralExpression)) return null; final String lhsText = commentTracker.text(lhs, ParenthesesUtils.SHIFT_PRECEDENCE); String expString = lhsText + operator + ShiftUtils.getLogBaseTwo((PsiLiteralExpression)rhs); final PsiElement parent = expression.getParent(); if (parent instanceof PsiExpression) { if (!(parent instanceof PsiParenthesizedExpression) && ParenthesesUtils.getPrecedence((PsiExpression)parent) < ParenthesesUtils.SHIFT_PRECEDENCE) { expString = '(' + expString + ')'; } } return expString; } @Override public InspectionGadgetsFix buildFix(Object... infos) { final PsiExpression expression = (PsiExpression)infos[0]; if (expression instanceof PsiBinaryExpression) { final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)expression; final IElementType operationTokenType = binaryExpression.getOperationTokenType(); if (JavaTokenType.DIV.equals(operationTokenType)) { return null; } } else if (expression instanceof PsiAssignmentExpression) { final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)expression; final IElementType operationTokenType = assignmentExpression.getOperationTokenType(); if (JavaTokenType.DIVEQ.equals(operationTokenType)) { return null; } } return new MultiplyByPowerOfTwoFix(); } private static class MultiplyByPowerOfTwoFix extends InspectionGadgetsFix { @Override @NotNull public String getFamilyName() { return InspectionGadgetsBundle.message( "multiply.or.divide.by.power.of.two.replace.quickfix"); } @Override public void doFix(Project project, ProblemDescriptor descriptor) { final PsiExpression expression = (PsiExpression)descriptor.getPsiElement(); CommentTracker commentTracker = new CommentTracker(); final String newExpression = calculateReplacementShift(expression, commentTracker); if (newExpression != null) { PsiReplacementUtil.replaceExpression(expression, newExpression, commentTracker); } } } @Override public BaseInspectionVisitor buildVisitor() { return new ConstantShiftVisitor(); } private class ConstantShiftVisitor extends BaseInspectionVisitor { @Override public void visitBinaryExpression(@NotNull PsiBinaryExpression expression) { super.visitBinaryExpression(expression); final PsiExpression rhs = expression.getROperand(); if (rhs == null) { return; } final IElementType tokenType = expression.getOperationTokenType(); if (!tokenType.equals(JavaTokenType.ASTERISK)) { if (!checkDivision || !tokenType.equals(JavaTokenType.DIV)) { return; } } if (!ShiftUtils.isPowerOfTwo(rhs)) { return; } final PsiType type = expression.getType(); if (type == null) { return; } if (!ClassUtils.isIntegral(type)) { return; } registerError(expression, expression); } @Override public void visitAssignmentExpression(@NotNull PsiAssignmentExpression expression) { super.visitAssignmentExpression(expression); final IElementType tokenType = expression.getOperationTokenType(); if (!tokenType.equals(JavaTokenType.ASTERISKEQ)) { if (!checkDivision || !tokenType.equals(JavaTokenType.DIVEQ)) { return; } } final PsiExpression rhs = expression.getRExpression(); if (!ShiftUtils.isPowerOfTwo(rhs)) { return; } final PsiType type = expression.getType(); if (type == null) { return; } if (!ClassUtils.isIntegral(type)) { return; } registerError(expression, expression); } } }
milasuperstar/chaos-mesh
controllers/chaosimpl/iochaos/impl.go
// Copyright 2021 Chaos Mesh Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package iochaos import ( "context" "errors" "strings" "github.com/go-logr/logr" "go.uber.org/fx" v1 "k8s.io/api/core/v1" k8sError "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/chaos-mesh/chaos-mesh/api/v1alpha1" "github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/iochaos/podiochaosmanager" impltypes "github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/types" "github.com/chaos-mesh/chaos-mesh/controllers/utils/controller" ) var _ impltypes.ChaosImpl = (*Impl)(nil) const ( waitForApplySync v1alpha1.Phase = "Not Injected/Wait" waitForRecoverSync v1alpha1.Phase = "Injected/Wait" ) type Impl struct { client.Client Log logr.Logger builder *podiochaosmanager.Builder } func (impl *Impl) Apply(ctx context.Context, index int, records []*v1alpha1.Record, obj v1alpha1.InnerObject) (v1alpha1.Phase, error) { // The only possible phase to get in here is "Not Injected" or "Not Injected/Wait" impl.Log.Info("iochaos Apply", "namespace", obj.GetNamespace(), "name", obj.GetName()) iochaos := obj.(*v1alpha1.IOChaos) if iochaos.Status.Instances == nil { iochaos.Status.Instances = make(map[string]int64) } record := records[index] phase := record.Phase if phase == waitForApplySync { podiochaos := &v1alpha1.PodIOChaos{} namespacedName, err := controller.ParseNamespacedName(record.Id) if err != nil { return waitForApplySync, err } err = impl.Client.Get(ctx, namespacedName, podiochaos) if err != nil { if k8sError.IsNotFound(err) { return v1alpha1.NotInjected, nil } if k8sError.IsForbidden(err) { if strings.Contains(err.Error(), "because it is being terminated") { return v1alpha1.NotInjected, nil } } return waitForApplySync, err } if podiochaos.Status.FailedMessage != "" { return waitForApplySync, errors.New(podiochaos.Status.FailedMessage) } if podiochaos.Status.ObservedGeneration >= iochaos.Status.Instances[record.Id] { return v1alpha1.Injected, nil } return waitForApplySync, nil } podId, containerName, err := controller.ParseNamespacedNameContainer(records[index].Id) if err != nil { return v1alpha1.NotInjected, err } var pod v1.Pod err = impl.Client.Get(ctx, podId, &pod) if err != nil { return v1alpha1.NotInjected, err } source := iochaos.Namespace + "/" + iochaos.Name m := impl.builder.WithInit(source, types.NamespacedName{ Namespace: pod.Namespace, Name: pod.Name, }) m.T.SetVolumePath(iochaos.Spec.VolumePath) m.T.SetContainer(containerName) m.T.Append(v1alpha1.IOChaosAction{ Type: iochaos.Spec.Action, Filter: v1alpha1.Filter{ Path: iochaos.Spec.Path, Percent: iochaos.Spec.Percent, Methods: iochaos.Spec.Methods, }, Faults: []v1alpha1.IoFault{ { Errno: iochaos.Spec.Errno, Weight: 1, }, }, Latency: iochaos.Spec.Delay, AttrOverrideSpec: iochaos.Spec.Attr, MistakeSpec: iochaos.Spec.Mistake, Source: m.Source, }) generationNumber, err := m.Commit(ctx, iochaos) if err != nil { return v1alpha1.NotInjected, err } // modify the custom status iochaos.Status.Instances[record.Id] = generationNumber return waitForApplySync, nil } func (impl *Impl) Recover(ctx context.Context, index int, records []*v1alpha1.Record, obj v1alpha1.InnerObject) (v1alpha1.Phase, error) { // The only possible phase to get in here is "Injected" or "Injected/Wait" iochaos := obj.(*v1alpha1.IOChaos) if iochaos.Status.Instances == nil { iochaos.Status.Instances = make(map[string]int64) } record := records[index] phase := record.Phase if phase == waitForRecoverSync { podiochaos := &v1alpha1.PodIOChaos{} namespacedName, err := controller.ParseNamespacedName(record.Id) if err != nil { // This error is not expected to exist return waitForRecoverSync, nil } err = impl.Client.Get(ctx, namespacedName, podiochaos) if err != nil { // TODO: handle this error if k8sError.IsNotFound(err) { return v1alpha1.NotInjected, nil } return waitForRecoverSync, err } if podiochaos.Status.FailedMessage != "" { return waitForRecoverSync, errors.New(podiochaos.Status.FailedMessage) } if podiochaos.Status.ObservedGeneration >= iochaos.Status.Instances[record.Id] { return v1alpha1.NotInjected, nil } return waitForRecoverSync, nil } podId, _, err := controller.ParseNamespacedNameContainer(records[index].Id) if err != nil { // This error is not expected to exist return v1alpha1.NotInjected, err } var pod v1.Pod err = impl.Client.Get(ctx, podId, &pod) if err != nil { // TODO: handle this error if k8sError.IsNotFound(err) { return v1alpha1.NotInjected, nil } return v1alpha1.Injected, err } source := iochaos.Namespace + "/" + iochaos.Name m := impl.builder.WithInit(source, types.NamespacedName{ Namespace: pod.Namespace, Name: pod.Name, }) generationNumber, err := m.Commit(ctx, iochaos) if err != nil { if err == podiochaosmanager.ErrPodNotFound || err == podiochaosmanager.ErrPodNotRunning { return v1alpha1.NotInjected, nil } if k8sError.IsForbidden(err) { if strings.Contains(err.Error(), "because it is being terminated") { return v1alpha1.NotInjected, nil } } return v1alpha1.Injected, err } // Now modify the custom status and phase iochaos.Status.Instances[record.Id] = generationNumber return waitForRecoverSync, nil } func NewImpl(c client.Client, b *podiochaosmanager.Builder, log logr.Logger) *impltypes.ChaosImplPair { return &impltypes.ChaosImplPair{ Name: "iochaos", Object: &v1alpha1.IOChaos{}, Impl: &Impl{ Client: c, Log: log.WithName("iochaos"), builder: b, }, ObjectList: &v1alpha1.IOChaosList{}, Controlls: []client.Object{&v1alpha1.PodIOChaos{}}, } } var Module = fx.Provide( fx.Annotated{ Group: "impl", Target: NewImpl, }, podiochaosmanager.NewBuilder, )
localwatcher/localwatcher.github.io
src/client/components/video/Video.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Subtitles from '@client/components/Subtitles'; export default class Video extends Component { static propTypes = { src: PropTypes.string.isRequired, playing: PropTypes.bool.isRequired, time: PropTypes.number.isRequired, authorized: PropTypes.bool.isRequired, loaded: PropTypes.bool.isRequired, setDuration: PropTypes.func.isRequired, setLoaded: PropTypes.func.isRequired, setAuthorized: PropTypes.func.isRequired, end: PropTypes.func.isRequired, onTimeUpdate: PropTypes.func.isRequired, onDurationChange: PropTypes.func.isRequired, onProgress: PropTypes.func.isRequired, onPlayed: PropTypes.func.isRequired, onPaused: PropTypes.func.isRequired, onEnded: PropTypes.func.isRequired, preload: PropTypes.string, volume: PropTypes.number.isRequired, }; static defaultProps = { preload: 'auto', }; constructor(props) { super(props); this.element = null; this.ready = false; this.setElement = this.setElement.bind(this); this.play = this.play.bind(this); this.onLoadStart = this.onLoadStart.bind(this); this.onCanPlay = this.onCanPlay.bind(this); this.onCanPlayThrough = this.onCanPlayThrough.bind(this); this.onDurationChange = this.onDurationChange.bind(this); this.onNotAuthorized = this.onNotAuthorized.bind(this); this.onEnded = this.onEnded.bind(this); this.onAuthorized = this.onAuthorized.bind(this); this.onError = this.onError.bind(this); } get currentTime() { return parseFloat(this.element.currentTime.toFixed(3), 10); } get duration() { return parseFloat(this.element.duration.toFixed(3), 10); } get buffered() { return this.element.buffered; } componentDidUpdate(prevProps) { const { time, playing, volume } = this.props; if (playing !== prevProps.playing) { playing ? this.play(time) : this.pause(time); } else if (time !== prevProps.time) { this.seek(time); } if (volume !== prevProps.volume) { this.element.volume = this.props.volume; } } setElement(element) { this.element = element; if (element) { this.element.volume = this.props.volume; } } play(time) { this.seek(time); let promise = null; try { promise = this.element.play(); } catch (error) { this.onNotAuthorized(error); } if (promise) { promise.then(this.onAuthorized).catch(this.onNotAuthorized); } else { this.onAuthorized(); } } pause(time) { this.element.pause(); this.seek(time); } stop() { this.element.stop(); } seek(time) { if (typeof time === 'number') { this.element.currentTime = time; } } onAuthorized() { if (!this.props.authorized) { this.props.setAuthorized(true); } } onNotAuthorized(error) { if (error instanceof DOMException && error.name === 'NotAllowedError' && this.props.authorized) { this.props.setAuthorized(false); } } onLoadStart() { if (this.props.loaded) { this.props.setLoaded(false); } } onCanPlay() { if (!this.props.loaded) { this.props.setLoaded(true); if (this.props.time > this.element.currentTime) { this.seek(this.props.time); } } } onCanPlayThrough() { } onDurationChange() { this.props.setDuration(this.element.duration); this.props.onDurationChange(); } onEnded() { this.props.end(); this.props.onEnded(); } onError(error) { console.error(error); } render(){ const { src, preload } = this.props; return ( <video ref={this.setElement} src={src} preload={preload} onLoadStart={this.onLoadStart} onProgress={this.props.onProgress} onCanPlay={this.onCanPlay} onCanPlayThrough={this.onCanPlayThrough} onDurationChange={this.onDurationChange} onTimeUpdate={this.props.onTimeUpdate} onPlay={this.props.onPlayed} onPause={this.props.onPaused} onEnded={this.onEnded} > <Subtitles /> </video> ); } }
Biovision/comunit-base
app/services/comunit/network/handlers/post_handler.rb
<filename>app/services/comunit/network/handlers/post_handler.rb # frozen_string_literal: true module Comunit module Network module Handlers # Handling posts class PostHandler < Comunit::Network::Handler def self.since 10 end def self.permitted_attributes super + %i[ ip updated_at show_owner translation time_required publication_time slug title image_alt_text image_name image_source_name image_source_link original_title source_name source_link meta_title meta_keywords meta_description author_name author_title author_url translator_name lead body ] end def meta_for_remote meta = super meta[:agent] = entity.agent&.name if entity.attributes.key?('image') && !entity.image.blank? meta[:image_path] = entity.image.path meta[:image_url] = host + entity.image.url end meta end protected def after_pull apply_attachments apply_post_categories if entity.respond_to?(:post_categories) apply_taxa if entity.respond_to?(:taxa) forward if self.class.central_site? true end def forward site_ids = entity.post_categories.pluck(:site_id).uniq log_info "Forward to #{site_ids}" Site.where(id: site_ids).each do |other_site| next if other_site == entity.site NetworkEntitySyncJob.perform_later(entity.class.to_s, entity.id, other_site.uuid) end end def pull_data apply_attributes apply_post_type apply_user apply_region apply_image apply_simple_image end def relationships_for_remote result = { user: UserHandler.relationship_data(entity.user), attachments: attachments_for_remote } result[:region] = RegionHandler.relationship_data(entity.region) if entity.attributes.key?('region_id') if entity.attributes.key?('post_type_id') result[:post_type] = PostTypeHandler.relationship_data(entity.post_type) end result[:post_categories] = post_categories_for_remote if entity.respond_to?(:post_categories) result[:taxa] = taxa_for_remote if entity.respond_to?(:taxa) result end def attachments_for_remote collection = entity.post_attachments.map do |item| PostAttachmentHandler.relationship_data(item, false) end collection.any? ? { data: collection } : nil end def post_categories_for_remote collection = entity.post_categories.map do |item| PostCategoryHandler.relationship_data(item, false) end collection.any? ? { data: collection } : nil end def taxa_for_remote collection = entity.taxa.map do |item| TaxonHandler.relationship_data(item, false) end collection.any? ? { data: collection } : nil end def apply_attachments data.dig(:relationships, :attachments, :data)&.each do |data| PostAttachmentHandler.pull_for_post(entity, data) end end def apply_post_categories data.dig(:relationships, :post_categories, :data)&.each do |data| PostCategoryHandler.pull_for_post(entity, data) end end def apply_taxa data.dig(:relationships, :taxa, :data)&.each do |data| TaxonHandler.pull_for_post(entity, data) end end end end end end
dallaval5u/COMET
COMET/measurement_plugins/Frequency Scan.py
# This file manages the stripscan measurements and it is intended to be used as a plugin for the QTC software import logging import sys import numpy as np from time import sleep sys.path.append("../COMET") try: from .IVCV import IVCV_class from .Stripscan import Stripscan_class except: from .stripscan import Stripscan_class class FrequencyScan_class(Stripscan_class): def __init__(self, main_class): """ This class takes only one parameter, the main class, in which all parameters must be prevalent. It further starts the actual stripscan measurement, no further action need to be taken :param main_class: """ super(FrequencyScan_class, self).__init__(main_class) self.log = logging.getLogger(__name__) self.main = main_class self.job = self.main.job_details["Frequency Scan"] self.job_details = self.main.job_details self.general_options = self.job["General"] self.measurements = self.job.copy() self.measurements.pop("General") # Define a few values, so inital ramp up values etc. # These varaibles are used for the stripscan preparations!!! self.voltage_End = self.general_options["Start Voltage [V]"] self.voltage_Start = 0 self.voltage_steps = 10 self.compliance = self.general_options["Compliance [uA]"] # Voltage step list self.voltage_ramp = self.ramp_value( self.general_options["Start Voltage [V]"], self.general_options["End Voltage [V]"], self.general_options["Voltage Step [V]"], ) def run(self): """This function conducts the measurements """ self.do_preparations_for_stripscan(do_cal=False, measurement="Frequency Scan") # Do the voltage ramp self.numVSteps = len(self.voltage_ramp) self.numMSteps = len(self.measurements) for iter, volt in enumerate(self.voltage_ramp): self.change_value(self.bias_SMU, "set_voltage", str(volt)) self.main.framework["Configs"]["config"]["settings"]["bias_voltage"] = volt if self.steady_state_check( self.bias_SMU, command="get_read_current", max_slope=1e-8, wait=0.05, samples=7, Rsq=0.8, compliance=self.compliance, ): # Is a dynamic waiting time for the measuremnts self.current_voltage = self.main.framework["Configs"]["config"][ "settings" ]["bias_voltage"] if self.check_compliance( self.bias_SMU, self.compliance ): # if compliance is reached stop everything self.stop_everything() else: self.stop_everything() self.do_frequencyscan(iter + 1, volt) try: for i, func_name in enumerate(self.measurements.keys()): self.write_to_file( self.main.measurement_files["Frequency Scan"], self.voltage_ramp, self.main.measurement_data[func_name + "_freq"][0], self.main.measurement_data[func_name + "_freq"][1], ) if i > 0: self.log.critical( "ASCII output cannot cope with multiple data structures, output may be compromised." ) except Exception as err: self.log.error( "Writting to ASCII file failed due to an error: {}".format(err) ) # self.write_to_json() self.clean_up() def write_to_json(self): """Writes the individual data arrays to stand alone json files for easy plotting""" for i, func_name in enumerate(self.measurements.keys()): # Measuremnts data_to_dump = {} for j, data in enumerate( zip( self.main.measurement_data[func_name + "_freq"][0], self.main.measurement_data[func_name + "_freq"][1], ) ): # Voltage steps data_to_dump["{}V".format(self.voltage_ramp[j])] = [data[0], data[1]] new_name = { "Filename": self.job_details["Filename"] + "_{}".format(func_name) } details = self.job_details.copy() details.update(new_name) self.main.save_data_as( "json", details, data=data_to_dump, xunits=("frequency", "Hz"), yunits=("capacitance", "F"), ) def do_frequencyscan(self, iteration, voltage): """This function performes a frequency scan of the lcr meter and at each step it executes a LIST of mesaurement""" # Loop over all measurements step = 0 for func_name, measurement in self.measurements.items(): if not self.main.event_loop.stop_all_measurements_query(): step += 1 start_freq = measurement["Start Freq [Hz]"] end_freq = measurement["End Freq [Hz]"] step_freq = measurement["Steps"] LCR_volt = measurement["Amplitude [mV]"] * 0.001 strip = measurement.get("Strip [#]", -1) # Generate frequency list freq_list = list(self.ramp_value_log10(start_freq, end_freq, step_freq)) # Construct results array self.xvalues = np.zeros(len(freq_list)) self.yvalues = np.zeros(len(freq_list)) # Set the LCR amplitude voltage for measurement self.change_value(self.LCR_meter, "set_voltage", str(LCR_volt)) # Move to strip if necessary if ( strip > 0 and self.main.framework["Configs"]["config"]["settings"][ "Alignment" ] ): if not self.main.table.move_to_strip( self.sensor_pad_data, strip, self.trans, self.T, self.V0, self.height, ): self.log.error("Could not move to strip {}".format(strip)) break elif not self.main.framework["Configs"]["config"]["settings"][ "Alignment" ]: self.log.critical( "No alignment done, conducting frequency scan without moving table!" ) for i, freq in enumerate( list(freq_list) ): # does the loop over the frequencies if ( not self.main.event_loop.stop_all_measurements_query() ): # stops the loop if shutdown is necessary self.main.framework["Configs"]["config"]["settings"][ "progress" ] = (i + 1) / len(freq_list) yvalue = getattr(self, "do_" + func_name)( strip, samples=self.samples, freqscan=True, frequency=freq, write_to_main=False, ) # calls the measurement self.yvalues[i] = ( yvalue[0] if isinstance(yvalue, np.ndarray) else yvalue ) self.xvalues[i] = float(freq) # Append the data to the data array and sends it to the main as frequency scan measurement if not self.main.event_loop.stop_all_measurements_query(): if self.main.measurement_data[func_name + "_freq"][0][0]: self.main.measurement_data[func_name + "_freq"][0] = np.vstack( [ self.main.measurement_data[func_name + "_freq"][0], self.xvalues, ] ) self.main.measurement_data[func_name + "_freq"][1] = np.vstack( [ self.main.measurement_data[func_name + "_freq"][1], self.yvalues, ] ) else: self.main.measurement_data[func_name + "_freq"][ 0 ] = self.xvalues self.main.measurement_data[func_name + "_freq"][ 1 ] = self.yvalues self.main.queue_to_main.put( {func_name + "_freq": [self.xvalues, self.yvalues]} ) def write_to_file(self, file, voltages, xvalues, yvalues): """ Writes data to the ascii file """ # Check if length of voltages matches the length of data array if len(xvalues) == len(yvalues): data = np.array([xvalues, yvalues]) # data = np.transpose(data) # Write voltage header for each measurement first the voltages self.main.write( file, "" + "".join( [format(el, "<{}".format(self.justlength * 2)) for el in voltages] ) + "\n", ) # Then the Units self.main.write( file, "".join( [ format( "frequency[Hz]{}capacitance[F]".format( " " * (self.justlength - 7) ), "<{}".format(self.justlength * 2), ) for x in range(len(voltages)) ] ) + "\n", ) try: for i in range(len(data[0, 0, :])): # For multidimensional data freq = [ format(time, "<{}".format(self.justlength)) for time in data[:, :, i][0] ] cap = [ format(curr, "<{}".format(self.justlength)) for curr in data[:, :, i][1] ] final = "".join([t + c for t, c in zip(freq, cap)]) self.main.write(file, final + "\n") except: freq = [format(time, "<{}".format(self.justlength)) for time in data[0]] cap = [format(curr, "<{}".format(self.justlength)) for curr in data[1]] final = "".join([t + c + "\n" for t, c in zip(freq, cap)]) self.main.write(file, final + "\n") else: self.log.error( "Length of results array are non matching, abort storing data to file" ) def do_CV( self, xvalue=-1, samples=5, freqscan=False, write_to_main=True, alternative_switching=False, frequency=1000, ): """Does the cac measurement""" device_dict = self.LCR_meter # Config the LCR to the correct freq of 1 kHz self.change_value(device_dict, "set_frequency", frequency) if not self.main.event_loop.stop_all_measurements_query(): if not self.switching.switch_to_measurement("CV"): self.stop_everything() return sleep( 5.0 ) # Is need due to some stray capacitances which corrupt the measurement if self.steady_state_check( device_dict, command="get_read", max_slope=1e-6, wait=0.0, samples=2, Rsq=0.5, check_compliance=False, ): # Is a dynamic waiting time for the measuremnt value = self.do_measurement( "CV", device_dict, xvalue, samples, write_to_main=not freqscan, correction=0, ) else: return False return value def do_measurement( self, name, device, xvalue=-1, samples=5, write_to_main=True, query="get_read", apply_to=None, correction=None, ): """ Does a simple measurement - really simple. Only acquire some values and build the mean of it :param name: What measurement is to be conducetd, if you pass a list, values returned, must be the same shape, other wise error will occure :param device: Which device schould be used :param xvalue: Which strip we are on, -1 means arbitrary :param samples: How many samples should be taken :param write_to_main: Writes the value back to the main loop :param query: what query should be used :param apply_to: data array will be given to a function for further calculations :param correction: single value or list of values subtracted to the resulting solution :return: Returns the mean of all aquired values """ # Do some averaging over values values = [] command = self.main.build_command(device, query) for i in range(samples): # takes samples values.append(self.vcw.query(device, command)) values = np.array( list(map(lambda x: x.split(device.get("separator", ",")), values)), dtype=float, ) values = np.mean(values, axis=0) # Apply correction values if isinstance(correction, list) or isinstance(correction, tuple): for i, val in enumerate(correction): values[i] -= val elif isinstance(correction, float) or isinstance(correction, int): values[0] -= correction if apply_to: # Only a single float or int are allowed as returns value = apply_to(values) elif values.shape == (1,) or isinstance(values, float): value = values else: value = values[0] if write_to_main: # Writes data to the main, or not if isinstance(name, str): self.main.measurement_data[str(name)][0][self.strip_iter] = float( xvalue ) self.main.measurement_data[str(name)][1][self.strip_iter] = float(value) self.main.queue_to_main.put({str(name): [float(xvalue), float(value)]}) elif isinstance(name, list) or isinstance(name, tuple): try: for i, sub in enumerate(name): self.main.measurement_data[str(sub)][0][ self.strip_iter ] = float(xvalue) self.main.measurement_data[str(sub)][1][ self.strip_iter ] = float(values[i]) self.main.queue_to_main.put( {str(sub): [float(xvalue), float(values[i])]} ) except IndexError as err: self.log.error( "An error happened during values indexing in multi value return", exc_info=True, ) return values
mdg/pygrate
setup.py
<gh_stars>1-10 #!/usr/bin/env python from distutils.core import setup setup(name='pygrate', version='0.2', description='Python DB Migration Framework', author='<NAME>', url='http://github.com/mdg/pygrate', scripts=['bin/pygrate'], packages=['pygration'] )
javashop/pangu
src/main/java/com/enation/pangu/model/Step.java
<reponame>javashop/pangu package com.enation.pangu.model; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.enation.pangu.domain.PluginConfigVO; import java.util.List; import java.util.Map; /** * 步骤实体类 * @author zhangsong * @date 2020-11-01 */ @TableName(value = "step") public class Step { /** * 步骤id */ @TableId(type = IdType.AUTO) private Long id; /** * 步骤名称 */ private String name; /** * 执行顺序 */ private Integer sequence; /** * 执行器,可选值:ssh */ private String executor; /** * 校验器,可选值:port,command,process */ private String checkType; /** * 部署id */ private Long deploymentId; /** * 创建时间 */ private Long addTime; /** * 执行器参数 */ private String executorParams; /** * 检测器参数 */ private String checkerParams; /** * 是否跳过执行 0不跳过 1跳过 */ private Integer isSkip; /** * 执行器配置 */ @TableField(exist = false) private PluginConfigVO executorConfig; /** * 检测器配置 */ @TableField(exist = false) private PluginConfigVO checkerConfig; /** * 回显特殊执行器参数用 *(write_config执行器 git_clone执行器) */ @TableField(exist = false) private Map writeConfigParams; /** * write_config执行器的配置文件列表(回显数据用) */ @TableField(exist = false) private List<ConfigFile> configFileList; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCheckType() { return checkType; } public void setCheckType(String checkType) { this.checkType = checkType; } public Long getDeploymentId() { return deploymentId; } public void setDeploymentId(Long deploymentId) { this.deploymentId = deploymentId; } public Long getAddTime() { return addTime; } public void setAddTime(Long addTime) { this.addTime = addTime; } public Integer getSequence() { return sequence; } public void setSequence(Integer sequence) { this.sequence = sequence; } public String getExecutor() { return executor; } public void setExecutor(String executor) { this.executor = executor; } public String getExecutorParams() { return executorParams; } public void setExecutorParams(String executorParams) { this.executorParams = executorParams; } public PluginConfigVO getExecutorConfig() { if(this.executorConfig == null){ return new PluginConfigVO(); } return executorConfig; } public void setExecutorConfig(PluginConfigVO executorConfig) { this.executorConfig = executorConfig; } public PluginConfigVO getCheckerConfig() { if(this.checkerConfig == null){ return new PluginConfigVO(); } return checkerConfig; } public void setCheckerConfig(PluginConfigVO checkerConfig) { this.checkerConfig = checkerConfig; } public String getCheckerParams() { return checkerParams; } public void setCheckerParams(String checkerParams) { this.checkerParams = checkerParams; } public Map getWriteConfigParams() { return writeConfigParams; } public void setWriteConfigParams(Map writeConfigParams) { this.writeConfigParams = writeConfigParams; } public List<ConfigFile> getConfigFileList() { return configFileList; } public void setConfigFileList(List<ConfigFile> configFileList) { this.configFileList = configFileList; } public Integer getIsSkip() { return isSkip; } public void setIsSkip(Integer isSkip) { this.isSkip = isSkip; } @Override public String toString() { return "Step{" + "id=" + id + ", name='" + name + '\'' + ", sequence=" + sequence + ", executor='" + executor + '\'' + ", checkType='" + checkType + '\'' + ", deploymentId=" + deploymentId + ", addTime=" + addTime + ", executorParams='" + executorParams + '\'' + ", checkerParams='" + checkerParams + '\'' + ", executorConfig=" + executorConfig + ", checkerConfig=" + checkerConfig + ", writeConfigParams=" + writeConfigParams + ", configFileList=" + configFileList + '}'; } }
RubyOcelot/SPTAG-1
AnnService/src/IVF/SimpleScorer.cpp
<filename>AnnService/src/IVF/SimpleScorer.cpp #include "inc/IVF/SimpleScorer.h" namespace IVF { float SimpleScorer::score() { if (currentItem != nullptr) return currentItem->score(); else return -1.0;//TODO } SimpleScorer::SimpleScorer(PostingItemIter &pIter) : pIter(pIter) { currentItem = pIter.getFirst(); } DocId SimpleScorer::next() { currentItem = pIter.getNext(); if (currentItem == nullptr) return -1; else return currentItem->getDocId(); } DocId SimpleScorer::skipTo(DocId id) { currentItem = pIter.skipTo(id); if (currentItem == nullptr) return -1; else return currentItem->getDocId(); } }
Zenrer/p1xt-guides
evidence/tier-0/software-engineering-foundations/ryan_macdonald_recap_exercise_3/multiply.rb
def multiply(a, b) return 0 if a == 0 if a > 0 b + multiply(a - 1, b) else -b + multiply(a + 1, b) end end p multiply(3, 5) # => 15 p multiply(5, 3) # => 15 p multiply(2, 4) # => 8 p multiply(0, 10) # => 0 p multiply(-3, -6) # => 18 p multiply(3, -6) # => -18 p multiply(-3, 6) # => -18
jaylinhong/jdk14-learn
src/jdk14-source/java.naming/com/sun/naming/internal/FactoryEnumeration.java
<filename>src/jdk14-source/java.naming/com/sun/naming/internal/FactoryEnumeration.java /* * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.naming.internal; import java.util.List; import javax.naming.NamingException; /** * The FactoryEnumeration is used for returning factory instances. * * @author <NAME> * @author <NAME> */ // no need to implement Enumeration since this is only for internal use public final class FactoryEnumeration { // List<NamedWeakReference<Class | Object>> private List<NamedWeakReference<Object>> factories; private int posn = 0; private ClassLoader loader; /** * Records the input list and uses it directly to satisfy * hasMore()/next() requests. An alternative would have been to use * an enumeration/iterator from the list, but we want to update the * list so we keep the * original list. The list initially contains Class objects. * As each element is used, the Class object is replaced by an * instance of the Class itself; eventually, the list contains * only a list of factory instances and no more updates are required. * * <p> Both Class objects and factories are wrapped in weak * references so as not to prevent GC of the class loader. Each * weak reference is tagged with the factory's class name so the * class can be reloaded if the reference is cleared. * * @param factories A non-null list * @param loader The class loader of the list's contents * * This internal method is used with Thread Context Class Loader (TCCL), * please don't expose this method as public. */ FactoryEnumeration(List<NamedWeakReference<Object>> factories, ClassLoader loader) { this.factories = factories; this.loader = loader; } public Object next() throws NamingException { synchronized (factories) { NamedWeakReference<Object> ref = factories.get(posn++); Object answer = ref.get(); if ((answer != null) && !(answer instanceof Class)) { return answer; } String className = ref.getName(); try { if (answer == null) { // reload class if weak ref cleared Class<?> cls = Class.forName(className, true, loader); answer = cls; } // Instantiate Class to get factory @SuppressWarnings("deprecation") Object tmp = ((Class) answer).newInstance(); answer = tmp; ref = new NamedWeakReference<>(answer, className); factories.set(posn-1, ref); // replace Class object or null return answer; } catch (ClassNotFoundException e) { NamingException ne = new NamingException("No longer able to load " + className); ne.setRootCause(e); throw ne; } catch (InstantiationException e) { NamingException ne = new NamingException("Cannot instantiate " + answer); ne.setRootCause(e); throw ne; } catch (IllegalAccessException e) { NamingException ne = new NamingException("Cannot access " + answer); ne.setRootCause(e); throw ne; } } } public boolean hasMore() { synchronized (factories) { return posn < factories.size(); } } }
kingtaurus/vogl
src/vogleditor/vogleditor_tracereplayer.cpp
<reponame>kingtaurus/vogl #include "vogleditor_apicalltreeitem.h" #include "vogleditor_apicallitem.h" #include "vogleditor_frameitem.h" #include "vogleditor_tracereplayer.h" #include "vogl_find_files.h" #include "vogl_file_utils.h" #include "vogl_gl_replayer.h" #include "vogleditor_output.h" vogleditor_traceReplayer::vogleditor_traceReplayer() : m_pTraceReplayer(vogl_new(vogl_gl_replayer)) { } vogleditor_traceReplayer::~vogleditor_traceReplayer() { if (m_pTraceReplayer != NULL) { vogl_delete(m_pTraceReplayer); m_pTraceReplayer = NULL; } } void vogleditor_traceReplayer::enable_screenshot_capturing(std::string screenshot_prefix) { m_screenshot_prefix = screenshot_prefix; } void vogleditor_traceReplayer::enable_fs_preprocessor(std::string fs_preprocessor) { m_fs_preprocessor = fs_preprocessor; } bool vogleditor_traceReplayer::process_events() { SDL_Event wnd_event; while (SDL_PollEvent(&wnd_event)) { switch (wnd_event.type) { case SDL_WINDOWEVENT_SHOWN: case SDL_WINDOWEVENT_RESTORED: { m_pTraceReplayer->update_window_dimensions(); break; } case SDL_WINDOWEVENT_MOVED: case SDL_WINDOWEVENT_RESIZED: { m_pTraceReplayer->update_window_dimensions(); break; } case SDL_WINDOWEVENT: { switch (wnd_event.window.event) { case SDL_WINDOWEVENT_CLOSE: vogl_message_printf("Exiting\n"); return false; break; default: break; }; break; } default: break; } } return true; } bool vogleditor_traceReplayer::applying_snapshot_and_process_resize(const vogl_gl_state_snapshot *pSnapshot) { vogl_gl_replayer::status_t status = m_pTraceReplayer->begin_applying_snapshot(pSnapshot, false); bool bStatus = true; while (status == vogl_gl_replayer::cStatusResizeWindow) { vogleditor_output_message("Waiting for replay window to resize."); // Pump X events in case the window is resizing if (process_events()) { status = m_pTraceReplayer->process_pending_window_resize(); } else { bStatus = false; break; } } if (bStatus && status != vogl_gl_replayer::cStatusOK) { vogleditor_output_error("Replay unable to apply snapshot"); bStatus = false; } return bStatus; } vogleditor_tracereplayer_result vogleditor_traceReplayer::take_state_snapshot_if_needed(vogleditor_gl_state_snapshot **ppNewSnapshot, uint32_t apiCallNumber) { vogleditor_tracereplayer_result result = VOGLEDITOR_TRR_SUCCESS; if (ppNewSnapshot != NULL) { // get the snapshot after the selected api call if ((!*ppNewSnapshot) && (m_pTraceReplayer->get_last_processed_call_counter() == static_cast<int64_t>(apiCallNumber))) { dynamic_string info; vogleditor_output_message(info.format("Taking snapshot on API call # %u...", apiCallNumber).c_str()); vogl_gl_state_snapshot *pNewSnapshot = m_pTraceReplayer->snapshot_state(); if (pNewSnapshot == NULL) { result = VOGLEDITOR_TRR_ERROR; vogleditor_output_error("... snapshot failed!"); } else { result = VOGLEDITOR_TRR_SNAPSHOT_SUCCESS; vogleditor_output_message("... snapshot succeeded!\n"); *ppNewSnapshot = vogl_new(vogleditor_gl_state_snapshot, pNewSnapshot); if (*ppNewSnapshot == NULL) { result = VOGLEDITOR_TRR_ERROR; vogleditor_output_error("Allocating memory for snapshot container failed!"); vogl_delete(pNewSnapshot); } } } } return result; } inline bool status_indicates_end(vogl_gl_replayer::status_t status) { return (status == vogl_gl_replayer::cStatusHardFailure) || (status == vogl_gl_replayer::cStatusAtEOF); } vogleditor_tracereplayer_result vogleditor_traceReplayer::recursive_replay_apicallTreeItem(vogleditor_apiCallTreeItem *pItem, vogleditor_gl_state_snapshot **ppNewSnapshot, uint64_t apiCallNumber) { vogleditor_tracereplayer_result result = VOGLEDITOR_TRR_SUCCESS; if (pItem->frameItem() != NULL && m_screenshot_prefix.size() > 0) { // take screenshot m_pTraceReplayer->snapshot_backbuffer(); dynamic_string screenshot_filename; pItem->frameItem()->set_screenshot_filename(screenshot_filename.format("%s_%07" PRIu64 ".png", m_screenshot_prefix.c_str(), pItem->frameItem()->frameNumber())); } vogleditor_apiCallItem *pApiCall = pItem->apiCallItem(); if (pApiCall != NULL) { vogl_trace_packet *pTrace_packet = pApiCall->getTracePacket(); vogl_gl_replayer::status_t status = vogl_gl_replayer::cStatusOK; // See if a window resize or snapshot is pending. If a window resize is pending we must delay a while and pump X events until the window is resized. while (m_pTraceReplayer->get_has_pending_window_resize() || m_pTraceReplayer->get_pending_apply_snapshot()) { // Pump X events in case the window is resizing if (process_events()) { status = m_pTraceReplayer->process_pending_window_resize(); if (status != vogl_gl_replayer::cStatusResizeWindow) break; } else { // most likely the window wants to close, so let's return return VOGLEDITOR_TRR_USER_EXIT; } } // process pending trace packets (this could include glXMakeCurrent) if (!status_indicates_end(status) && m_pTraceReplayer->has_pending_packets()) { status = m_pTraceReplayer->process_pending_packets(); // if that was successful, check to see if a state snapshot is needed if (!status_indicates_end(status)) { // update gl entrypoints if needed if (vogl_is_make_current_entrypoint(pTrace_packet->get_entrypoint_id()) && load_gl()) { vogl_init_actual_gl_entrypoints(vogl_get_proc_address_helper); } result = take_state_snapshot_if_needed(ppNewSnapshot, apiCallNumber); } } // replay the trace packet if (!status_indicates_end(status)) status = m_pTraceReplayer->process_next_packet(*pTrace_packet); // if that was successful, check to see if a state snapshot is needed if (!status_indicates_end(status)) { // update gl entrypoints if needed if (vogl_is_make_current_entrypoint(pTrace_packet->get_entrypoint_id()) && load_gl()) { vogl_init_actual_gl_entrypoints(vogl_get_proc_address_helper); } result = take_state_snapshot_if_needed(ppNewSnapshot, apiCallNumber); } else { // replaying the trace packet failed, set as error result = VOGLEDITOR_TRR_ERROR; dynamic_string info; vogleditor_output_error(info.format("Unable to replay gl entrypoint at call %" PRIu64, pTrace_packet->get_call_counter()).c_str()); } } if (result == VOGLEDITOR_TRR_SUCCESS && pItem->has_snapshot() && pItem->get_snapshot()->is_edited() && pItem->get_snapshot()->is_valid()) { if (applying_snapshot_and_process_resize(pItem->get_snapshot()->get_snapshot())) { result = VOGLEDITOR_TRR_SUCCESS; } } if (result == VOGLEDITOR_TRR_SUCCESS) { for (int i = 0; i < pItem->childCount(); i++) { result = recursive_replay_apicallTreeItem(pItem->child(i), ppNewSnapshot, apiCallNumber); if (result != VOGLEDITOR_TRR_SUCCESS) break; // Pump X events in case the window is resizing if (process_events() == false) { // most likely the window wants to close, so let's return return VOGLEDITOR_TRR_USER_EXIT; } } } return result; } vogleditor_tracereplayer_result vogleditor_traceReplayer::replay(vogl_trace_file_reader *m_pTraceReader, vogleditor_apiCallTreeItem *pRootItem, vogleditor_gl_state_snapshot **ppNewSnapshot, uint64_t apiCallNumber, bool endlessMode) { // reset to beginnning of trace file. m_pTraceReader->seek_to_frame(0); int initial_window_width = 1280; int initial_window_height = 1024; if (!m_window.open(initial_window_width, initial_window_height)) { vogleditor_output_error("Failed opening GL replayer window!"); return VOGLEDITOR_TRR_ERROR; } uint replayer_flags = cGLReplayerForceDebugContexts; if (m_screenshot_prefix.size() > 0) { replayer_flags |= cGLReplayerDumpScreenshots; m_pTraceReplayer->set_screenshot_prefix(m_screenshot_prefix.c_str()); } if (m_fs_preprocessor.size() > 0) { replayer_flags |= cGLReplayerFSPreprocessor; m_pTraceReplayer->set_fs_preprocessor(m_fs_preprocessor.c_str()); // Only check FSpp options when FS preprocessor is enabled if (m_fs_preprocessor_options.size() > 0) m_pTraceReplayer->set_fs_preprocessor_options(m_fs_preprocessor_options.c_str()); if (m_fs_preprocessor_prefix.size() > 0) m_pTraceReplayer->set_fs_preprocessor_prefix(m_fs_preprocessor_prefix.c_str()); } if (!m_pTraceReplayer->init(replayer_flags, &m_window, m_pTraceReader->get_sof_packet(), m_pTraceReader->get_multi_blob_manager())) { vogleditor_output_error("Failed initializing GL replayer!"); m_window.close(); return VOGLEDITOR_TRR_ERROR; } timer tm; tm.start(); vogleditor_tracereplayer_result result = VOGLEDITOR_TRR_SUCCESS; for (;;) { if (process_events() == false) { result = VOGLEDITOR_TRR_USER_EXIT; break; } if (pRootItem->childCount() > 0) { vogleditor_apiCallTreeItem *pFirstFrame = pRootItem->child(0); bool bStatus = true; // if the first snapshot has not been edited, then restore it here, otherwise it will get restored in the recursive call below. if (pFirstFrame->has_snapshot() && !pFirstFrame->get_snapshot()->is_edited()) { // Attempt to initialize GL func pointers here so they're available when loading from a snapshot at start of trace if (load_gl()) vogl_init_actual_gl_entrypoints(vogl_get_proc_address_helper); bStatus = applying_snapshot_and_process_resize(pFirstFrame->get_snapshot()->get_snapshot()); } if (bStatus) { // replay each API call. result = recursive_replay_apicallTreeItem(pRootItem, ppNewSnapshot, apiCallNumber); if (result == VOGLEDITOR_TRR_ERROR) { QString msg = QString("Replay ending abruptly at frame index %1, global api call %2").arg(m_pTraceReplayer->get_frame_index()).arg(m_pTraceReplayer->get_last_processed_call_counter()); vogleditor_output_error(msg.toStdString().c_str()); break; } else if (result == VOGLEDITOR_TRR_SNAPSHOT_SUCCESS) { break; } else if (result == VOGLEDITOR_TRR_USER_EXIT) { vogleditor_output_message("Replay stopped"); break; } else { QString msg = QString("At trace EOF, frame index %1").arg(m_pTraceReplayer->get_frame_index()); vogleditor_output_message(msg.toStdString().c_str()); if (!endlessMode) { break; } } } else { break; } } } m_pTraceReplayer->deinit(); m_window.close(); return result; } bool vogleditor_traceReplayer::pause() { VOGL_ASSERT(!"Not implemented"); return false; } bool vogleditor_traceReplayer::restart() { VOGL_ASSERT(!"Not implemented"); return false; } bool vogleditor_traceReplayer::trim() { VOGL_ASSERT(!"Not implemented"); return false; } bool vogleditor_traceReplayer::stop() { VOGL_ASSERT(!"Not implemented"); return false; }
VolgaKurvar/AtCoder
ABC117/ABC117c.py
<reponame>VolgaKurvar/AtCoder<gh_stars>0 # ABC117c import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) n, m = map(int, input().split()) x = list(map(int, input().split())) x.sort() sa = [] for i in range(1, m): sa.append(x[i]-x[i-1]) print(x) print(sa) print('aa') for haba in range(x[-1]+1): last = -99999999 koma = [] for i in x: if last+haba < i: if(len(koma) >= n): break last = i koma.append(i) koma.append(x[-1]+1) print(koma) cost = 0 for j in range(1, len(koma)): for i in range(len(x)): if(koma[j-1] == x[i]): continue if(koma[j-1] <= x[i] < koma[j]): print(koma[j-1], x[i], sa[i]) cost += sa[i] continue else: break print(cost)
SeanGaoTesing/halo-master
src/main/java/run/halo/app/exception/ThemeNotFoundException.java
package run.halo.app.exception; /** * Theme not found exception. * * @author johnniang * @date 2020-03-01 */ public class ThemeNotFoundException extends BadRequestException { public ThemeNotFoundException(String message) { super(message); } public ThemeNotFoundException(String message, Throwable cause) { super(message, cause); } }
philipptrenz/conex.io
src/main/java/io/swagger/exception/HomeAutomationServerNotReachableException.java
package io.swagger.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * The Class HomeAutomationServerNotReachableException. * * @author <NAME> */ @ResponseStatus(value=HttpStatus.SERVICE_UNAVAILABLE, reason="The home automation server is not reachable") public class HomeAutomationServerNotReachableException extends Exception { /** * Instantiates a new home automation server not reachable exception. */ public HomeAutomationServerNotReachableException() { super(); } /** * Instantiates a new home automation server not reachable exception. * * @param arg0 the arg 0 */ public HomeAutomationServerNotReachableException(String arg0) { super(arg0); } }
davidyuan/WagonWar
cocos2d/cocos/editor-support/cocostudio/WidgetReader/TextBMFontReader/TextBMFontReader.cpp
#include "TextBMFontReader.h" #include "ui/UITextBMFont.h" USING_NS_CC; using namespace ui; namespace cocostudio { static TextBMFontReader* instanceTextBMFontReader = NULL; IMPLEMENT_CLASS_WIDGET_READER_INFO(TextBMFontReader) TextBMFontReader::TextBMFontReader() { } TextBMFontReader::~TextBMFontReader() { } TextBMFontReader* TextBMFontReader::getInstance() { if (!instanceTextBMFontReader) { instanceTextBMFontReader = new TextBMFontReader(); } return instanceTextBMFontReader; } void TextBMFontReader::setPropsFromJsonDictionary(Widget *widget, const rapidjson::Value &options) { WidgetReader::setPropsFromJsonDictionary(widget, options); std::string jsonPath = GUIReader::getInstance()->getFilePath(); TextBMFont* labelBMFont = static_cast<TextBMFont*>(widget); const rapidjson::Value& cmftDic = DICTOOL->getSubDictionary_json(options, "fileNameData"); int cmfType = DICTOOL->getIntValue_json(cmftDic, "resourceType"); switch (cmfType) { case 0: { std::string tp_c = jsonPath; const char* cmfPath = DICTOOL->getStringValue_json(cmftDic, "path"); const char* cmf_tp = tp_c.append(cmfPath).c_str(); labelBMFont->setFntFile(cmf_tp); break; } case 1: CCLOG("Wrong res type of LabelAtlas!"); break; default: break; } const char* text = DICTOOL->getStringValue_json(options, "text"); labelBMFont->setText(text); WidgetReader::setColorPropsFromJsonDictionary(widget, options); } }
bk7084/framework
bk7084/geometry/ray.py
<filename>bk7084/geometry/ray.py from typing import Sequence import numpy as np from .shape import Shape from ..graphics.util import DrawingMode from ..math import Vec3 from ..misc import Color, PaletteDefault class Ray(Shape): def __init__(self, origin, direction, colors: Sequence[Color] = (PaletteDefault.GreenB.as_color(),)): super().__init__(2, colors) self._o = Vec3(origin) if not isinstance(origin, Vec3) else origin self._d = Vec3(direction) if not isinstance(direction, Vec3) else direction def __str__(self): _str = 'Ray ⚬ {} ⟶ {}' return _str.format(self._o, self._d) @property def vertices(self) -> np.ndarray: return np.concatenate([self._o, self._o + self._d]).ravel() @property def vertex_count(self) -> int: return 2 @property def drawing_mode(self) -> DrawingMode: return DrawingMode.Lines @property def origin(self): return self._o @origin.setter def origin(self, value: Vec3): self._o = value @property def direction(self): return self._d @direction.setter def direction(self, value: Vec3): self._d = value @property def indices(self): return np.array([0, 1], dtype=int) @property def index_count(self): return 2
UPB-FILS/alg
TP/TP2/ex11.js
'use strict'; var etudiants = [ { nom: 'Ion', prenom: 'Mihai', points_credit: 35}, { nom: 'Popescu', prenom: 'Stefan', points_credit: 120}, { nom: 'Dumitru', prenom: 'Ana-Maria', points_credit: 200}, { nom: 'Vasile', prenom: 'Anca', points_credit: 170}, { nom: 'Stanescu', prenom: 'George', points_credit: 100} ]; function sortArray (property) { etudiants = etudiants.sort (function (a, b) { let propA = a[property]; let propB = b[property]; if (propA < propB) { return -1; } if (propA > propB) { return 1; } return 0; }); return etudiants; } console.log(sortArray('points_credit'));
dongLeHappy/vue_manage
src/api/lotteryCore/lc_timeTimeLottery/generalHigherPercent.js
<reponame>dongLeHappy/vue_manage import request from '@/utils/request' export function getTypeOrPercent() { // 游戏玩法管理接口 return request({ baseURL: 'http://192.168.50.81/mock/', // 请求自己配的json url: '/5c9f805b21d4990ddb61f672/lotteryCore/lcConfig/lc_config/timeTimeLottery/generalHigherPercent', method: 'get' }) }
mikkel1156/drago
drago/state/etcd/interface.go
package etcd import ( "context" "errors" structs "github.com/seashell/drago/drago/structs" "go.etcd.io/etcd/clientv3" ) // Interfaces : func (r *StateRepository) Interfaces(ctx context.Context) ([]*structs.Interface, error) { prefix := resourceKey(resourceTypeInterface, "") res, err := r.client.Get(ctx, prefix, clientv3.WithPrefix(), clientv3.WithSort(clientv3.SortByVersion, clientv3.SortDescend)) if err != nil { return nil, err } items := []*structs.Interface{} for _, el := range res.Kvs { iface := &structs.Interface{} if err := decodeValue(el.Value, iface); err != nil { return nil, err } items = append(items, iface) } return items, nil } // InterfacesByNodeID : func (r *StateRepository) InterfacesByNodeID(ctx context.Context, id string) ([]*structs.Interface, error) { prefix := resourceKey(resourceTypeInterface, "") res, err := r.client.Get(ctx, prefix, clientv3.WithPrefix(), clientv3.WithSort(clientv3.SortByVersion, clientv3.SortDescend)) if err != nil { return nil, err } items := []*structs.Interface{} for _, el := range res.Kvs { iface := &structs.Interface{} if err := decodeValue(el.Value, iface); err != nil { return nil, err } if iface.NodeID == id { items = append(items, iface) } } return items, nil } // InterfacesByNetworkID : func (r *StateRepository) InterfacesByNetworkID(ctx context.Context, id string) ([]*structs.Interface, error) { prefix := resourceKey(resourceTypeInterface, "") res, err := r.client.Get(ctx, prefix, clientv3.WithPrefix(), clientv3.WithSort(clientv3.SortByVersion, clientv3.SortDescend)) if err != nil { return nil, err } items := []*structs.Interface{} for _, el := range res.Kvs { iface := &structs.Interface{} if err := decodeValue(el.Value, iface); err != nil { return nil, err } if iface.NetworkID == id { items = append(items, iface) } } return items, nil } // InterfaceByID : func (r *StateRepository) InterfaceByID(ctx context.Context, id string) (*structs.Interface, error) { key := resourceKey(resourceTypeInterface, id) res, err := r.client.Get(ctx, key) if err != nil { return nil, err } if res.Count == 0 { return nil, errors.New("not found") } iface := &structs.Interface{} if err = decodeValue(res.Kvs[0].Value, iface); err != nil { return nil, err } return iface, nil } // UpsertInterface : func (r *StateRepository) UpsertInterface(ctx context.Context, n *structs.Interface) error { key := resourceKey(resourceTypeInterface, n.ID) if _, err := r.client.Put(ctx, key, encodeValue(n)); err != nil { return err } return nil } // DeleteInterfaces : func (r *StateRepository) DeleteInterfaces(ctx context.Context, ids []string) error { for _, id := range ids { key := resourceKey(resourceTypeInterface, id) if _, err := r.client.Delete(ctx, key); err != nil { return err } } return nil }
uthark/homebrew-core
Formula/djvu2pdf.rb
class Djvu2pdf < Formula desc "Small tool to convert Djvu files to PDF files" homepage "https://0x2a.at/site/projects/djvu2pdf/" url "https://0x2a.at/site/projects/djvu2pdf/djvu2pdf-0.9.2.tar.gz" sha256 "afe86237bf4412934d828dfb5d20fe9b584d584ef65b012a893ec853c1e84a6c" bottle :unneeded depends_on "djvulibre" depends_on "ghostscript" def install bin.install "djvu2pdf" man1.install "djvu2pdf.1.gz" end test do system "#{bin}/djvu2pdf", "-h" end end
hetmanchuk/control
pkg/workflows/steps/amazon/create_vpc_test.go
<filename>pkg/workflows/steps/amazon/create_vpc_test.go package amazon import ( "bytes" "context" "os" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" "github.com/pkg/errors" "github.com/stretchr/testify/require" "github.com/supergiant/control/pkg/clouds" "github.com/supergiant/control/pkg/profile" "github.com/supergiant/control/pkg/workflows/steps" ) type fakeEC2VPC struct { ec2iface.EC2API createVPCOutput *ec2.CreateVpcOutput describeVPCOutput *ec2.DescribeVpcsOutput err error } func (f *fakeEC2VPC) CreateVpcWithContext(aws.Context, *ec2.CreateVpcInput, ...request.Option) (*ec2.CreateVpcOutput, error) { return f.createVPCOutput, f.err } func (f *fakeEC2VPC) DescribeVpcsWithContext(aws.Context, *ec2.DescribeVpcsInput, ...request.Option) (*ec2.DescribeVpcsOutput, error) { return f.describeVPCOutput, f.err } func (f *fakeEC2VPC) WaitUntilVpcExistsWithContext(aws.Context, *ec2.DescribeVpcsInput, ...request.WaiterOption) error { return nil } func TestCreateVPCStep_Run(t *testing.T) { tt := []struct { awsFN GetEC2Fn err error awsCfg steps.AWSConfig }{ { func(config steps.AWSConfig) (ec2iface.EC2API, error) { return &fakeEC2VPC{ createVPCOutput: &ec2.CreateVpcOutput{ Vpc: &ec2.Vpc{ VpcId: aws.String("ID"), }, }, }, ErrAuthorization }, ErrAuthorization, steps.AWSConfig{}, }, { func(config steps.AWSConfig) (ec2iface.EC2API, error) { return &fakeEC2VPC{ createVPCOutput: &ec2.CreateVpcOutput{ Vpc: &ec2.Vpc{ VpcId: aws.String("ID"), }, }, }, nil }, nil, steps.AWSConfig{}, }, { //happy path func(config steps.AWSConfig) (ec2iface.EC2API, error) { return &fakeEC2VPC{ createVPCOutput: &ec2.CreateVpcOutput{ Vpc: &ec2.Vpc{ VpcId: aws.String("ID"), }, }, }, nil }, nil, steps.AWSConfig{}, }, { //happy path func(config steps.AWSConfig) (ec2iface.EC2API, error) { return &fakeEC2VPC{ createVPCOutput: &ec2.CreateVpcOutput{ Vpc: &ec2.Vpc{ VpcId: aws.String("ID"), }, }, err: errors.New("error"), }, nil }, ErrCreateVPC, steps.AWSConfig{}, }, { //error, vpc id was provided but isn't available in the AWS func(config steps.AWSConfig) (ec2iface.EC2API, error) { return &fakeEC2VPC{ err: errors.New(""), }, nil }, ErrReadVPC, steps.AWSConfig{ VPCID: "1", }, }, { func(config steps.AWSConfig) (ec2iface.EC2API, error) { return &fakeEC2VPC{ describeVPCOutput: &ec2.DescribeVpcsOutput{ Vpcs: []*ec2.Vpc{ { VpcId: aws.String("1"), IsDefault: aws.Bool(true), CidrBlock: aws.String("10.20.30.40/16"), }, }, }, }, nil }, nil, steps.AWSConfig{ VPCID: "1", }, }, { func(config steps.AWSConfig) (ec2iface.EC2API, error) { return &fakeEC2VPC{ describeVPCOutput: &ec2.DescribeVpcsOutput{ Vpcs: []*ec2.Vpc{ { VpcId: aws.String("default"), CidrBlock: aws.String("10.20.30.40/16"), IsDefault: aws.Bool(true), }, }, }, }, nil }, nil, steps.AWSConfig{ VPCID: "default", }, }, } for i, tc := range tt { cfg := steps.NewConfig("TEST", "", "TEST", profile.Profile{ Region: "us-east-1", Provider: clouds.AWS, }) cfg.AWSConfig = tc.awsCfg step := NewCreateVPCStep(tc.awsFN) err := step.Run(context.Background(), os.Stdout, cfg) if tc.err == nil { require.NoError(t, err, "TC%d, %v", i, err) } else { require.True(t, tc.err == errors.Cause(err), "TC%d, %v", i, err) } } } func TestInitCreateVPC(t *testing.T) { InitCreateVPC(GetEC2) s := steps.GetStep(StepCreateVPC) if s == nil { t.Errorf("Step must not be nil") } } func TestNewCreateVPCStep(t *testing.T) { s := NewCreateVPCStep(GetEC2) if s == nil { t.Errorf("Step must not be nil") } if s.GetEC2 == nil { t.Errorf("GetEC2 func must not be nil") } if api, err := s.GetEC2(steps.AWSConfig{}); err != nil || api == nil { t.Errorf("Wrong values %v %v", api, err) } } func TestNewCreateVPCStepErr(t *testing.T) { fn := func(steps.AWSConfig) (ec2iface.EC2API, error) { return nil, errors.New("errorMessage") } s := NewCreateVPCStep(fn) if s == nil { t.Errorf("Step must not be nil") } if s.GetEC2 == nil { t.Errorf("GetEC2 func must not be nil") } if api, err := s.GetEC2(steps.AWSConfig{}); err == nil || api != nil { t.Errorf("Wrong values %v %v", api, err) } } func TestCreateVPCStep_Depends(t *testing.T) { s := &CreateVPCStep{} if deps := s.Depends(); deps != nil { t.Errorf("deps must not be nil") } } func TestCreateVPCStep_Name(t *testing.T) { s := &CreateVPCStep{} if name := s.Name(); name != StepCreateVPC { t.Errorf("Wrong step name expected %s actual %s", StepCreateVPC, s.Name()) } } func TestCreateVPCStep_Description(t *testing.T) { s := &CreateVPCStep{} if desc := s.Description(); desc != "create a vpc in aws or reuse existing one" { t.Errorf("Wrong step desc expected "+ "create a vpc in aws or reuse existing one actual %s", s.Description()) } } func TestCreateVPCStep_Rollback(t *testing.T) { s := &CreateVPCStep{} if err := s.Rollback(context.Background(), &bytes.Buffer{}, &steps.Config{}); err != nil { t.Errorf("Unexpected error while rolback") } }
Eshavish/TwitterAPIwithZip
node_modules/hdma-geoviewer/public/geoviewer/dev/v2.0/js/api/hdma.util.js
<reponame>Eshavish/TwitterAPIwithZip if(!window.hdma){window.hdma={}} hdma.util={ /** * convert javascript object to html * @param {Object} obj * @param {Array} notShowArray is an array of string which is not shown in the html * @return {String} html string */ objectToHtml: function(obj, notShowArray){ if(!obj){console.log("[ERROR]hdma.util.objectToHtml: obj is null!");return;} if(!notShowArray){notShowArray=[]} var html="<ul class='objToHtml'>"; for(var k in obj){ //if k (a property) is not in the notShowArray($.inArray(k, notShowArray)==-1) if($.inArray(k, notShowArray)==-1){ html+="<li><b>"+k+"</b>: " + obj[k] + "</li>"; } } html+="</ul>"; return html; }, /** * highlight keyword */ highlightKeyword: function(keywords, html){ //highlight keyword var rgxp,rep1; $.each(keywords, function(j,keyword){ rgxp = new RegExp(keyword, 'ig'); repl = '<span class="highlightKeyword">' + keyword + '</span>'; html = html.replace(rgxp, repl); }); return html; }, /** * read all features properies in the cluster */ readClusterFeatureProperies: function(clusterObj, properties, propertyName){ if(clusterObj._markers && clusterObj._markers.length>0){ $.each(clusterObj._markers, function(i,marker){ properties.push(marker[propertyName]); }); } if(clusterObj._childClusters && clusterObj._childClusters.length>0){ $.each(clusterObj._childClusters, function(i,cluster){ properties.concat(hdma.util.readClusterFeatureProperies(cluster, properties, propertyName)); }); } return properties; }, /** * parse geojsonProperties to Array * @param {GEOJSON} geojson can be featureColleciton or a feature * @return {Object} containing {columns: an array of titles, datas: an array of properties} */ geojsonPropertiesToArray: function(geojson, options){ if(!geojson){console.log("[ERROR] hdma.util.geoJsonPropertiesToArray: no geojson");return;} var obj={ columns_dataTable:[], columns:[], datas:[], googleChartData:[], statisticsColumn:{} } //options if(!options){options={}} options.statisticsColumn=options.statisticsColumn || null if(options.statisticsColumn){ obj.statisticsColumn[options.statisticsColumn]={ "sum":0 }; } //if geojson is an array if(geojson instanceof Array){ geojson={type:"FeatureCollection", features:geojson}; } //geojson is featureCollection if(geojson.type.toUpperCase()=='FEATURECOLLECTION'){ $.each(geojson.features, function(i, feature){ //get columns if(i==0){ var temp=parseFeature(i, feature, true); obj.columns_dataTable=temp.columns_dataTable; obj.columns=temp.columns; obj.datas.push(temp.datas); }else{ obj.datas.push(parseFeature(i, feature, false).datas) } //statistics if(options.statisticsColumn){ obj.statisticsColumn[options.statisticsColumn]['sum']+=parseFloat(feature.properties[options.statisticsColumn]) } }); } //geojson is a feature if(geojson.type.toUpperCase()=='FEATURE'){ var temp=parseFeature(0, geojson, true); obj.columns=temp.columns; obj.columns_dataTable=temp.columns_dataTable; obj.datas.push(temp.datas); } //googleChartData obj.googleChartData=obj.datas.slice(0); obj.googleChartData.splice(0,0,obj.columns); return obj; //parse Feature function parseFeature(i, feature, needColumns){ var columns_dataTable=[], columns=[], datas=[]; datas[0]=i+1; //for ID if(needColumns){ columns_dataTable[0]={"sTitle": "ID"} columns[0]="ID"; } //if (!options.orderedColumns) { $.each(feature.properties, function(k,v){ //check if td contains http hyperlink var hasHyperlink=false, value=String(v).toUpperCase(); if(value.indexOf("HTTP://")>=0 || value.indexOf("HTTPS://")>=0){ //start from http:// v=hdma.util.linkify(String(v)); hasHyperlink=true; } if(needColumns){ var obj={"sTitle": k}; if(hasHyperlink){ obj.sType='html'; } columns_dataTable.push(obj) columns.push(k); } datas.push(v); }); //add coordinates if(feature.geometry.type=="Point"){ if(needColumns){ columns_dataTable.push({"sTitle": "Coordinates"}); columns.push("Coordinates"); }; var lat=feature.geometry.coordinates[1].toFixed(3), lng=feature.geometry.coordinates[0].toFixed(3) datas.push(lng+", "+lat); } return {columns:columns, columns_dataTable:columns_dataTable, datas:datas} } }, /** * convert text to link if contains http, https, ftp, mailto * from http://stackoverflow.com/questions/247479/jquery-text-to-link-script * @param {String} content */ linkify: function(content){ var url1 = /(^|&lt;|\s)(www\..+?\..+?)(\s|&gt;|$)/g, url2 = /(^|&lt;|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|&gt;|$)/g; content = content.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(url1, '$1<a target="_blank" href="http://$2">$2</a>$3') .replace(url2, '$1<a target="_blank" href="$2">$2</a>$5'); return content }, /** * create wordcloud */ //create wordCloud beta createWordCloud: function(cloudtexts, $target, options) { var $target, colors = d3.scale.category20b(), maxcount = 0; //options if(!options){options={}} var width=options.width=options.width || $(document).width() var height=options.height=options.height || 400 //find max for (var indx in cloudtexts) if (cloudtexts[indx].count > maxcount) { maxcount = cloudtexts[indx].count;} //data var data=cloudtexts.map(function(d){ return {text: d.value, size: Math.sqrt(d.count/maxcount *100)*10}; }) if (!app.wordcloud) { app.wordcloud = d3.layout.cloud().size([width, height]) .words(data) .rotate(function() { return ~~(Math.random() * 1) * 90; }) .font("Impact") .spiral("archimedean") //.spiral("rectangular") .fontSize(function(d) { return d.size; }) .on("end", draw) .start(); } else { app.wordcloud.stop().words(data).on("end", draw).start(); } function search(keyword) { console.log(keyword); } function draw(words) { //d3.select("svg").remove(); d3.select($target.selector).append("svg") .attr("width", width) .attr("height", height) .attr("style", "border-color:lightgray;border-style:solid;border-width:0px;") .attr("viewBox","0 0 "+width+" "+ height) .attr("preserveAspectRatio", "xMidYMid") .append("g") .attr("transform", "translate(" + (width/2) + "," + (height/2) + ")") .selectAll("text") .data(words) .enter().append("text") .style("font-size", function(d) { return d.size + "px"; }) .style("font-family", "Impact") .attr("text-anchor", "middle") .attr("transform", function(d) { return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")"; }) .text(function(d) { return d.text; }); $("text").css("fill", function() { return colors(this.__data__.text.toLowerCase()); }) $("text").click(function() { search(this.__data__.text); }).css("cursor", "pointer") //.mouseover(function() { $(this).css("fill", "#cc2222"); }) .mouseover(function() { $(this).css("fill", "#22aa22"); }) .mouseout(function() { $(this).css("fill", colors(this.__data__.text.toLowerCase())); }); } } }
jiuchongyangzy/tangxiaoyi
gen/com/goide/psi/GoForStatement.java
<gh_stars>0 // This is a generated file. Not intended for manual editing. package com.goide.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface GoForStatement extends GoStatement { @Nullable GoBlock getBlock(); @Nullable GoExpression getExpression(); @Nullable GoForClause getForClause(); @Nullable GoRangeClause getRangeClause(); @NotNull PsiElement getFor(); }
One-E2-Team/ApartmentsWP
src/services/SearchService.java
package services; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import beans.ApartmentDeal; import beans.Reservation; import beans.apartment.Apartment; import beans.apartment.ApartmentStatus; import beans.user.Role; import beans.user.User; import repository.ApartmentRepository; import repository.NonWorkingDaysRepository; import repository.ReservationRepository; @Path("/search") public class SearchService { @SuppressWarnings("deprecation") @GET @Path("/apartments") @Produces(MediaType.APPLICATION_JSON) public Collection<ApartmentDeal> searchApartments(@Context HttpServletRequest request, @QueryParam("dateFrom") String dateF, @QueryParam("dateTo") String dateT, @QueryParam("location") String loc, @QueryParam("latitude") String latMap, @QueryParam("longitude") String longMap, @QueryParam("priceFrom") String priceF, @QueryParam("priceTo") String priceT, @QueryParam("roomsFrom") String roomsF, @QueryParam("roomsTo") String roomsT, @QueryParam("personsFrom") String personsF, @QueryParam("personsTo") String personsT) { Object obj = request.getSession().getAttribute("user"); Role role = obj == null ? Role.GUEST : ((User) obj).getRole(); User user = (User) obj; Date fromDate = null; Date toDate = null; String locationString = null; Double latitude = null; Double longitude = null; Double priceMin = null; Double priceMax = null; Integer roomsMin = null; Integer roomsMax = null; Integer personsMin = null; Integer personsMax = null; try { fromDate = new Date(dateF); } catch (Exception e) { } try { toDate = new Date(dateT); } catch (Exception e) { } locationString = loc.toLowerCase(); if (locationString.equals("")) locationString = null; try { latitude = Double.parseDouble(latMap); } catch (Exception e) { } try { longitude = Double.parseDouble(longMap); } catch (Exception e) { } try { priceMin = Double.parseDouble(priceF); } catch (Exception e) { } try { priceMax = Double.parseDouble(priceT); } catch (Exception e) { } try { roomsMin = Integer.parseInt(roomsF); } catch (Exception e) { } try { roomsMax = Integer.parseInt(roomsT); } catch (Exception e) { } try { personsMin = Integer.parseInt(personsF); } catch (Exception e) { } try { personsMax = Integer.parseInt(personsT); } catch (Exception e) { } LinkedList<ApartmentDeal> deals = new LinkedList<ApartmentDeal>(); Collection<Apartment> allApartments = ApartmentRepository.getInstance().getAll(); double angleTenKm = 10.0 * 360 / 40075; // Approximation, this defines be trapezoid shape on globe, since // latitude changes horizontal circumference if (fromDate == null && toDate == null && locationString == null && latitude == null && longitude == null && priceMin == null && priceMax == null && roomsMin == null && roomsMax == null && personsMin == null && personsMax == null) // in production return null here for (Apartment apartment : allApartments) { ApartmentDeal deal = new ApartmentDeal(); deal.setApartment(apartment); deals.add(deal); } else { for (Apartment apartment : allApartments) { if (((role.equals(Role.GUEST) && apartment.getStatus().equals(ApartmentStatus.ACTIVE) && !apartment.isDeleted()) || (role.equals(Role.HOST) && apartment.getHostId().equals(user.getUsername()) && !apartment.isDeleted()) || role.equals(Role.ADMINISTRATOR)) && (personsMin == null || apartment.getGuestNum() >= personsMin) && (personsMax == null || apartment.getGuestNum() <= personsMax) && (roomsMin == null || apartment.getRoomNum() >= roomsMin) && (roomsMax == null || apartment.getRoomNum() <= roomsMax) && (locationString == null || apartment.getLocation().getAddress().getCity().toLowerCase().contains(locationString) || apartment.getLocation().getAddress().getCountry().toLowerCase() .contains(locationString)) && (latitude == null || Math.abs(apartment.getLocation().getLatitude() - latitude) <= angleTenKm) && (longitude == null || Math.abs(apartment.getLocation().getLongitude() - longitude) <= angleTenKm) && ((fromDate == null && toDate == null) || apartmentFreeForDateSpan(apartment, fromDate, toDate))) { ApartmentDeal deal = new ApartmentDeal(); deal.setApartment(apartment); deals.add(deal); } } } if (fromDate != null && toDate != null) { for (ApartmentDeal ad : deals) ad.setDeal(getCostFactorForDates(fromDate, toDate) * ad.getApartment().getNightStayPrice()); } return deals.size() == 0 ? null : deals; } public static double getCostFactorForDates(Date fromDate, Date toDate) { int duration = (int) ((toDate.getTime() - fromDate.getTime()) / (60 * 60 * 24 * 1000)); double costFactor = 0; LinkedList<Date> nwd = NonWorkingDaysRepository.get(Calendar.getInstance().get(Calendar.YEAR)); // TODO for (int i = 0; i < duration; i++) { Date date = new Date(fromDate.getTime() + i * 60 * 60 * 24 * 1000); boolean foundHoliday = false; for (Date d : nwd) { if (d.getTime() == date.getTime()) { foundHoliday = true; break; } } if (foundHoliday) costFactor += 1.05; else costFactor += 1; } Calendar cal = Calendar.getInstance(); cal.setTime(fromDate); if (costFactor == (double) duration && duration >= 2 && duration <= 3 && cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) costFactor *= 0.9; return costFactor; } public static boolean apartmentFreeForDateSpan(Apartment apartment, Date from, Date to) { for (int resId : apartment.getReservationIds()) { Reservation reservation = ReservationRepository.getInstance().read(resId); if (!(to.before(reservation.getStartDate()) || (from.after(reservation.getStartDate()) && from.after(new Date(reservation.getStartDate().getTime() + reservation.getStayNights() * 60 * 60 * 24 * 1000))))) return false; } return true; } }
fathelen/BioDWH2
src/biodwh2-canadiannutrientfile/src/main/java/de/unibi/agbi/biodwh2/canadiannutrientfile/model/Measure.java
<gh_stars>1-10 package de.unibi.agbi.biodwh2.canadiannutrientfile.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonPropertyOrder({"MeasureID","MeasureDescription","MeasureDescriptionF"}) public class Measure { @JsonProperty("MeasureID") public String id; @JsonProperty("MeasureDescription") public String description; @JsonProperty("MeasureDescriptionF") public String descriptionFrench; }
leonardoc2o/nos.vc
acceptance/home_page_spec.rb
<reponame>leonardoc2o/nos.vc # coding: utf-8 require File.expand_path(File.dirname(__FILE__) + '/acceptance_helper') feature "Home Page Feature" do scenario "When I visit home page, it should show a compilation of projects and curated pages" do home_page = [ Factory(:project, created_at: 30.days.ago, expires_at: 30.days.from_now, visible: true, recommended: true), Factory(:project, created_at: 30.days.ago, expires_at: 30.days.from_now, visible: true, recommended: true), Factory(:project, created_at: 30.days.ago, expires_at: 30.days.from_now, visible: true, recommended: true), Factory(:project, created_at: 30.days.ago, expires_at: 30.days.from_now, visible: true, recommended: true), Factory(:project, created_at: 30.days.ago, expires_at: 30.days.from_now, visible: true, recommended: true), Factory(:project, created_at: 30.days.ago, expires_at: 30.days.from_now, visible: true, recommended: true), Factory(:project, created_at: 30.days.ago, expires_at: 30.days.from_now, visible: true, recommended: true) ] expiring = [ Factory(:project, created_at: 30.days.ago, expires_at: 2.days.from_now, visible: true), Factory(:project, created_at: 30.days.ago, expires_at: 3.days.from_now, visible: true), Factory(:project, created_at: 30.days.ago, expires_at: 4.days.from_now, visible: true), Factory(:project, created_at: 30.days.ago, expires_at: 5.days.from_now, visible: true) ] recent = [ Factory(:project, created_at: 2.days.ago, expires_at: 30.days.from_now, visible: true), Factory(:project, created_at: 3.days.ago, expires_at: 30.days.from_now, visible: true), Factory(:project, created_at: 4.days.ago, expires_at: 30.days.from_now, visible: true), Factory(:project, created_at: 5.days.ago, expires_at: 30.days.from_now, visible: true) ] successful = [ Factory(:project, created_at: 30.days.ago, expires_at: 2.days.ago, visible: true, goal: 2), Factory(:project, created_at: 30.days.ago, expires_at: 3.days.ago, visible: true, goal: 2), Factory(:project, created_at: 30.days.ago, expires_at: 4.days.ago, visible: true, goal: 2), Factory(:project, created_at: 30.days.ago, expires_at: 5.days.ago, visible: true, goal: 2) ] successful.each do |project| 2.times { Factory(:backer, project: project, value: project.goal, confirmed: true) } project.successful?.should be_true end curated_pages = [] 8.times{|t| curated_pages << Factory(:curated_page, created_at: t.days.ago, visible: true) } curated_pages << Factory(:curated_page, created_at: 2.days.ago, visible: false) visit homepage verify_translations within 'head title' do page.should have_content("#{I18n.t('site.title')} · #{I18n.t('site.name')}") end titles = all(".list_title .title h2") titles.shift.text.should have_content "NOSSOS DESTAQUES" titles.shift.text.should have_content "ÚLTIMA CHAMADA" titles.shift.text.should have_content "<NAME>" home_page_list = all(".selected_projects .curated_project") home_page_list.should have(3).items lists = all(".list") expiring_list = lists.shift.all(".curated_project") expiring_list.should have(3).items recent_list = lists.shift.all(".curated_project") recent_list.should have(3).items successful_list = lists.shift.all(".curated_project") successful_list.should have(3).items curated_pages_list = find(".partners").all("li") curated_pages_list.should have(8).items curated_pages_list.each_index do |index| within curated_pages_list[index] do find("a")[:href].should match(/\/#{curated_pages[index].permalink}/) end end end end
alanzh/alloy-ui
src/aui-editor/js/aui-editor-tools-plugin.js
<reponame>alanzh/alloy-ui var Lang = A.Lang, UA = A.UA, JUSTIFY = 'justify', BLOCK_TAGS = { div: true, h1: true, h2: true, h3: true, h4: true, h5: true, h6: true, p: true }, IGNORE_TAGS = { br: true }, ITEM_TAGS = { li: true }, TPL_JUSTIFY = '<div style="text-align: {0};">{1}</div>'; function findInsert(item) { var found = null; var childNodes = item.get('childNodes'); childNodes.some( function(item, index, collection) { if (item.get('innerHTML') == '{0}') { item.html(''); found = item; return true; } return findInsert(item); } ); return found; } function addWrapper(parent, item, html) { var wrapper = A.Node.create(html); parent.insert(wrapper, item); if (wrapper.html() != '') { if (wrapper.html() == '{0}') { wrapper.html(''); } else { var insert = findInsert(wrapper); if (insert) { wrapper = insert; } } } return wrapper; } function compareTextContent(innerItem, outerItem) { var attr = (UA.ie ? 'innerText' : 'textContent'); return (innerItem.get(attr) == outerItem.get(attr)); } var EditorTools = {}; A.mix( A.Plugin.ExecCommand.COMMANDS, { justify: function(cmd, val) { var instance = this; var host = instance.get('host'); var frame = host.getInstance(); var selection = new frame.Selection(); var items = selection.getSelected(); var insertHtml = false; if (selection.isCollapsed || !items.size()) { var anchorTextNode = selection.anchorTextNode; items = [anchorTextNode]; insertHtml = true; } A.each( items, function(item, index, collection) { var tagName = item.get('tagName'); if (tagName) { tagName = tagName.toLowerCase(); } if (IGNORE_TAGS[tagName]) { return; } if (tagName == 'font') { var tempNode = item.get('parentNode'); if (!tempNode.test('body')) { item = tempNode; tagName = item.get('tagName').toLowerCase(); } } if (!item.test('body') && item.getComputedStyle('textAlign') == val) { return; } var parent = item.get('parentNode'); var wrapper; if (BLOCK_TAGS[tagName] || item.getComputedStyle('display') == 'block') { wrapper = item; } else if (!parent.get('childNodes').item(1) || ITEM_TAGS[tagName]) { tagName = parent.get('tagName').toLowerCase(); if (BLOCK_TAGS[tagName] || parent.getComputedStyle('display') == 'block') { wrapper = parent; } } else { if (insertHtml) { host.execCommand('inserthtml', Lang.sub(TPL_JUSTIFY, [val, frame.Selection.CURSOR])); selection.focusCursor(true, true); return; } else { wrapper = A.Node.create(Lang.sub(TPL_JUSTIFY, [val, ''])); parent.insert(wrapper, item); wrapper.append(item); } } if (wrapper) { wrapper.setStyle('textAlign', val); } } ); }, justifycenter: function() { var instance = this; return instance.get('host').execCommand(JUSTIFY, 'center'); }, justifyleft: function() { var instance = this; return instance.get('host').execCommand(JUSTIFY, 'left'); }, justifyright: function() { var instance = this; return instance.get('host').execCommand(JUSTIFY, 'right'); }, subscript: function() { var instance = this; return instance.get('host').execCommand('wrap', 'sub'); }, superscript: function() { var instance = this; return instance.get('host').execCommand('wrap', 'sup'); }, wraphtml: function(cmd, val) { var instance = this; var host = instance.get('host'); var frame = host.getInstance(); var selection = new frame.Selection(); var items = selection.getSelected(); if (!selection.isCollapsed && items.size()) { var firstInner; var firstOuter; var lastInner; var lastOuter; var outerNodes; if (items.size() > 1) { var itemIndex; var itemTotal; items.each( function(item, index, collection) { var parent = item; var total = 0; var previous; while ((parent = parent.ancestor()) && !parent.test('body')) { total++; previous = parent; } if (itemTotal == null || total < itemTotal) { itemIndex = index; itemTotal = total; } } ); var item = items.item(itemIndex); var parent = (item.test('font') ? item.ancestor().ancestor() : item.ancestor()); var outerIndex = []; outerNodes = parent.get('childNodes'); items.each( function(item, index, collection) { var parent = item; var foundIndex = -1; if (item.ancestor().test('body')) { foundIndex = index; } else { while ((parent = parent.ancestor()) != null) { outerNodes.some( function(outerItem, outerIndex, outerCollection) { if (outerItem == parent) { foundIndex = outerIndex; return true; } } ); if (foundIndex != -1) { break; } } } outerIndex[index] = foundIndex; } ); if (outerIndex.length > 1) { var firstIndex; var lastIndex; for (var i = 0; i < outerIndex.length; i++) { if (outerIndex[i] != -1) { if (outerIndex[i] < firstIndex || firstIndex == null) { firstIndex = outerIndex[i]; firstInner = items.item(i); firstOuter = outerNodes.item(firstIndex); } if (outerIndex[i] > lastIndex || lastIndex == null) { lastIndex = outerIndex[i]; lastInner = items.item(i); lastOuter = outerNodes.item(lastIndex); } } else { firstOuter = null; break; } } } } if (firstOuter != null && ((firstOuter == lastOuter) || (compareTextContent(firstInner, firstOuter) && compareTextContent(lastInner, lastOuter)))) { var parent = firstOuter.ancestor(); var wrapper = addWrapper(parent, firstOuter, val); for (var i = firstIndex; i <= lastIndex; i++) { wrapper.append(outerNodes.item(i)); } } else { items.each( function(item, index, collection) { var tagName = item.get('tagName').toLowerCase(); if (!IGNORE_TAGS[tagName]) { var parent = item.ancestor(); var wrapper = addWrapper(parent, item, val); wrapper.append(item); } } ); } } else { host.execCommand('inserthtml', Lang.sub(val, [frame.Selection.CURSOR])); if (val.indexOf('{0}') != -1) { selection.focusCursor(true, true); } } } } ); A.Plugin.EditorTools = EditorTools;
Jcw87/urde
Editor/SplashScreen.cpp
#include "SplashScreen.hpp" #include "version.h" #include "badging/Badging.hpp" namespace metaforce { #define SPLASH_WIDTH 555 #define SPLASH_HEIGHT 300 #define WIRE_START 0 #define WIRE_FRAMES 60 #define SOLID_START 40 #define SOLID_FRAMES 40 #define TEXT_START 80 #define TEXT_FRAMES 40 #define LINE_WIDTH 2 #define TEXT_MARGIN 10 #define BADGE_WIDTH 551 #define BADGE_HEIGHT 217 #define BADGE_MARGIN 35 SplashScreen::SplashScreen(ViewManager& vm, specter::ViewResources& res) : ModalWindow(res, vm.rootView(), specter::RectangleConstraint(SPLASH_WIDTH * res.pixelFactor(), SPLASH_HEIGHT * res.pixelFactor())) , m_vm(vm) , m_textColor(res.themeData().uiText()) , m_textColorClear(m_textColor) , m_newString(m_vm.translate<locale::new_project>()) , m_openString(m_vm.translate<locale::open_project>()) , m_extractString(m_vm.translate<locale::extract_game>()) , m_newProjBind(*this) , m_openProjBind(*this) , m_extractProjBind(*this) { if (METAFORCE_WC_DATE[0] != '\0' && METAFORCE_WC_REVISION[0] != '\0' && METAFORCE_WC_BRANCH[0] != '\0') { m_buildInfoStr = fmt::format(FMT_STRING("{}: {}\n{}: {}\n{}: {}"), vm.translate<locale::version>(), METAFORCE_WC_DESCRIBE, vm.translate<locale::branch>(), METAFORCE_WC_BRANCH, vm.translate<locale::commit>(), METAFORCE_WC_REVISION/*, vm.translate<locale::date>(), METAFORCE_WC_DATE*/); } m_openProjBind.m_openRecentMenuRoot.m_text = vm.translate<locale::recent_projects>(); m_textColorClear[3] = 0.0; } void SplashScreen::think() { if (phase() == Phase::Done) { if (m_fileBrowser.m_view) m_fileBrowser.m_view.reset(); return; } ModalWindow::think(); if (m_fileBrowser.m_view) m_fileBrowser.m_view->think(); if (m_openButt.m_view) m_openButt.m_view->think(); if (m_newProjBind.m_deferPath.size()) { Log.report(logvisor::Info, FMT_STRING(_SYS_STR("Making project '{}'")), m_newProjBind.m_deferPath); m_vm.projectManager().newProject(m_newProjBind.m_deferPath); m_newProjBind.m_deferPath.clear(); } else if (m_openProjBind.m_deferPath.size()) { Log.report(logvisor::Info, FMT_STRING(_SYS_STR("Opening project '{}'")), m_openProjBind.m_deferPath); m_vm.projectManager().openProject(m_openProjBind.m_deferPath); m_openProjBind.m_deferPath.clear(); } else if (m_extractProjBind.m_deferPath.size()) { Log.report(logvisor::Info, FMT_STRING(_SYS_STR("Extracting game '{}'")), m_extractProjBind.m_deferPath); m_vm.projectManager().extractGame(m_extractProjBind.m_deferPath); m_extractProjBind.m_deferPath.clear(); } } void SplashScreen::updateContentOpacity(float opacity) { specter::ViewResources& res = rootView().viewRes(); if (!m_title && res.fontCacheReady()) { m_title.reset(new specter::TextView(res, *this, res.m_titleFont)); zeus::CColor clearColor = res.themeData().uiText(); clearColor[3] = 0.0; m_title->typesetGlyphs("URDE", clearColor); m_buildInfo.reset(new specter::MultiLineTextView(res, *this, res.m_mainFont, specter::TextView::Alignment::Right)); m_buildInfo->typesetGlyphs(m_buildInfoStr, clearColor); m_badgeIcon.reset(new specter::IconView(res, *this, GetBadge())); m_badgeText.reset(new specter::TextView(res, *this, res.m_heading18, specter::TextView::Alignment::Right)); m_badgeText->typesetGlyphs(BADGE_PHRASE, clearColor); m_newButt.m_view.reset( new specter::Button(res, *this, &m_newProjBind, m_newString, nullptr, specter::Button::Style::Text)); m_openButt.m_view.reset( new specter::Button(res, *this, &m_openProjBind, m_openString, nullptr, specter::Button::Style::Text)); m_extractButt.m_view.reset( new specter::Button(res, *this, &m_extractProjBind, m_extractString, nullptr, specter::Button::Style::Text)); updateSize(); } zeus::CColor clearColor = res.themeData().uiText(); clearColor[3] = 0.0; zeus::CColor color = zeus::CColor::lerp(clearColor, res.themeData().uiText(), opacity); m_title->colorGlyphs(color); m_buildInfo->colorGlyphs(color); m_badgeIcon->setMultiplyColor({1.f, 1.f, 1.f, color.a()}); m_badgeText->colorGlyphs(color); m_newButt.m_view->colorGlyphs(color); m_openButt.m_view->colorGlyphs(color); m_extractButt.m_view->colorGlyphs(color); } void SplashScreen::mouseDown(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mod) { if (skipBuildInAnimation()) return; if (m_fileBrowser.m_view && !m_fileBrowser.m_view->closed()) m_fileBrowser.m_view->mouseDown(coord, button, mod); else { m_newButt.mouseDown(coord, button, mod); m_openButt.mouseDown(coord, button, mod); m_extractButt.mouseDown(coord, button, mod); } } void SplashScreen::mouseUp(const boo::SWindowCoord& coord, boo::EMouseButton button, boo::EModifierKey mod) { if (m_fileBrowser.m_view && !m_fileBrowser.m_view->closed()) m_fileBrowser.m_view->mouseUp(coord, button, mod); else { m_newButt.mouseUp(coord, button, mod); m_openButt.mouseUp(coord, button, mod); m_extractButt.mouseUp(coord, button, mod); } } void SplashScreen::mouseMove(const boo::SWindowCoord& coord) { if (m_fileBrowser.m_view && !m_fileBrowser.m_view->closed()) m_fileBrowser.m_view->mouseMove(coord); else { m_newButt.mouseMove(coord); m_openButt.mouseMove(coord); m_extractButt.mouseMove(coord); } } void SplashScreen::mouseEnter(const boo::SWindowCoord& coord) { if (m_fileBrowser.m_view && !m_fileBrowser.m_view->closed()) m_fileBrowser.m_view->mouseEnter(coord); else { m_newButt.mouseEnter(coord); m_openButt.mouseEnter(coord); m_extractButt.mouseEnter(coord); } } void SplashScreen::mouseLeave(const boo::SWindowCoord& coord) { if (m_fileBrowser.m_view && !m_fileBrowser.m_view->closed()) m_fileBrowser.m_view->mouseLeave(coord); else { m_newButt.mouseLeave(coord); m_openButt.mouseLeave(coord); m_extractButt.mouseLeave(coord); } } void SplashScreen::scroll(const boo::SWindowCoord& coord, const boo::SScrollDelta& scroll) { if (m_fileBrowser.m_view) m_fileBrowser.m_view->scroll(coord, scroll); } void SplashScreen::touchDown(const boo::STouchCoord& coord, uintptr_t tid) { if (m_fileBrowser.m_view) m_fileBrowser.m_view->touchDown(coord, tid); } void SplashScreen::touchUp(const boo::STouchCoord& coord, uintptr_t tid) { if (m_fileBrowser.m_view) m_fileBrowser.m_view->touchUp(coord, tid); } void SplashScreen::touchMove(const boo::STouchCoord& coord, uintptr_t tid) { if (m_fileBrowser.m_view) m_fileBrowser.m_view->touchMove(coord, tid); } void SplashScreen::charKeyDown(unsigned long charCode, boo::EModifierKey mods, bool isRepeat) { if (skipBuildInAnimation()) return; if (m_fileBrowser.m_view) m_fileBrowser.m_view->charKeyDown(charCode, mods, isRepeat); } void SplashScreen::specialKeyDown(boo::ESpecialKey key, boo::EModifierKey mods, bool isRepeat) { if (skipBuildInAnimation()) return; if (m_fileBrowser.m_view) m_fileBrowser.m_view->specialKeyDown(key, mods, isRepeat); } void SplashScreen::resized(const boo::SWindowRect& root, const boo::SWindowRect& sub) { ModalWindow::resized(root, sub); float pf = rootView().viewRes().pixelFactor(); boo::SWindowRect centerRect = subRect(); centerRect.location[0] = root.size[0] / 2 - (SPLASH_WIDTH * pf / 2.0); centerRect.location[1] = root.size[1] / 2 - (SPLASH_HEIGHT * pf / 2.0); boo::SWindowRect badgeRect = centerRect; badgeRect.location[0] += LINE_WIDTH * pf; badgeRect.location[1] += BADGE_MARGIN * pf; badgeRect.size[0] = BADGE_WIDTH * pf; badgeRect.size[1] = BADGE_HEIGHT * pf; boo::SWindowRect textRect = centerRect; textRect.location[0] += TEXT_MARGIN * pf; textRect.location[1] += (SPLASH_HEIGHT - 36) * pf; if (m_title) { m_title->resized(root, textRect); textRect.location[0] = centerRect.location[0] + (SPLASH_WIDTH - TEXT_MARGIN) * pf; textRect.location[1] -= 5 * pf; m_buildInfo->resized(root, textRect); textRect.location[0] = centerRect.location[0] + (SPLASH_WIDTH - TEXT_MARGIN) * pf; textRect.location[1] = centerRect.location[1] + (BADGE_MARGIN + TEXT_MARGIN) * pf; m_badgeIcon->resized(root, badgeRect); m_badgeText->resized(root, textRect); textRect.size[0] = m_newButt.m_view->nominalWidth(); textRect.size[1] = m_newButt.m_view->nominalHeight(); textRect.location[1] = centerRect.location[1] + 20 * pf; textRect.location[0] = centerRect.location[0] + SPLASH_WIDTH / 4 * pf - m_newButt.m_view->nominalWidth() / 2; m_newButt.m_view->resized(root, textRect); textRect.size[0] = m_openButt.m_view->nominalWidth(); textRect.size[1] = m_openButt.m_view->nominalHeight(); textRect.location[1] = centerRect.location[1] + 20 * pf; textRect.location[0] = centerRect.location[0] + SPLASH_WIDTH * 2 / 4 * pf - m_openButt.m_view->nominalWidth() / 2; m_openButt.m_view->resized(root, textRect); textRect.size[0] = m_extractButt.m_view->nominalWidth(); textRect.size[1] = m_extractButt.m_view->nominalHeight(); textRect.location[1] = centerRect.location[1] + 20 * pf; textRect.location[0] = centerRect.location[0] + SPLASH_WIDTH * 3 / 4 * pf - m_extractButt.m_view->nominalWidth() / 2; m_extractButt.m_view->resized(root, textRect); } if (m_fileBrowser.m_view) m_fileBrowser.m_view->resized(root, root); } void SplashScreen::draw(boo::IGraphicsCommandQueue* gfxQ) { if (phase() == Phase::Done) return; ModalWindow::draw(gfxQ); if (m_title) { m_title->draw(gfxQ); m_buildInfo->draw(gfxQ); m_badgeIcon->draw(gfxQ); m_badgeText->draw(gfxQ); m_newButt.m_view->draw(gfxQ); m_openButt.m_view->draw(gfxQ); m_extractButt.m_view->draw(gfxQ); } if (m_fileBrowser.m_view) m_fileBrowser.m_view->draw(gfxQ); } } // namespace metaforce
jct197/PeakInvestigator-Python-SDK
peakinvestigator/peakinvestigator_saas.py
<reponame>jct197/PeakInvestigator-Python-SDK ## -*- coding: utf-8 -*- # # Copyright (c) 2019, Veritomyx, Inc. # # This file is part of the Python SDK for PeakInvestigator # (http://veritomyx.com) and is distributed under the terms # of the BSD 3-Clause license. import os import requests import tarfile import zipfile import glob from paramiko.client import SSHClient, WarningPolicy from peakinvestigator.progress.uploader import Uploader class PeakInvestigatorSaaS(object): """"An object for interacting with the PeakInvestigator API. See http://veritomyx.com for more information about PeakInvestigtor and https://peakinvestigator.veritomyx.com/api for information about the public API. Here's an example:: service = PeakInvestigatorSaaS("https://peakinvestigator.veritomyx.com") action = PiVersionsAction("4.2", "joe", "badpw") response = service.execute(action) action.process_response(response) See other documentation for more details. """ def __init__(self, *args, **kwds): """Constructor. If the 'server' keyword is specified, that is used for the API calls. Otherwise, it will try to use the first argument. Note that only the hostname without any path should be specified. If neither keywords or arguments are specified, it will default to https://peakinvestigator.veritomyx.com. https:// will be pre-pended if it is missing. """ if "server" in kwds: server = kwds["server"] elif len(args) > 0: server = args[0] else: server = "https://peakinvestigator.veritomyx.com" if "http" not in server: server = "https://" + server self._server = server def execute(self, action): """Call the API with the given action. An action should implement a build_query() method that returns a dictionary containing the appropriate parameters for the HTTP POST request. This method returns the response from the server as a string, which is usually processed with the same action. """ response = requests.post(self._server + "/api/", data=action.build_query()) return response.text def upload(self, upload_action, local_file, progress_factory, num_scan=0): """Upload file to a SFTP server""" upload_action.num = num_scan uploader = Uploader(upload_action.host, upload_action.token, progress_factory) if os.path.exists(local_file): if tarfile.is_tarfile(local_file): uploader.upload_tarfile(local_file) elif zipfile.is_zipfile(local_file): uploader.upload_zipfile(local_file) else: uploader.upload_file(local_file, int(upload_action.num)) else: filenames = glob.glob(local_file) uploader.upload_files(filenames) uploader.close() def download(self, sftp_action, remote_file, local_file, callback=None): """Download a file from a SFTP server.""" with SSHClient() as ssh: ssh.set_missing_host_key_policy(WarningPolicy()) ssh.connect(sftp_action.host, port=sftp_action.port, username=sftp_action.sftp_username, password=sftp_action.sftp_password) with ssh.open_sftp() as sftp: sftp.get(remote_file, local_file, callback)