repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
afeng11/tomato-arm
release/src-rt-6.x.4708/router/transmission/gtk/transmission-resources.h
<reponame>afeng11/tomato-arm #ifndef __RESOURCE_transmission_H__ #define __RESOURCE_transmission_H__ #include <gio/gio.h> extern GResource *transmission_get_resource (void); #endif
ts-miller/rails-project
app/controllers/callbacks_controller.rb
<reponame>ts-miller/rails-project class CallbacksController < ApplicationController def google @user = User.from_omniauth(request.env["omniauth.auth"]) session[:user_id] = @user.id set_session(@user) redirect_to user_pledges_path(@user) end end
jMonkeyEngine/jMonkeyEngineSDK
jme3-core/src/com/jme3/gde/core/sceneexplorer/nodes/animation/JmeJointChildren.java
/* * Copyright (c) 2009-2020 jMonkeyEngine * 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 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.gde.core.sceneexplorer.nodes.animation; import com.jme3.anim.Joint; import com.jme3.gde.core.scene.SceneApplication; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutionException; import org.openide.loaders.DataObject; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.util.Exceptions; /** * Representation of multiple Joints in the Scene Explorer * @author MeFisto94 */ public class JmeJointChildren extends Children.Keys<Object> { protected Joint rootJoint; protected JmeSkinningControl jmeSkinningControl; protected boolean readOnly = true; protected HashMap<Object, Node> map = new HashMap<>(); private DataObject dataObject; public JmeJointChildren() { } public JmeJointChildren(JmeSkinningControl jmeSkinningControl, Joint rootJoint) { this.rootJoint = rootJoint; this.jmeSkinningControl = jmeSkinningControl; } public void refreshChildren(boolean immediate) { setKeys(createKeys()); refresh(); } public void setReadOnly(boolean cookie) { this.readOnly = cookie; } @Override protected void addNotify() { super.addNotify(); setKeys(createKeys()); } protected List<Object> createKeys() { try { return SceneApplication.getApplication().enqueue(() -> { List<Object> keys = new LinkedList<>(); if (rootJoint != null) { keys.addAll(rootJoint.getChildren()); } else { keys.addAll(Arrays.asList(jmeSkinningControl.getSkinningControl().getArmature().getRoots())); } return keys; }).get(); } catch (InterruptedException | ExecutionException ex) { Exceptions.printStackTrace(ex); return null; } } @Override protected Node[] createNodes(Object key) { if (key instanceof Joint) { JmeJointChildren children = new JmeJointChildren(jmeSkinningControl, (Joint)key); children.setReadOnly(readOnly); children.setDataObject(dataObject); return new Node[]{new JmeJoint(jmeSkinningControl, (Joint)key, children).setReadOnly(readOnly)}; } else { return new Node[]{Node.EMPTY}; } } public void setSkinningControl(JmeSkinningControl jmeSkinningControl) { this.jmeSkinningControl = jmeSkinningControl; } public DataObject getDataObject() { return dataObject; } public void setDataObject(DataObject dataObject) { this.dataObject = dataObject; } }
UmerSami/SS-OpenSpecimen
WEB-INF/src/com/krishagni/catissueplus/core/administrative/domain/factory/SpecimenRequestErrorCode.java
package com.krishagni.catissueplus.core.administrative.domain.factory; import com.krishagni.catissueplus.core.common.errors.ErrorCode; public enum SpecimenRequestErrorCode implements ErrorCode { NOT_FOUND, NOT_APPROVED, CLOSED, SPECIMEN_DISTRIBUTED, SPECIMEN_SHIPPED, FORM_NOT_CONFIGURED, FORM_NOT_FILLED, INVALID_CAT_ID, INVALID_ITEM_ID, REQUESTOR_EMAIL_REQ, USED_IN_ORDER; @Override public String code() { return "SPMN_REQ_" + this.name(); } }
franneck94/UdemyCExt
12_Advanced/MatrixLib3/Matrix.h
<gh_stars>0 #ifndef MATRIX_H #define MATRIX_H #include <stdbool.h> #include <stdint.h> #include "Vector.h" /**********************/ /* DEFINES AND TYPES */ /**********************/ typedef enum { AXIS_0, AXIS_1, } Axis; typedef struct { float *data; size_t num_rows; size_t num_cols; } Matrix; /**********************/ /* MAIN FUNCTIONS */ /**********************/ Matrix *createMatrix(const size_t num_rows, const size_t num_cols, const float value); Matrix *freeMatrix(Matrix *matrix); /**********************/ /* HELPER FUNCTIONS */ /**********************/ size_t matrixIndex(const size_t num_cols, const size_t i, const size_t j); size_t matrixNumElements(const Matrix *matrix); bool matrixSameSize(const Matrix *matrix1, const Matrix *matrix2); bool matrixMultiplyPossible(const Matrix *matrix1, const Matrix *matrix2); /**********************/ /* I/O FUNCTIONS */ /**********************/ void printMatrix(const Matrix *matrix); /**********************/ /* MATH. FUNCTIONS */ /**********************/ Matrix *addMatrix(const Matrix *matrix1, const Matrix *matrix2); Matrix *subMatrix(const Matrix *matrix1, const Matrix *matrix2); Matrix *multiplyMatrix(const Matrix *matrix1, const Matrix *matrix2); Matrix *multiplyMatrixByScalar(const Matrix *matrix, const float scalar); Matrix *divideMatrixByScalar(const Matrix *matrix, const float scalar); Vector *minMatrix(const Matrix *matrix, const Axis axis); Vector *maxMatrix(const Matrix *matrix, const Axis axis); Vector *meanMatrix(const Matrix *matrix, const Axis axis); #endif // MATRIX_H
Pritam-Biswas/Transaction-Cost-Analytics-Engine
Multi Process Application/analysis/SimpleAnalysisSpread.py
<filename>Multi Process Application/analysis/SimpleAnalysisSpread.py<gh_stars>1-10 from data.DataCash import CDataCash from data.DataFuture import CDataFuture from utils.Spread import CSpread from utils.UtilsSpread import CUtilsSpread from data.FormatData import CFormatData from visualize.plot.CustomPlot import CCustomPlot from AnalysisAbstract import CAnalysisAbstract #Class to perform SimpleAnalysis of Cash Futures Spread class CSimpleAnalysisSpread(CAnalysisAbstract): #Input parameters are taken in the form of a dictionary def __init__(self, input_dict): self.m_DataCash_obj = CDataCash() self.m_DataFuture_obj = CDataFuture() self.m_UtilsSpread_obj = CSpread() self.m_FormatData_obj = CFormatData(input_dict) def GetData(self, cash_data_list, future_data_list): self.m_FormatData_obj.FormatDataCash(self.m_DataCash_obj, cash_data_list) self.m_FormatData_obj.FormatDataFuture(self.m_DataFuture_obj, future_data_list) return True def AnalyseData(self): utils_spread_obj = CUtilsSpread() utils_spread_obj.GetLastPriceTotal(self.m_DataCash_obj) utils_spread_obj.GetLastPriceTotal(self.m_DataFuture_obj) self.m_UtilsSpread_obj.GetMinList(self.m_DataCash_obj, self.m_DataFuture_obj) return True #Method to plot data def PlotData(self): customplot_obj = CCustomPlot() customplot_obj.StartPlot({'Market': '', 'Portfolio': '', 'Predicted': '', 'Cash': self.m_DataCash_obj, 'Future': self.m_DataFuture_obj, 'Spread': self.m_UtilsSpread_obj}) return True #Method to display data in forms of tables def TabulateData(self): return True #Method to choose form of output def VisualizeData(self, choice = 'PLOT'): if choice.upper() == 'PLOT': self.PlotData() if choice.upper() == 'TABULATE': self.TabulateData() return True #Method to trigger analysis of Cash Future Spreads def StartSimpleAnalysisSpread(self, cash_data_list , future_data_list, choice = 'PLOT'): self.GetData(cash_data_list, future_data_list) self.AnalyseData() self.VisualizeData(choice) return True #Class to initiate an object of type CSimpleAnalysisSpread class CTest: if __name__ == "__main__": simple_analysis_cf_obj = CSimpleAnalysisSpread({'date': '14032016', 'symbol': 'DRREDDY-EQ', 'window_size': 15, 'path': 'C:/Users/rashishs/Downloads', 'portfolio_filename': '', 'strategy_logs_filename': '', 'URL': '', 'username': '', 'password': ''}) simple_analysis_cf_obj.StartSimpleAnalysisSpread()
yogeshwargnanasekaran/gophercloud
acceptance/openstack/networking/v2/extensions/fwaas/firewall_test.go
// +build acceptance networking fwaas package fwaas import ( "testing" "github.com/yogeshwargnanasekaran/gophercloud/acceptance/clients" layer3 "github.com/yogeshwargnanasekaran/gophercloud/acceptance/openstack/networking/v2/extensions/layer3" "github.com/yogeshwargnanasekaran/gophercloud/acceptance/tools" "github.com/yogeshwargnanasekaran/gophercloud/openstack/networking/v2/extensions/fwaas/firewalls" "github.com/yogeshwargnanasekaran/gophercloud/openstack/networking/v2/extensions/fwaas/routerinsertion" th "github.com/yogeshwargnanasekaran/gophercloud/testhelper" ) func TestFirewallCRUD(t *testing.T) { client, err := clients.NewNetworkV2Client() th.AssertNoErr(t, err) router, err := layer3.CreateExternalRouter(t, client) th.AssertNoErr(t, err) defer layer3.DeleteRouter(t, client, router.ID) rule, err := CreateRule(t, client) th.AssertNoErr(t, err) defer DeleteRule(t, client, rule.ID) tools.PrintResource(t, rule) policy, err := CreatePolicy(t, client, rule.ID) th.AssertNoErr(t, err) defer DeletePolicy(t, client, policy.ID) tools.PrintResource(t, policy) firewall, err := CreateFirewall(t, client, policy.ID) th.AssertNoErr(t, err) defer DeleteFirewall(t, client, firewall.ID) tools.PrintResource(t, firewall) fwName := "" fwDescription := "" fwUpdateOpts := firewalls.UpdateOpts{ Name: &fwName, Description: &fwDescription, PolicyID: policy.ID, } _, err = firewalls.Update(client, firewall.ID, fwUpdateOpts).Extract() th.AssertNoErr(t, err) newFirewall, err := firewalls.Get(client, firewall.ID).Extract() th.AssertNoErr(t, err) tools.PrintResource(t, newFirewall) th.AssertEquals(t, newFirewall.Name, fwName) th.AssertEquals(t, newFirewall.Description, fwDescription) th.AssertEquals(t, newFirewall.PolicyID, policy.ID) allPages, err := firewalls.List(client, nil).AllPages() th.AssertNoErr(t, err) allFirewalls, err := firewalls.ExtractFirewalls(allPages) th.AssertNoErr(t, err) var found bool for _, firewall := range allFirewalls { if firewall.ID == newFirewall.ID { found = true } } th.AssertEquals(t, found, true) } func TestFirewallCRUDRouter(t *testing.T) { client, err := clients.NewNetworkV2Client() th.AssertNoErr(t, err) router, err := layer3.CreateExternalRouter(t, client) th.AssertNoErr(t, err) defer layer3.DeleteRouter(t, client, router.ID) rule, err := CreateRule(t, client) th.AssertNoErr(t, err) defer DeleteRule(t, client, rule.ID) tools.PrintResource(t, rule) policy, err := CreatePolicy(t, client, rule.ID) th.AssertNoErr(t, err) defer DeletePolicy(t, client, policy.ID) tools.PrintResource(t, policy) firewall, err := CreateFirewallOnRouter(t, client, policy.ID, router.ID) th.AssertNoErr(t, err) defer DeleteFirewall(t, client, firewall.ID) tools.PrintResource(t, firewall) router2, err := layer3.CreateExternalRouter(t, client) th.AssertNoErr(t, err) defer layer3.DeleteRouter(t, client, router2.ID) description := "Some firewall description" firewallUpdateOpts := firewalls.UpdateOpts{ PolicyID: policy.ID, Description: &description, } updateOpts := routerinsertion.UpdateOptsExt{ firewallUpdateOpts, []string{router2.ID}, } _, err = firewalls.Update(client, firewall.ID, updateOpts).Extract() th.AssertNoErr(t, err) newFirewall, err := firewalls.Get(client, firewall.ID).Extract() th.AssertNoErr(t, err) tools.PrintResource(t, newFirewall) } func TestFirewallCRUDRemoveRouter(t *testing.T) { client, err := clients.NewNetworkV2Client() th.AssertNoErr(t, err) router, err := layer3.CreateExternalRouter(t, client) th.AssertNoErr(t, err) defer layer3.DeleteRouter(t, client, router.ID) rule, err := CreateRule(t, client) th.AssertNoErr(t, err) defer DeleteRule(t, client, rule.ID) tools.PrintResource(t, rule) policy, err := CreatePolicy(t, client, rule.ID) th.AssertNoErr(t, err) defer DeletePolicy(t, client, policy.ID) tools.PrintResource(t, policy) firewall, err := CreateFirewallOnRouter(t, client, policy.ID, router.ID) th.AssertNoErr(t, err) defer DeleteFirewall(t, client, firewall.ID) tools.PrintResource(t, firewall) description := "Some firewall description" firewallUpdateOpts := firewalls.UpdateOpts{ PolicyID: policy.ID, Description: &description, } updateOpts := routerinsertion.UpdateOptsExt{ firewallUpdateOpts, []string{}, } _, err = firewalls.Update(client, firewall.ID, updateOpts).Extract() th.AssertNoErr(t, err) newFirewall, err := firewalls.Get(client, firewall.ID).Extract() th.AssertNoErr(t, err) tools.PrintResource(t, newFirewall) }
ETN-Tech/isen_emergence-app
react-ui/src/components/godfather/MeetingRating.js
<filename>react-ui/src/components/godfather/MeetingRating.js /** * MEETINGS RATING COMPONENT <- GODFATHER MEETING CARD COMPONENT <- GODFATHER MEETINGS LIST PAGE * Radio buttons to rate a meeting */ import React, {useState} from "react"; import {Button, Form, FormCheck} from "react-bootstrap"; function MeetingRating ({ meeting, updateRating }) { const[note, setNote] = useState(null); const meetingUid = meeting.fkGodfatherAccountId +"-"+ meeting.fkLaureateAccountId; return ( <> <Form className='py-2'> <FormCheck custom inline type='radio' id={`${meetingUid}-R1`} name={meetingUid} label='1' onChange={(e) => setNote(1)} /> <FormCheck custom inline type='radio' id={`${meetingUid}-R2`} name={meetingUid} label='2' onChange={(e) => setNote(2)} /> <FormCheck custom inline type='radio' id={`${meetingUid}-R3`} name={meetingUid} label='3' onChange={(e) => setNote(3)} /> <FormCheck custom inline type='radio' id={`${meetingUid}-R4`} name={meetingUid} label='4' onChange={(e) => setNote(4)} /> </Form> <div className='text-center'> {meeting.godfatherRating == null ? ( <Button className=" align-self-center col" variant="btn btn-success" onClick={() => updateRating(meeting.fkLaureateAccountId, note)}>Envoyer</Button> ) : ( <> <Button className=" align-self-center col" variant="btn btn-danger cursor-not-allowed" disabled>Envoyer</Button> <p className='text-muted'>Réponse envoyée</p> </> )} </div> </> ) } export default MeetingRating;
hendrik-skubch/alica
alica_tests/autogenerated/src/Plans/Defend1402488893641.cpp
<filename>alica_tests/autogenerated/src/Plans/Defend1402488893641.cpp #include "Plans/Defend1402488893641.h" using namespace alica; /*PROTECTED REGION ID(eph1402488893641) ENABLED START*/ // Add additional using directives here /*PROTECTED REGION END*/ namespace alicaAutogenerated { // Plan:Defend /* generated comment Task: DefaultTask -> EntryPoint-ID: 1402488903550 */ shared_ptr<UtilityFunction> UtilityFunction1402488893641::getUtilityFunction(Plan* plan) { /*PROTECTED REGION ID(1402488893641) ENABLED START*/ shared_ptr<UtilityFunction> defaultFunction = make_shared<DefaultUtilityFunction>(plan); return defaultFunction; /*PROTECTED REGION END*/ } // State: Tackle in Plan: Defend /* * * Transition: * - Name: MISSING_NAME, ConditionString: , Comment : TackleToGetBall * * Plans in State: * - Plan - (Name): TackleDefault, (PlanID): 1402488956661 * - Plan - (Name): Tackle, (PlanID): 1402489318663 * * Tasks: * - DefaultTask (1225112227903) (Entrypoint: 1402488903550) * * States: * - Tackle (1402488903549) * - GetGoal (1402488910751) * - GetBall (1402488959965) * - TryToDefendGoal (1402489037735) * * Vars: */ bool TransitionCondition1402488993122::evaluate(shared_ptr<RunningPlan> rp) { /*PROTECTED REGION ID(1402488991762) ENABLED START*/ return false; /*PROTECTED REGION END*/ } // State: GetGoal in Plan: Defend // State: GetBall in Plan: Defend /* * * Transition: * - Name: MISSING_NAME, ConditionString: , Comment : GetBallToTackle * * Plans in State: * * Tasks: * - DefaultTask (1225112227903) (Entrypoint: 1402488903550) * * States: * - Tackle (1402488903549) * - GetGoal (1402488910751) * - GetBall (1402488959965) * - TryToDefendGoal (1402489037735) * * Vars: */ bool TransitionCondition1402488991641::evaluate(shared_ptr<RunningPlan> rp) { /*PROTECTED REGION ID(1402488990761) ENABLED START*/ return false; /*PROTECTED REGION END*/ } /* * * Transition: * - Name: MISSING_NAME, ConditionString: , Comment : TESTESTETS * * Plans in State: * * Tasks: * - DefaultTask (1225112227903) (Entrypoint: 1402488903550) * * States: * - Tackle (1402488903549) * - GetGoal (1402488910751) * - GetBall (1402488959965) * - TryToDefendGoal (1402489037735) * * Vars: */ bool TransitionCondition1402489065962::evaluate(shared_ptr<RunningPlan> rp) { /*PROTECTED REGION ID(1402489064693) ENABLED START*/ return false; /*PROTECTED REGION END*/ } // State: TryToDefendGoal in Plan: Defend /* * * Transition: * - Name: MISSING_NAME, ConditionString: , Comment : TryToDefendGoalToGetGoal * * Plans in State: * - Plan - (Name): PlanType, (PlanID): 1402489564599 * * Tasks: * - DefaultTask (1225112227903) (Entrypoint: 1402488903550) * * States: * - Tackle (1402488903549) * - GetGoal (1402488910751) * - GetBall (1402488959965) * - TryToDefendGoal (1402489037735) * * Vars: */ bool TransitionCondition1402489073613::evaluate(shared_ptr<RunningPlan> rp) { /*PROTECTED REGION ID(1402489071510) ENABLED START*/ return false; /*PROTECTED REGION END*/ } } // namespace alicaAutogenerated
rajat-saxena14/All-Integrated-Apps
app/src/main/java/com/example/allandroidprojects/SplashAnimation1.java
package com.example.allandroidprojects; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.view.MenuItem; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; public class SplashAnimation1 extends AppCompatActivity { private static int SPLASH_SCREEN=6500; MediaPlayer startups; Animation topAnim, rotate, slideR; ImageView iv1,iv2; TextView t1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); getSupportActionBar().hide(); setContentView(R.layout.activity_splash_animation1); startups= MediaPlayer.create(SplashAnimation1.this,R.raw.startup); startups.start(); topAnim= AnimationUtils.loadAnimation(this, R.anim.top_animation); rotate= AnimationUtils.loadAnimation(this, R.anim.rotate); slideR = AnimationUtils.loadAnimation(this, R.anim.slider); iv2=findViewById(R.id.iv1); t1=findViewById(R.id.t1); iv2.startAnimation(rotate); t1.setAnimation(topAnim); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent i=new Intent(SplashAnimation1.this, MainActivity.class); startActivity(i); finish(); } },SPLASH_SCREEN); } @Override protected void onPause(){ super.onPause(); finish(); } }
stephenjmaher/ipet
ipet/validation/__init__.py
<reponame>stephenjmaher/ipet<filename>ipet/validation/__init__.py<gh_stars>10-100 # -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2018 Zuse Institute Berlin, www.zib.de Permissions are granted as stated in the license file you have obtained with this software. If you find the library useful for your purpose, please refer to README.md for how to cite IPET. @author: <NAME> """ from .Validation import Validation __all__ = ["TestSets"]
frasermacquarrie/thenoiseontoys
modules/core/client/config/core-admin.client.menus.js
'use strict'; angular.module('core.admin').run(['Menus', function (Menus) { //Adding the topbar menu Menus.addMenu('admin.sidebar', { roles: ['admin'] }); Menus.addMenuItem('admin.sidebar', { title: 'Dashboard', state: 'admin.home', //type: 'dropdown', icon: { 'simpleline': 'home' }, roles: ['admin'] }); } ]);
giantcroc/envoy
source/common/tracing/http_tracer_impl.cc
#include "source/common/tracing/http_tracer_impl.h" #include <string> #include "envoy/config/core/v3/base.pb.h" #include "envoy/network/address.h" #include "envoy/tracing/http_tracer.h" #include "envoy/type/metadata/v3/metadata.pb.h" #include "envoy/type/tracing/v3/custom_tag.pb.h" #include "source/common/common/assert.h" #include "source/common/common/fmt.h" #include "source/common/common/macros.h" #include "source/common/common/utility.h" #include "source/common/formatter/substitution_formatter.h" #include "source/common/grpc/common.h" #include "source/common/http/codes.h" #include "source/common/http/header_map_impl.h" #include "source/common/http/header_utility.h" #include "source/common/http/headers.h" #include "source/common/http/utility.h" #include "source/common/protobuf/utility.h" #include "source/common/stream_info/utility.h" #include "absl/strings/str_cat.h" namespace Envoy { namespace Tracing { // TODO(perf): Avoid string creations/copies in this entire file. static std::string buildResponseCode(const StreamInfo::StreamInfo& info) { return info.responseCode() ? std::to_string(info.responseCode().value()) : "0"; } static absl::string_view valueOrDefault(const Http::HeaderEntry* header, const char* default_value) { return header ? header->value().getStringView() : default_value; } const std::string HttpTracerUtility::IngressOperation = "ingress"; const std::string HttpTracerUtility::EgressOperation = "egress"; const std::string& HttpTracerUtility::toString(OperationName operation_name) { switch (operation_name) { case OperationName::Ingress: return IngressOperation; case OperationName::Egress: return EgressOperation; } return EMPTY_STRING; // Make the compiler happy. } Decision HttpTracerUtility::shouldTraceRequest(const StreamInfo::StreamInfo& stream_info) { // Exclude health check requests immediately. if (stream_info.healthCheck()) { return {Reason::HealthCheck, false}; } const Tracing::Reason trace_reason = stream_info.traceReason(); switch (trace_reason) { case Reason::ClientForced: case Reason::ServiceForced: case Reason::Sampling: return {trace_reason, true}; default: return {trace_reason, false}; } } static void addTagIfNotNull(Span& span, const std::string& tag, const Http::HeaderEntry* entry) { if (entry != nullptr) { span.setTag(tag, entry->value().getStringView()); } } static void addGrpcRequestTags(Span& span, const Http::RequestHeaderMap& headers) { addTagIfNotNull(span, Tracing::Tags::get().GrpcPath, headers.Path()); addTagIfNotNull(span, Tracing::Tags::get().GrpcAuthority, headers.Host()); addTagIfNotNull(span, Tracing::Tags::get().GrpcContentType, headers.ContentType()); addTagIfNotNull(span, Tracing::Tags::get().GrpcTimeout, headers.GrpcTimeout()); } template <class T> static void addGrpcResponseTags(Span& span, const T& headers) { addTagIfNotNull(span, Tracing::Tags::get().GrpcStatusCode, headers.GrpcStatus()); addTagIfNotNull(span, Tracing::Tags::get().GrpcMessage, headers.GrpcMessage()); // Set error tag when status is not OK. absl::optional<Grpc::Status::GrpcStatus> grpc_status_code = Grpc::Common::getGrpcStatus(headers); if (grpc_status_code && grpc_status_code.value() != Grpc::Status::WellKnownGrpcStatus::Ok) { span.setTag(Tracing::Tags::get().Error, Tracing::Tags::get().True); } } static void annotateVerbose(Span& span, const StreamInfo::StreamInfo& stream_info) { const auto start_time = stream_info.startTime(); StreamInfo::TimingUtility timing(stream_info); if (timing.lastDownstreamRxByteReceived()) { span.log(start_time + std::chrono::duration_cast<SystemTime::duration>( *timing.lastDownstreamRxByteReceived()), Tracing::Logs::get().LastDownstreamRxByteReceived); } if (timing.firstUpstreamTxByteSent()) { span.log(start_time + std::chrono::duration_cast<SystemTime::duration>( *timing.firstUpstreamTxByteSent()), Tracing::Logs::get().FirstUpstreamTxByteSent); } if (timing.lastUpstreamTxByteSent()) { span.log(start_time + std::chrono::duration_cast<SystemTime::duration>(*timing.lastUpstreamTxByteSent()), Tracing::Logs::get().LastUpstreamTxByteSent); } if (timing.firstUpstreamRxByteReceived()) { span.log(start_time + std::chrono::duration_cast<SystemTime::duration>( *timing.firstUpstreamRxByteReceived()), Tracing::Logs::get().FirstUpstreamRxByteReceived); } if (timing.lastUpstreamRxByteReceived()) { span.log(start_time + std::chrono::duration_cast<SystemTime::duration>( *timing.lastUpstreamRxByteReceived()), Tracing::Logs::get().LastUpstreamRxByteReceived); } if (timing.firstDownstreamTxByteSent()) { span.log(start_time + std::chrono::duration_cast<SystemTime::duration>( *timing.firstDownstreamTxByteSent()), Tracing::Logs::get().FirstDownstreamTxByteSent); } if (timing.lastDownstreamTxByteSent()) { span.log(start_time + std::chrono::duration_cast<SystemTime::duration>( *timing.lastDownstreamTxByteSent()), Tracing::Logs::get().LastDownstreamTxByteSent); } } void HttpTracerUtility::finalizeDownstreamSpan(Span& span, const Http::RequestHeaderMap* request_headers, const Http::ResponseHeaderMap* response_headers, const Http::ResponseTrailerMap* response_trailers, const StreamInfo::StreamInfo& stream_info, const Config& tracing_config) { // Pre response data. if (request_headers) { if (request_headers->RequestId()) { span.setTag(Tracing::Tags::get().GuidXRequestId, request_headers->getRequestIdValue()); } span.setTag( Tracing::Tags::get().HttpUrl, Http::Utility::buildOriginalUri(*request_headers, tracing_config.maxPathTagLength())); span.setTag(Tracing::Tags::get().HttpMethod, request_headers->getMethodValue()); span.setTag(Tracing::Tags::get().DownstreamCluster, valueOrDefault(request_headers->EnvoyDownstreamServiceCluster(), "-")); span.setTag(Tracing::Tags::get().UserAgent, valueOrDefault(request_headers->UserAgent(), "-")); span.setTag( Tracing::Tags::get().HttpProtocol, Formatter::SubstitutionFormatUtils::protocolToStringOrDefault(stream_info.protocol())); const auto& remote_address = stream_info.downstreamAddressProvider().directRemoteAddress(); if (remote_address->type() == Network::Address::Type::Ip) { const auto remote_ip = remote_address->ip(); span.setTag(Tracing::Tags::get().PeerAddress, remote_ip->addressAsString()); } else { span.setTag(Tracing::Tags::get().PeerAddress, remote_address->logicalName()); } if (request_headers->ClientTraceId()) { span.setTag(Tracing::Tags::get().GuidXClientTraceId, request_headers->getClientTraceIdValue()); } if (Grpc::Common::isGrpcRequestHeaders(*request_headers)) { addGrpcRequestTags(span, *request_headers); } } CustomTagContext ctx{request_headers, stream_info}; const CustomTagMap* custom_tag_map = tracing_config.customTags(); if (custom_tag_map) { for (const auto& it : *custom_tag_map) { it.second->applySpan(span, ctx); } } span.setTag(Tracing::Tags::get().RequestSize, std::to_string(stream_info.bytesReceived())); span.setTag(Tracing::Tags::get().ResponseSize, std::to_string(stream_info.bytesSent())); setCommonTags(span, response_headers, response_trailers, stream_info, tracing_config); span.finishSpan(); } void HttpTracerUtility::finalizeUpstreamSpan(Span& span, const Http::ResponseHeaderMap* response_headers, const Http::ResponseTrailerMap* response_trailers, const StreamInfo::StreamInfo& stream_info, const Config& tracing_config) { span.setTag( Tracing::Tags::get().HttpProtocol, Formatter::SubstitutionFormatUtils::protocolToStringOrDefault(stream_info.protocol())); if (stream_info.upstreamInfo() && stream_info.upstreamInfo()->upstreamHost()) { span.setTag(Tracing::Tags::get().UpstreamAddress, stream_info.upstreamInfo()->upstreamHost()->address()->asStringView()); } setCommonTags(span, response_headers, response_trailers, stream_info, tracing_config); span.finishSpan(); } void HttpTracerUtility::setCommonTags(Span& span, const Http::ResponseHeaderMap* response_headers, const Http::ResponseTrailerMap* response_trailers, const StreamInfo::StreamInfo& stream_info, const Config& tracing_config) { span.setTag(Tracing::Tags::get().Component, Tracing::Tags::get().Proxy); if (stream_info.upstreamInfo() && stream_info.upstreamInfo()->upstreamHost()) { span.setTag(Tracing::Tags::get().UpstreamCluster, stream_info.upstreamInfo()->upstreamHost()->cluster().name()); span.setTag(Tracing::Tags::get().UpstreamClusterName, stream_info.upstreamInfo()->upstreamHost()->cluster().observabilityName()); } // Post response data. span.setTag(Tracing::Tags::get().HttpStatusCode, buildResponseCode(stream_info)); span.setTag(Tracing::Tags::get().ResponseFlags, StreamInfo::ResponseFlagUtils::toShortString(stream_info)); // GRPC data. if (response_trailers && response_trailers->GrpcStatus() != nullptr) { addGrpcResponseTags(span, *response_trailers); } else if (response_headers && response_headers->GrpcStatus() != nullptr) { addGrpcResponseTags(span, *response_headers); } if (tracing_config.verbose()) { annotateVerbose(span, stream_info); } if (!stream_info.responseCode() || Http::CodeUtility::is5xx(stream_info.responseCode().value())) { span.setTag(Tracing::Tags::get().Error, Tracing::Tags::get().True); } } HttpTracerImpl::HttpTracerImpl(DriverSharedPtr driver, const LocalInfo::LocalInfo& local_info) : driver_(std::move(driver)), local_info_(local_info) {} SpanPtr HttpTracerImpl::startSpan(const Config& config, Http::RequestHeaderMap& request_headers, const StreamInfo::StreamInfo& stream_info, const Tracing::Decision tracing_decision) { std::string span_name = HttpTracerUtility::toString(config.operationName()); if (config.operationName() == OperationName::Egress) { span_name.append(" "); span_name.append(std::string(request_headers.getHostValue())); } SpanPtr active_span = driver_->startSpan(config, request_headers, span_name, stream_info.startTime(), tracing_decision); // Set tags related to the local environment if (active_span) { active_span->setTag(Tracing::Tags::get().NodeId, local_info_.nodeName()); active_span->setTag(Tracing::Tags::get().Zone, local_info_.zoneName()); } return active_span; } } // namespace Tracing } // namespace Envoy
Cherobin/GameJamUnivali2020
ApocalipseCHI/src/engine/base/entities/GameObject.java
package engine.base.entities; import java.awt.Graphics2D; import java.util.Map; import engine.utils.BoundingBox; public interface GameObject extends Comparable<GameObject> { String getName(); void update(float diffTime); void render(Graphics2D dbg); Map<String, Component> getComponents(); int compareTo(GameObject o); BoundingBox getBoundingBox(); Map<String, Object> getProperties(); boolean isAlive(); }
apache/incubator-taverna-server
taverna-server-webapp/src/main/java/org/apache/taverna/server/master/exceptions/FilesystemAccessException.java
<filename>taverna-server-webapp/src/main/java/org/apache/taverna/server/master/exceptions/FilesystemAccessException.java /* */ package org.apache.taverna.server.master.exceptions; /* * 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. */ import java.rmi.RemoteException; import javax.xml.ws.WebFault; /** * An exception that happened when the underlying filesystem was accessed. * @author <NAME> */ @WebFault(name = "FilesystemAccessFault") public class FilesystemAccessException extends Exception { private static final long serialVersionUID = 8715937300989820318L; public FilesystemAccessException(String msg) { super(msg); } public FilesystemAccessException(String string, Throwable cause) { super(string, getRealCause(cause)); } private static Throwable getRealCause(Throwable t) { if (t instanceof RemoteException) { RemoteException remote = (RemoteException) t; if (remote.detail != null) return remote.detail; } if (t.getCause() != null) return t.getCause(); return t; } }
FEPD/Kira
kira-manager/src/main/webapp/app/view/task/TaskList.js
Ext.define('Kira.view.task.TaskList', { extend : 'Ext.container.Container', //extend : 'Ext.form.Panel', alias : 'widget.tasklist', title : '任务配置管理', layout: 'fit', closable : true, initComponent : function() { var me = this; Ext.applyIf(me, { //margin : '0 10 10 10' }); me.callParent(arguments); }, flushView : function() { this.doComponentLayout(); }, loadView : function() { var grid = Ext.create('Ext.grid.Panel', { store : Ext.getStore('taskStore'), autoShow : true, scroll : true, viewConfig : { enableTextSelection : true }, columns :[{ text : '操作', xtype : 'actioncolumn', width : 50, align : 'center', id : 'taskListIcon', icon : 'extjs/resources/images/action.gif' },{ text : 'AppId', dataIndex : 'appId', width : 200 },{ text : '定时任务Id', dataIndex : 'triggerId', width : 200 },{ text : '版本号', dataIndex : 'version', width : 50 },{ text : '描述', dataIndex : 'description', width : 600 },{ text : '被调用的appId', dataIndex : 'targetAppId', width : 200 },{ text : '被调用的定时任务Id', dataIndex : 'targetTriggerId', width : 200 },{ text : '定时任务类型', dataIndex : 'triggerType', width : 100 },{ text : '创建时间', dataIndex : 'createTimeAsString', width : 150/*, renderer : function(value){ if(value instanceof Date){ return new Date(value).format('Y-m-d H:i:s'); }else{ return Ext.util.Format.date(new Date(value),'Y-m-d H:i:s'); } }*/ },{ text : '是否手动创建', dataIndex : 'manuallyCreated', width : 80 },{ text : '手动创建人', dataIndex : 'manuallyCreatedBy', width : 100 },{ text : 'cron表达式', dataIndex : 'cronExpression', width : 100 },{ text : '开始时间', dataIndex : 'startTimeAsString', width : 150 }, { text : '结束时间', dataIndex : 'endTimeAsString', width : 150 },{ text : '启动延迟(ms)', dataIndex : 'startDelay', width : 120 },{ text : '执行间隔(ms)', dataIndex : 'repeatInterval', width : 120 },{ text : '运行时间阀值(ms)', dataIndex : 'runTimeThreshold', width : 120 },{ text : '执行次数', dataIndex : 'repeatCount', width : 60, renderer : function(value){ if(value == '-1'){ return '无限次'; } return value; } },{ text : '最后一次执行结束时间', dataIndex : 'finalizedTimeAsString', width : 150 },{ text : '是否异步执行', dataIndex : 'asynchronous', width : 80 },{ text : '触发时是否只派送到一个执行地点执行', dataIndex : 'onlyRunOnSingleProcess', width : 220 },{ text : '任务执行地点', dataIndex : 'locationsToRunJob', width : 350 },{ text : '是否只在指定的执行地点执行任务', dataIndex : 'limitToSpecifiedLocations', width : 200 },{ text : '允许业务方法被并发执行', dataIndex : 'concurrent', width : 130 },{ text : 'Pool本地调度', dataIndex : 'scheduledLocally', width : 80 },{ text : 'Disabled', dataIndex : 'disabled', width : 50 },{ text : '执行方法', dataIndex : 'targetMethod', width : 120 },{ text : '方法参数类型', dataIndex : 'targetMethodArgTypes', width : 200 },{ text : '方法参数值', dataIndex : 'argumentsAsJsonArrayString', width : 200 },{ text : '漏执行策略', dataIndex : 'misfireInstruction', width : 80 },{ text : '优先级', dataIndex : 'priority', width : 80 },{ text : '需要宕机恢复', dataIndex : 'requestsRecovery', width : 80 },{ text : '配置从MasterZone复制到SlaveZone', dataIndex : 'copyFromMasterToSlaveZone', width : 200 },{ text : '只在MasterZone中被调度执行', dataIndex : 'onlyScheduledInMasterZone', width : 180 },{ text : '任务派送超时Enabled', dataIndex : 'jobDispatchTimeoutEnabled', width : 130 },{ text : '任务派送超时时间(毫秒)', dataIndex : 'jobDispatchTimeout', width : 130 },{ text : '备注', dataIndex : 'comments', width : 200 }], tbar : ['AppId:',{ xtype : 'combo', //id : 'taskList_poolId', name : 'app', editable : true, value : '', store : Ext.getStore('poolStore').load(), displayField : 'poolName', valueField : 'poolValue', matchFieldWidth: false, //queryMode: 'remote', triggerAction:'all', listConfig : { loadingText: 'Loading...', emptyText:'未找到匹配值', width: 200, autoHeight:true }, listeners : { 'beforequery':function(e){ var combo = e.combo; if(!e.forceAll){ var input = e.query; // 检索的正则 var regExp = new RegExp(".*" + input + ".*"); // 执行检索 combo.store.filterBy(function(record,id){ // 得到每个record的项目名称值 var text = record.get(combo.displayField); return regExp.test(text); }); combo.expand(); return false; } } } },'-','定时任务Id:',{ xtype : 'combo', //id : 'taskList_triggerId', name : 'trigger', editable : true, value : '', store : Ext.getStore('targetTriggerStore'), displayField : 'triggerName', valueField : 'triggerValue', matchFieldWidth: false, queryMode: 'local', triggerAction:'all', listConfig : { loadingText: 'Loading...', width: 200, autoHeight:true } },'-','是否手动创建:',{ xtype : 'combo', name : 'manuallyCreated', editable : true, value : '', store : Ext.getStore('manuallyCreatedStore'), displayField : 'manuallyCreatedName', valueField : 'manuallyCreatedValue', matchFieldWidth: true, queryMode: 'local', triggerAction:'all' },'-',{ text : '查询', iconCls : 'icon-search', action : 'select' }], dockedItems :[{ xtype: 'pagingtoolbar', store: Ext.getStore('taskStore'),// same store GridPanel is using dock: 'bottom', //分页 位置 emptyMsg: '没有数据', displayInfo: true, displayMsg: '当前显示{0}-{1}条记录 / 共{2}条记录 ', beforePageText: '第', afterPageText: '页/共{0}页' }] }); this.add(grid); this.flushView(); } });
yangfancoming/spring-5.1.x
spring-tx/src/main/java/org/springframework/dao/DataIntegrityViolationException.java
package org.springframework.dao; /** * Exception thrown when an attempt to insert or update data * results in violation of an integrity constraint. Note that this * is not purely a relational concept; unique primary keys are * required by most database types. * * @author <NAME> */ @SuppressWarnings("serial") public class DataIntegrityViolationException extends NonTransientDataAccessException { /** * Constructor for DataIntegrityViolationException. * @param msg the detail message */ public DataIntegrityViolationException(String msg) { super(msg); } /** * Constructor for DataIntegrityViolationException. * @param msg the detail message * @param cause the root cause from the data access API in use */ public DataIntegrityViolationException(String msg, Throwable cause) { super(msg, cause); } }
mtezych/cpp
vulkan/include/vulkan/PipelineCache.h
#ifndef VULKAN_PIPELINE_CACHE #define VULKAN_PIPELINE_CACHE #include <vulkan/vulkan.h> #include <vector> namespace vk { struct Device; struct PipelineCache { const Device* device; VkPipelineCache vkPipelineCache; PipelineCache ( const Device& device, const std::vector<const void*>& initialData ); ~PipelineCache (); PipelineCache (PipelineCache&& pipelineCache); PipelineCache (const PipelineCache& pipelineCache) = delete; PipelineCache& operator = (PipelineCache&& pipelineCache); PipelineCache& operator = (const PipelineCache& pipelineCache) = delete; }; } #endif
raeleus/gdx-vfx
gdx-vfx/core/src/com/crashinvaders/vfx/utils/ScreenQuadMesh.java
/******************************************************************************* * Copyright 2012 bmanuel * Copyright 2019 metaphore * * 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.crashinvaders.vfx.utils; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Mesh.VertexDataType; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.glutils.ShaderProgram; /** * Encapsulates a fullscreen quad mesh. Geometry is aligned to the screen corners. * * @author bmanuel * @author metaphore */ public class ScreenQuadMesh { private final Mesh mesh; public ScreenQuadMesh() { this(new VertexAttribute(Usage.Position, 2, "a_position"), new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoord0")); } public ScreenQuadMesh(VertexAttribute... vertexAttributes) { mesh = new Mesh(VertexDataType.VertexArray, true, 4, 0, vertexAttributes); mesh.setVertices(verts); } public void dispose () { mesh.dispose(); } /** * Renders the quad with the specified shader program. */ public void render (ShaderProgram program) { mesh.render(program, GL20.GL_TRIANGLE_FAN, 0, 4); } public Mesh getMesh() { return mesh; } private static final int VERT_SIZE = 16; private static final int X1 = 0; private static final int Y1 = 1; private static final int U1 = 2; private static final int V1 = 3; private static final int X2 = 4; private static final int Y2 = 5; private static final int U2 = 6; private static final int V2 = 7; private static final int X3 = 8; private static final int Y3 = 9; private static final int U3 = 10; private static final int V3 = 11; private static final int X4 = 12; private static final int Y4 = 13; private static final int U4 = 14; private static final int V4 = 15; private static final float[] verts; static { verts = new float[VERT_SIZE]; // Vertex coords verts[X1] = -1; verts[Y1] = -1; verts[X2] = 1; verts[Y2] = -1; verts[X3] = 1; verts[Y3] = 1; verts[X4] = -1; verts[Y4] = 1; // Tex coords verts[U1] = 0f; verts[V1] = 0f; verts[U2] = 1f; verts[V2] = 0f; verts[U3] = 1f; verts[V3] = 1f; verts[U4] = 0f; verts[V4] = 1f; } }
ldy121/algorithm
google_interview_practice/The_k_Strongest_Values_in_an_Array/solve.cc
class Solution { public: vector<int> getStrongest(vector<int>& arr, int k) { vector<int> ret; int m; sort(arr.begin(), arr.end()); m = arr[(arr.size() - 1) / 2]; for (int left = 0, right = arr.size() - 1; (left <= right) && ret.size() < k;) { int l = m - arr[left]; int r = arr[right] - m; if (r < 0) r *= -1; if (l < 0) l *= -1; if (l > r) ret.push_back(arr[left++]); else ret.push_back(arr[right--]); } return ret; } };
openforis/calc
calc-webapp/src/main/webapp/js/calc/manager/data/strata-data-provider.js
/** * data provider for strata. * * @author <NAME> */ StrataDataProvider = function (){ this.exportEnabled = false; this.schema = ''; this.table = ''; this.variables = []; this.count( $.proxy(function(cnt){ if( cnt > 0 ){ var tableInfo = new StratumManager.prototype.tableInfo(); this.schema = tableInfo.fields.schema; this.table = tableInfo.fields.table; for(var i in tableInfo.fields.columns ){ var col = tableInfo.fields.columns[ i ]; this.variables.push( col.column_name ); } } },this)); }; /** * Returns info on the current table */ StrataDataProvider.prototype.tableInfo = function(success) { Utils.applyFunction(success , new StratumManager.prototype.tableInfo() ); }; StrataDataProvider.prototype.count = function(success) { var cnt = 0; WorkspaceManager.getInstance().activeWorkspace( $.proxy(function(ws){ if( ws.strata && ws.strata.length > 0 ){ cnt = ws.strata.length; } Utils.applyFunction( success , cnt ); } , this)); }; StrataDataProvider.prototype.data = function(offset , numberOfItems , excludeNulls, variables, success) { WorkspaceManager.getInstance().activeWorkspace( $.proxy(function(ws){ var records = []; if( ws.strata && ws.strata.length > 0 ){ var end = offset + numberOfItems; var max = ( ws.strata.length <= end ) ? ws.strata.length : end; var strata = ws.strata.slice( offset , max ); for( var i in strata ){ var stratum = strata[ i ]; var record = {}; record.id = i; record.fields = {}; record.fields.stratum_no = stratum.stratumNo; record.fields.stratum_label = stratum.caption; records.push( record ); } } Utils.applyFunction( success , records ); } , this)); };
Cadcorp/GeometricTools
GTE/Graphics/DX11/DX11SamplerState.cpp
// <NAME>, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2020 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 4.0.2019.08.13 #include <Graphics/DX11/GTGraphicsDX11PCH.h> #include <Graphics/DX11/DX11SamplerState.h> using namespace gte; DX11SamplerState::DX11SamplerState(ID3D11Device* device, SamplerState const* samplerState) : DX11DrawingState(samplerState) { // Specify the sampler state description. D3D11_SAMPLER_DESC desc; desc.Filter = msFilter[samplerState->filter]; desc.AddressU = msMode[samplerState->mode[0]]; desc.AddressV = msMode[samplerState->mode[1]]; desc.AddressW = msMode[samplerState->mode[2]]; desc.MipLODBias = samplerState->mipLODBias; desc.MaxAnisotropy = samplerState->maxAnisotropy; desc.ComparisonFunc = msComparison[samplerState->comparison]; desc.BorderColor[0] = samplerState->borderColor[0]; desc.BorderColor[1] = samplerState->borderColor[1]; desc.BorderColor[2] = samplerState->borderColor[2]; desc.BorderColor[3] = samplerState->borderColor[3]; desc.MinLOD = samplerState->minLOD; desc.MaxLOD = samplerState->maxLOD; // Create the sampler state. ID3D11SamplerState* state = nullptr; DX11Log(device->CreateSamplerState(&desc, &state)); mDXObject = state; } std::shared_ptr<GEObject> DX11SamplerState::Create(void* device, GraphicsObject const* object) { if (object->GetType() == GT_SAMPLER_STATE) { return std::make_shared<DX11SamplerState>( reinterpret_cast<ID3D11Device*>(device), static_cast<SamplerState const*>(object)); } LogError("Invalid object type."); } D3D11_FILTER const DX11SamplerState::msFilter[] = { D3D11_FILTER_MIN_MAG_MIP_POINT, D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR, D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR, D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT, D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT, D3D11_FILTER_MIN_MAG_MIP_LINEAR, D3D11_FILTER_ANISOTROPIC, D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT, D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR, D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT, D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR, D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT, D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR, D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, D3D11_FILTER_COMPARISON_ANISOTROPIC }; D3D11_TEXTURE_ADDRESS_MODE const DX11SamplerState::msMode[] = { D3D11_TEXTURE_ADDRESS_WRAP, D3D11_TEXTURE_ADDRESS_MIRROR, D3D11_TEXTURE_ADDRESS_CLAMP, D3D11_TEXTURE_ADDRESS_BORDER, D3D11_TEXTURE_ADDRESS_MIRROR_ONCE }; D3D11_COMPARISON_FUNC const DX11SamplerState::msComparison[] = { D3D11_COMPARISON_NEVER, D3D11_COMPARISON_LESS, D3D11_COMPARISON_EQUAL, D3D11_COMPARISON_LESS_EQUAL, D3D11_COMPARISON_GREATER, D3D11_COMPARISON_NOT_EQUAL, D3D11_COMPARISON_GREATER_EQUAL, D3D11_COMPARISON_ALWAYS };
privet56/qDesktopSearch
clucene/CLucene/search/FilterResultCache.h
<reponame>privet56/qDesktopSearch /*------------------------------------------------------------------------------ * Copyright (C) 2003-2006 <NAME> and the CLucene Team * * Distributable under the terms of either the Apache License (Version 2.0) or * the GNU Lesser General Public License, as specified in the COPYING file. ------------------------------------------------------------------------------*/ #ifndef _lucene_search_FilterResultCache_ #define _lucene_search_FilterResultCache_ CL_CLASS_DEF(index,IndexReader) CL_NS_DEF(search) /** * Holds one cached result */ template<class T> class ResultHolder : LUCENE_BASE { bool deleteRes; public: T* result; ResultHolder( T * result, bool deleteRes ) { this->result = result; this->deleteRes = deleteRes; } ~ResultHolder(){ if ( deleteRes ) _CLDELETE( result ); } }; /** * Wraps another filter's result and caches it. The purpose is to allow * filters to implement this and allow itself to be cached. Alternatively, * use the CachingWrapperFilter to cache the filter. */ template<class T> class FilterResultCache { typedef CL_NS(util)::CLHashMap< CL_NS(index)::IndexReader*, BitSetHolder*, CL_NS(util)::Compare::Void<CL_NS(index)::IndexReader>, CL_NS(util)::Equals::Void<CL_NS(index)::IndexReader>, CL_NS(util)::Deletor::Object<CL_NS(index)::IndexReader>, CL_NS(util)::Deletor::Object<ResultHolder<T> > > CacheType; CacheType cache; bool bDeleteResults; DEFINE_MUTEX( cache_LOCK ) public: FilterResultCache( bool bDeleteResults ); virtual ~FilterResultCache(); T* getResult( CL_NS(index)::IndexReader* reader ); protected: void closeCallback( CL_NS(index)::IndexReader* reader, void* param ); }; CL_NS_END #endif
ScalablyTyped/SlinkyTyped
s/std/src/main/scala/typingsSlinky/std/MSAssertion.scala
package typingsSlinky.std import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait MSAssertion extends StObject { val id: java.lang.String = js.native val `type`: MSCredentialType = js.native } object MSAssertion { @scala.inline def apply(id: java.lang.String, `type`: MSCredentialType): MSAssertion = { val __obj = js.Dynamic.literal(id = id.asInstanceOf[js.Any]) __obj.updateDynamic("type")(`type`.asInstanceOf[js.Any]) __obj.asInstanceOf[MSAssertion] } @scala.inline implicit class MSAssertionMutableBuilder[Self <: MSAssertion] (val x: Self) extends AnyVal { @scala.inline def setId(value: java.lang.String): Self = StObject.set(x, "id", value.asInstanceOf[js.Any]) @scala.inline def setType(value: MSCredentialType): Self = StObject.set(x, "type", value.asInstanceOf[js.Any]) } }
s-guillaume/nuxeo-web-ui
packages/nuxeo-web-ui-ftest/pages/ui/group.js
import BasePage from '../base'; export default class Group extends BasePage { getField(field) { driver.waitForExist(this._selector); driver.waitForVisible(this._selector); return this.el.element(`[id="${field}"]`); } get dropdown() { return this.el.element('#menu'); } get groupItem() { return this.el.element('paper-icon-item[name="group"]'); } get createGroupForm() { return this.el.element('nuxeo-create-group #form'); } get createGroupButton() { return this.el.element('nuxeo-create-group #createButton'); } get editGroupButton() { return this.el.element('#editGroupButton'); } get editGroupLabel() { return this.el.element('#editGroupDialog input'); } get editGroupDialogButton() { return this.el.element('#editGroupDialog paper-button.primary'); } get deleteGroupButton() { return this.el.element('#deleteGroupButton'); } get confirmDeleteGroupButton() { return this.el.element('#deleteGroupDialog paper-button'); } fillMultipleValues(table) { table.rows().forEach((row) => { if (row[0] === 'groupName') { // eslint-disable-next-line prefer-destructuring global.groups[row[1]] = row[1]; } const fieldEl = this.getField(row[0]); fieldEl.waitForVisible(); return fixtures.layouts.setValue(fieldEl, row[1]); }); } searchFor(searchTerm) { driver.waitForExist(this._selector); driver.waitForVisible(this._selector); const searchBox = this.el.element('nuxeo-user-group-search paper-input'); searchBox.waitForVisible(); return fixtures.layouts.setValue(searchBox, searchTerm); } searchResult(searchTerm) { this.el.waitForExist('nuxeo-card[name="groups"] .table [name="id"]'); return this.el.elementByTextContent('nuxeo-card[name="groups"] .table [name="id"]', searchTerm); } }
sabachan/framework
src/Core/Assert.cpp
<gh_stars>0 #include "stdafx.h" #include "Assert.h" #include "IntTypes.h" #include "Log.h" #include "WindowsH.h" #include <sstream> #include <unordered_set> namespace sg { //============================================================================= namespace { size_t PackFileAndLine_CanCollide(char const* iFile, size_t iLine) { static const size_t rscount = sizeof(size_t)*8 * 3/5; return (ptrdiff_t)iFile ^ (iLine << rscount); } } //============================================================================= bool HandleAssertFailedReturnMustBreak(char const* iExpr, char const* iMsg, char const* iFile, size_t iLine, char const* iFctName) { std::ostringstream oss; oss << "Assert FAILED :" << std::endl; oss << " (" << iExpr << ") is false" << std::endl; oss << "in " << iFctName << " (" << iFile << ":" << iLine << ")." << std::endl; if(nullptr != iMsg) oss << std::endl << iMsg << std::endl; SG_LOG_ERROR("Assert", oss.str().c_str()); static std::unordered_set<size_t> toIgnore; if(!toIgnore.empty()) { auto f = toIgnore.find(PackFileAndLine_CanCollide(iFile, iLine)); if(toIgnore.end() != f) return false; } bool enableBreakpoint = true; bool ignoreThisAssert = false; #if SG_PLATFORM_IS_WIN bool const isDebuggerPresent = IsDebuggerPresent() == TRUE; #else #error "todo" #endif if(!isDebuggerPresent) // disabled with debugger, as there is already a breakpoint with its own window { std::ostringstream oss2; oss2 << oss.str() << std::endl; oss2 << "(press abort to exit program, retry to continue, ignore to mute this assert)" << std::endl; int ret = MessageBox( NULL, oss2.str().c_str(), "Assert failed!", MB_ABORTRETRYIGNORE | MB_ICONERROR | MB_TASKMODAL | MB_TOPMOST | MB_SETFOREGROUND | MB_DEFBUTTON2 ); switch(ret) { case IDABORT: #if !SG_ENABLE_ASSERT exit(1); #endif enableBreakpoint = true; ignoreThisAssert = false; break; case IDIGNORE: enableBreakpoint = false; ignoreThisAssert = true; break; case IDRETRY: enableBreakpoint = false; ignoreThisAssert = false; break; default: SG_ASSERT_NOT_REACHED(); return false; } } if(ignoreThisAssert) { toIgnore.insert(PackFileAndLine_CanCollide(iFile, iLine)); } return enableBreakpoint; } //============================================================================= }
CommandPost/FinalCutProFrameworks
Headers/Frameworks/Ozone/OZCurveEditorAppDelegate-Protocol.h
<filename>Headers/Frameworks/Ozone/OZCurveEditorAppDelegate-Protocol.h // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 11 2021 20:53:35). // // Copyright (C) 1997-2019 <NAME>. // #import <Ozone/NSObject-Protocol.h> @class NSString; @protocol OZCurveEditorAppDelegate <NSObject> - (void)unsuppressEventCoalescing; - (void)suppressEventCoalescing; - (unsigned int)startTimecode; - (unsigned int)firstFrameNumber; - (BOOL)shouldDisplayTimeAsFrames; - (CDStruct_e83c9415)displayRange; - (void)setCurrentTime:(const CDStruct_1b6d18a9 *)arg1; - (CDStruct_1b6d18a9)currentTime; - (CDStruct_1b6d18a9)secondsPerTextStep; - (BOOL)isMotion; - (double)version; - (CDStruct_1b6d18a9)getFrameDuration; - (BOOL)isObjectSelected:(struct OZChannelObjectRootBase *)arg1; - (BOOL)objectsSelectedInScene; - (struct OZCurveSetListSerializer *)getCurveSetListSerializer; - (vector_187e9f86)selectedObjectsRootChannels; - (struct OZChannelObjectRootBase *)selectedObjectRoot; - (struct OZChannelObjectRootBase *)sceneChannelRoot; - (BOOL)isPlaying; - (void)abort; - (void)didSetChannelValue:(struct OZChannelBase *)arg1; - (void)willSetChannelValue:(struct OZChannelBase *)arg1; - (void)didChangeChannel:(struct OZChannelBase *)arg1; - (void)willChangeChannel:(struct OZChannelBase *)arg1; - (void)addChannelToUndo:(struct OZChannelBase *)arg1 undoDescription:(NSString *)arg2; - (void)addToUndo:(id)arg1 type:(int)arg2 action:(unsigned int)arg3 undoDescription:(NSString *)arg4; - (void)endCaptureModifiedChannels; - (void)startCaptureModifiedChannels:(NSString *)arg1; - (BOOL)wasChannelModified:(struct OZChannelBase *)arg1; - (void)resetModifiedChannels; - (vector_cdb86442)modifiedChannels; - (void)postNotification:(unsigned int)arg1; @end
gczhang-minhong/spring-boot-samples
spring-boot-demo/src/main/java/com/funtl/spring/hello/moudule/proxy/staticProxy/StaticProxy.java
<filename>spring-boot-demo/src/main/java/com/funtl/spring/hello/moudule/proxy/staticProxy/StaticProxy.java package com.funtl.spring.hello.moudule.proxy.staticProxy; import com.funtl.spring.hello.moudule.proxy.Man; import com.funtl.spring.hello.moudule.proxy.Person; /** * @PackgeName: com.funtl.spring.hello.moudule.proxy * @ClassName: StaticProxy * @Author: Administrator * Date: 2020/1/1 0001 17:35 * project name: spring-boot-alibaba-samples * @Version: * @Description: 静态代理 实现目标对象的代理 */ public class StaticProxy implements Person { private Person person; public StaticProxy(Person person) { this.person = person; } public void findLove(){ System.out.println("根据你的要求物色"); this.person.findLove(); System.out.println("双方父母是不是同意"); } //静态代理测试 public static void main(String[] args) { StaticProxy staticProxy = new StaticProxy(new Man()); staticProxy.findLove(); } }
langkcc/AndroidFramwork
androidframework/src/main/java/com/juefeng/android/framework/LKDownFileManager.java
package com.juefeng.android.framework; import com.juefeng.android.framework.down.DownHandler; import java.io.File; /** * Created with IntelliJ IDEA. * User: LangK * Date: 2017/9/28 * Time: 16:14 * Description: */ public interface LKDownFileManager { /** * down file. * support breakpoint resume * @param url url path * @param file local file * @param headler callback */ void downFile(String url, File file, DownHandler headler); void downFile(String url, File file, int threadNumber,DownHandler headler); }
TerikKek/Chuu
src/main/java/core/parsers/explanation/ArtistExplanation.java
package core.parsers.explanation; import core.parsers.explanation.util.Explanation; import core.parsers.explanation.util.ExplanationLineType; import core.parsers.explanation.util.Interactible; import net.dv8tion.jda.api.interactions.commands.OptionType; public class ArtistExplanation implements Explanation { public static final String NAME = "artist"; @Override public Interactible explanation() { return new ExplanationLineType(NAME, "The artist written will be used or if no artist is provided the artist that you are currently listening to will be used", OptionType.STRING); } }
NickRowell/companieshouseapiclient
src/dm/Links.java
/* * Gaia CU5 DU10 * * (c) 2005-2020 Gaia Data Processing and Analysis Consortium * * * CU5 photometric calibration software is free software; you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of the * License, or (at your option) any later version. * * CU5 photometric calibration software 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this CU5 software; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * *----------------------------------------------------------------------------- */ package dm; import java.io.Serializable; /** * A set of URLs related to a particular resource and providing links to other related resources. * * @author nrowell * @version $Id$ */ public class Links implements Serializable { /** * The serialVersionUID. */ private static final long serialVersionUID = 3033779799967794027L; /** * The nested URL of the officer appointments resource. */ public OfficerLink officer; /** * The URL of the company's charge resource. */ public String charges; /** * The URL of the company resource. */ public String company; /** * The URL of the company's filing history list resource. */ public String filing_history; /** * The URL of the company's insolvency list resource. */ public String insolvency; /** * The URL of the company's officer list resource. */ public String officers; /** * The URL of the company's persons with significant control list resource. */ public String persons_with_significant_control; /** * The URL of the company's persons with significant control statements list resource */ public String persons_with_significant_control_statements; /** * The URL of the registers resource for this company. */ public String registers; /** * The URL of the resource. */ public String self; /** * {@inheritDoc} */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("officer.appointments = ").append(officer.appointments).append("\n"); sb.append("charges = ").append(charges).append("\n"); sb.append("company = ").append(company).append("\n"); sb.append("filing_history = ").append(filing_history).append("\n"); sb.append("insolvency = ").append(insolvency).append("\n"); sb.append("officers = ").append(officers).append("\n"); sb.append("persons_with_significant_control = ").append(persons_with_significant_control).append("\n"); sb.append("persons_with_significant_control_statements = ").append(persons_with_significant_control_statements).append("\n"); sb.append("registers = ").append(registers).append("\n"); sb.append("self = ").append(self).append("\n"); return sb.toString(); } }
tooky/dm-more
dm-serializer/spec/unit/to_json_spec.rb
require 'pathname' require Pathname(__FILE__).dirname.expand_path.parent + 'spec_helper' describe DataMapper::Serialize, '#to_json' do # # ==== ajaxy JSON # before(:all) do query = DataMapper::Query.new(DataMapper::repository(:default), Cow) @collection = DataMapper::Collection.new(query) do |c| c.load([1, 2, 'Betsy', 'Jersey']) c.load([10, 20, 'Berta', 'Guernsey']) end @empty_collection = DataMapper::Collection.new(query) {} end it "serializes resource to JSON" do deserialized_hash = JSON.parse(Cow.new(:id => 1, :composite => 322, :name => "Harry", :breed => "Angus").to_json) deserialized_hash["id"].should == 1 deserialized_hash["composite"].should == 322 deserialized_hash["name"].should == "Harry" deserialized_hash["breed"].should == "Angus" end it "excludes nil attributes" do deserialized_hash = JSON.parse(Cow.new(:id => 1, :name => "Harry", :breed => "Angus").to_json) deserialized_hash["id"].should == 1 deserialized_hash["composite"].should be(nil) deserialized_hash["name"].should == "Harry" deserialized_hash["breed"].should == "Angus" end it "serializes collections to JSON by serializing each member" do deserialized_collection = JSON.parse(@collection.to_json) betsy = deserialized_collection.first berta = deserialized_collection.last betsy["id"].should == 1 betsy["composite"].should == 2 betsy["name"].should == "Betsy" betsy["breed"].should == "Jersey" berta["id"].should == 10 berta["composite"].should == 20 berta["name"].should == "Berta" berta["breed"].should == "Guernsey" end it "handles empty collections just fine" do deserialized_collection = JSON.parse(@empty_collection.to_json) deserialized_collection.should be_empty end it "handles options given to a collection properly" do deserialized_collection = JSON.parse(@collection.to_json(:only => [:composite])) betsy = deserialized_collection.first berta = deserialized_collection.last betsy["id"].should be_nil betsy["composite"].should == 2 betsy["name"].should be_nil betsy["breed"].should be_nil berta["id"].should be_nil berta["composite"].should == 20 berta["name"].should be_nil berta["breed"].should be_nil end it "serializes values returned by methods given to :methods option" do deserialized_hash = JSON.parse(Planet.new(:name => "Mars", :aphelion => 249_209_300.4).to_json(:methods => [:category, :has_known_form_of_life?])) deserialized_hash["category"].should == "terrestrial" deserialized_hash["has_known_form_of_life?"].should be(false) end it "only includes properties given to :only option" do deserialized_hash = JSON.parse(Planet.new(:name => "Mars", :aphelion => 249_209_300.4).to_json(:only => [:name])) deserialized_hash["name"].should == "Mars" deserialized_hash["aphelion"].should be(nil) end it "only includes properties given to :only option" do deserialized_hash = JSON.parse(Planet.new(:name => "Mars", :aphelion => 249_209_300.4).to_json(:exclude => [:aphelion])) deserialized_hash["name"].should == "Mars" deserialized_hash["aphelion"].should be(nil) end it "has higher presedence for :only option" do deserialized_hash = JSON.parse(Planet.new(:name => "Mars", :aphelion => 249_209_300.4).to_json(:only => [:aphelion], :exclude => [:aphelion])) deserialized_hash["name"].should be(nil) deserialized_hash["aphelion"].should == 249_209_300.4 end it "supports :include option for one level depth" it "supports :include option for more than one level depth" it "has :repository option to override used repository" end
gtkatakura/furb-learn-regex
client/components/exercises/Form.js
<filename>client/components/exercises/Form.js<gh_stars>1-10 import React from 'react'; import { FieldArray } from 'redux-form'; import { Form, TextField } from 'components/forms'; import { required } from 'validations'; import { SaveButton } from 'components/buttons'; import ExerciseSteps from './Steps'; import RegularExpressionField from './RegularExpressionField'; const ExerciseForm = ({ submitting, ...props }) => ( <div className="container"> <div className="row"> <div className="col-md-12 p-3"> <Form {...props}> <SaveButton type="submit" className="mb-2" disabled={submitting} /> <TextField name="description" label="Descrição" validate={required} /> <RegularExpressionField name="regularExpression" label="Expressão Regular" /> <FieldArray name="steps" component={ExerciseSteps} /> </Form> </div> </div> </div> ); export default ExerciseForm;
sidhoda/dnp3
cpp/libs/src/opendnp3/outstation/event/EventCollection.h
/* * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or * more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Green Energy Corp 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. * * This project was forked on 01/01/2013 by Automatak, LLC and modifications * may have been made to this file. Automatak, LLC licenses these modifications * to you under the terms of the License. */ #ifndef OPENDNP3_EVENTCOLLECTION_H #define OPENDNP3_EVENTCOLLECTION_H #include "IEventWriteHandler.h" #include "EventWriting.h" #include "TypedStorage.h" namespace opendnp3 { template <class T> class EventCollection final : public IEventCollection<typename T::meas_t> { private: List<EventRecord>::Iterator& iterator; EventClassCounters& counters; typename T::event_variation_t variation; public: EventCollection( List<EventRecord>::Iterator& iterator, EventClassCounters& counters, typename T::event_variation_t variation ) : iterator(iterator), counters(counters), variation(variation) {} virtual uint16_t WriteSome(IEventWriter<typename T::meas_t>& writer) override; private: bool WriteOne(IEventWriter<typename T::meas_t>& writer); }; template <class T> uint16_t EventCollection<T>::WriteSome(IEventWriter<typename T::meas_t>& writer) { uint16_t num_written = 0; while (WriteOne(writer)) { ++num_written; } return num_written; } template <class T> bool EventCollection<T>::WriteOne(IEventWriter<typename T::meas_t>& writer) { // don't bother searching if (this->counters.selected == 0) return false; // find the next event with the same type and variation EventRecord* record = EventWriting::FindNextSelected(this->iterator, T::EventTypeEnum); // nothing left to write if (!record) return false; const auto data = TypedStorage<T>::Retrieve(*record); // wrong variation if (data->value.selectedVariation != this->variation) return false; // unable to write if (!writer.Write(data->value.value, record->index)) return false; // success! this->counters.OnWrite(record->clazz); record->state = EventState::written; this->iterator.Next(); return true; } } #endif
apm-learning/ApplicationInsights-Java
test/smoke/framework/utils/src/main/java/com/microsoft/applicationinsights/smoketest/HttpHelper.java
/* * ApplicationInsights-Java * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * 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 com.microsoft.applicationinsights.smoketest; import java.io.IOException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpHelper { public static int getResponseCodeEnsuringSampled(String url) throws IOException { HttpGet httpGet = new HttpGet(url); // traceId=27272727272727272727272727272727 is known to produce a score of 0.66 (out of 100) // so will be sampled as long as samplingPercentage > 1% httpGet.setHeader("traceparent", "00-27272727272727272727272727272727-1111111111111111-01"); return getResponseCode(httpGet); } public static String get(String url) throws IOException { return getBody(new HttpGet(url)); } private static String getBody(HttpGet httpGet) throws IOException { try (CloseableHttpClient client = getHttpClient()) { try (CloseableHttpResponse response = client.execute(httpGet)) { return EntityUtils.toString(response.getEntity()); } } } private static int getResponseCode(HttpGet httpGet) throws IOException { try (CloseableHttpClient client = getHttpClient()) { CloseableHttpResponse resp1 = client.execute(httpGet); EntityUtils.consume(resp1.getEntity()); return resp1.getStatusLine().getStatusCode(); } } private static CloseableHttpClient getHttpClient() { return HttpClientBuilder.create().disableAutomaticRetries().build(); } public static String post(String url, String body) throws IOException { try (CloseableHttpClient client = getHttpClient()) { HttpPost post = new HttpPost(url); post.setEntity(new StringEntity(body)); try (CloseableHttpResponse response = client.execute(post)) { return EntityUtils.toString(response.getEntity()); } } } private HttpHelper() {} }
angoodkind/darpa_aa
src/ngrammodel/FourgramModel.java
package ngrammodel; import java.io.*; import java.util.*; import keystroke.KeyStroke; public class FourgramModel implements Serializable { private static final long serialVersionUID = 6529685098267757691L; private ArrayList<String> unigrams; private HashMap<String,Integer> unigramCounts; private HashMap<Bigram,Integer> bigramCounts; private HashMap<Trigram,Integer> trigramCounts; private HashMap<Trigram,Double> trigramProbabilities; private HashMap<Fourgram,Integer> fourgramCounts; private HashMap<Fourgram,Double> fourgramProbabilities; private int vocabularySize; private boolean generated = false; public FourgramModel() {} /** * Create a FourgramModel from an ArrayList of unigram tokens * @param unigrams ArrayList of unigram tokens */ public FourgramModel(ArrayList<String> unigrams) { this.unigrams = unigrams; this.generate(); } public FourgramModel(HashMap<Bigram,Integer> bigramCounts, HashMap<Trigram,Integer> trigramCounts, HashMap<Fourgram,Integer> fourgramCounts, int vocabularySize) throws ModelGeneratorException { this.unigrams = new ArrayList<String>(Arrays.asList("EMPTY")); //no need to create unigrams this.unigramCounts = new HashMap<String,Integer>(); this.bigramCounts = bigramCounts; this.trigramCounts = trigramCounts; this.fourgramCounts = fourgramCounts; this.vocabularySize = vocabularySize; setFourgramProbabilities(); generated = true; } /** * Create a Fourgram Model from another Fourgram model * @param trigramModel */ public FourgramModel(FourgramModel fourgramModel) { this.unigrams = fourgramModel.getUnigrams(); this.unigramCounts = fourgramModel.getUnigramCountsMap(); this.bigramCounts = fourgramModel.getBigramCountsMap(); this.trigramCounts = fourgramModel.getTrigramCountsMap(); this.fourgramCounts = fourgramModel.getFourgramCountsMap(); this.fourgramProbabilities = fourgramModel.getFourgramProbabilitiesMap(); this.vocabularySize = fourgramModel.getVocabularySize(); this.generated = fourgramModel.isGenerated(); } /** * Imports a unigram list from a file * @param unigramFileName File containing unigram list */ public void setUnigramsFromFile(String unigramFileName) { try { File file = new File(unigramFileName); FileInputStream fileIStream = new FileInputStream(file); ObjectInputStream objectIStream = new ObjectInputStream(fileIStream); this.unigrams = (ArrayList<String>) objectIStream.readObject(); objectIStream.close(); } catch (IOException|ClassNotFoundException e) {e.printStackTrace();} } /** * After unigram list has been added, generate a model */ public void generate() { try { this.setUnigramCounts(); this.setVocabularySize(); this.setBigramTrigramFourgramCounts(); this.setFourgramProbabilities(); generated = true; } catch (ModelGeneratorException e) {e.printStackTrace();} } /** * From the unigram list, create the counts of all unique * unigrams * @throws ModelGeneratorException */ public void setUnigramCounts() throws ModelGeneratorException { if (unigrams==null) throw new ModelGeneratorException("Unigrams not set"); this.unigramCounts = new HashMap<String,Integer>(); for (String unigram : unigrams) { if (unigramCounts.containsKey(unigram)) unigramCounts.put(unigram, unigramCounts.get(unigram)+1); else { unigramCounts.put(unigram, 1); } } } /** * From the unigram list, create counts of unique fourgrams * @throws ModelGeneratorException */ public void setBigramTrigramFourgramCounts() throws ModelGeneratorException { if (unigrams==null || unigramCounts==null) throw new ModelGeneratorException("Unigrams or unigramCounts not set"); this.bigramCounts = new HashMap<Bigram,Integer>(); this.trigramCounts = new HashMap<Trigram,Integer>(); this.fourgramCounts = new HashMap<Fourgram,Integer>(); for (int i = 0; i < unigrams.size()-3; i++) { String gram1 = unigrams.get(i); String gram2 = unigrams.get(i+1); String gram3 = unigrams.get(i+2); String gram4 = unigrams.get(i+3); Bigram bigram = new Bigram(gram1,gram2); Trigram trigram = new Trigram(gram1,gram2,gram3); Fourgram fourgram = new Fourgram(gram1,gram2,gram3,gram4); if (bigramCounts.containsKey(bigram)) bigramCounts.put(bigram, bigramCounts.get(bigram)+1); else bigramCounts.put(bigram, 1); if (trigramCounts.containsKey(trigram)) trigramCounts.put(trigram, trigramCounts.get(trigram)+1); else trigramCounts.put(trigram, 1); if (fourgramCounts.containsKey(fourgram)) fourgramCounts.put(fourgram, fourgramCounts.get(fourgram)+1); else fourgramCounts.put(fourgram, 1); } } /** * sets probabilities of existing fourgrams * @throws ModelGeneratorException */ public void setFourgramProbabilities() throws ModelGeneratorException { if (unigrams==null || unigramCounts==null || bigramCounts==null || trigramCounts==null || fourgramCounts==null) throw new ModelGeneratorException("Unigrams, unigramCounts, bigramCounts, trigramCounts or fourgramCounts not set"); fourgramProbabilities = new HashMap<Fourgram,Double>(); for (Fourgram fourgram : this.fourgramCounts.keySet()) { int trigramCount = this.getTrigramCount(new Trigram(fourgram.gram1,fourgram.gram2,fourgram.gram3)); int fourgramCount = this.getFourgramCount(fourgram); double fourgramProbability = (fourgramCount*1.0)/trigramCount; fourgramProbabilities.put(fourgram, fourgramProbability); } } /** * Returns a smoothed probability of a fourgram, using * the inverse vocabulary size to smooth * @return smoothed probability */ public double getFourgramProbability(String gram1, String gram2, String gram3,String gram4) { int trigramCount = 0; int fourgramCount = 0; Trigram trigram = new Trigram(gram1,gram2,gram3); Fourgram fourgram = new Fourgram(gram1,gram2,gram3,gram4); if (this.getTrigramCountsMap().containsKey(trigram)) trigramCount = this.getTrigramCount(trigram); if (this.getFourgramCountsMap().containsKey(fourgram)) fourgramCount = this.getFourgramCount(fourgram); double inverseVocab = 1.0/this.getVocabularySize(); double smoothed = ((double)fourgramCount+inverseVocab)/((double)trigramCount+(fourgramCounts.keySet().size()*inverseVocab)); return smoothed; } public ArrayList<String> getUnigrams() { return unigrams; } public void setUnigrams(ArrayList<String> unigrams) { this.unigrams = unigrams; } public int getUnigramCount(String unigram) { return unigramCounts.get(unigram); } public HashMap<String, Integer> getUnigramCountsMap() { return unigramCounts; } public void setUnigramCountsMap(HashMap<String, Integer> unigramCounts) { this.unigramCounts = unigramCounts; } public int getBigramCount(Bigram bigram) { return this.bigramCounts.get(bigram); } public HashMap<Bigram, Integer> getBigramCountsMap() { return bigramCounts; } public void setBigramCountsMap(HashMap<Bigram, Integer> bigramCounts) { this.bigramCounts = bigramCounts; } public int getTrigramCount(Trigram trigram) { return this.trigramCounts.get(trigram); } public HashMap<Trigram, Integer> getTrigramCountsMap() { return trigramCounts; } public void setTrigramCountsMap(HashMap<Trigram, Integer> trigramCounts) { this.trigramCounts = trigramCounts; } public double getFourgramProbability(KeyStroke ks1, KeyStroke ks2, KeyStroke ks3, KeyStroke ks4) { String gram1 = KeyStroke.vkCodetoString(ks1.getKeyCode()); String gram2 = KeyStroke.vkCodetoString(ks2.getKeyCode()); String gram3 = KeyStroke.vkCodetoString(ks3.getKeyCode()); String gram4 = KeyStroke.vkCodetoString(ks4.getKeyCode()); return this.getFourgramProbability(gram1,gram2,gram3,gram4); } public double getFourgramProbability(Fourgram fourgram) { return this.getFourgramProbability(fourgram.getGram1(), fourgram.getGram2(), fourgram.getGram3(), fourgram.getGram4()); } public HashMap<Fourgram, Double> getFourgramProbabilitiesMap() { return fourgramProbabilities; } public void setTrigramProbabilitiesMap(HashMap<Trigram, Double> trigramProbabilities) { this.trigramProbabilities = trigramProbabilities; } public void setVocabularySize() throws ModelGeneratorException { if (unigrams==null) throw new ModelGeneratorException("Unigrams not set"); Set<String> vocab = new HashSet<String>(unigrams); vocabularySize = vocab.size(); } public int getVocabularySize() { return vocabularySize; } public boolean isGenerated() { return generated; } public HashMap<Fourgram,Integer> getFourgramCountsMap() { return fourgramCounts; } public int getFourgramCount(Fourgram fourgram) { return fourgramCounts.get(fourgram); } /** * Writes a generated model to an external file * @param fileName File name where Model is to be written * @throws ModelGeneratorException */ public void exportToFile(String fileName) throws ModelGeneratorException { if (!this.isGenerated()) throw new ModelGeneratorException("Fourgram Model not generated"); try { File file = new File(fileName); FileOutputStream fileOStream = new FileOutputStream(file); ObjectOutputStream objectOStream = new ObjectOutputStream(fileOStream); objectOStream.writeObject(this); objectOStream.close(); } catch (IOException e) {e.printStackTrace();} } /** * Read a fourgram model from an external file * @param fileName File containing fourgram Model * @return Fourgram model contained in file */ public static FourgramModel readFromFile(String fileName) { FourgramModel model = null; try { File file = new File(fileName); FileInputStream fileIStream = new FileInputStream(file); ObjectInputStream objectIStream = new ObjectInputStream(fileIStream); model = (FourgramModel) objectIStream.readObject(); objectIStream.close(); } catch(IOException|ClassNotFoundException e) {e.printStackTrace();} return model; } }
wangyuxiang0829/Codeforces-CPP
src/dynamic_programming/494.cpp
#include <vector> #include <cassert> #include <algorithm> using namespace std; class Solution { public: int findTargetSumWays(vector<int> &nums, int S) { int sum = 0; for_each(nums.begin(), nums.end(), [&](int num) { sum += num; }); if (sum < S || ((sum + S) & 1) != 0) return 0; int V = (sum + S) / 2; vector<int> dp(V + 1); dp[0] = 1; for (auto num : nums) { int i = V; while (i >= num) { dp[i] = dp[i] + dp[i - num]; i--; } } return dp[V]; } }; int main() { vector<int> nums = {1, 1, 1, 1, 1}; assert(Solution().findTargetSumWays(nums, 3) == 5); }
AdlerFleurant/roller
app/src/main/webapp/roller-ui/authoring/editors/xinha-1.5.1/plugins/MootoolsFileManager/MootoolsFileManager.FileManager.js
/** = Mootools File Manager = == File Manager == The functions in this file extend the MootoolsFileManager plugin with support for managing files (inserting a link to a file). This file is loaded automatically. * @author $Author$ * @version $Id$ * @package MootoolsFileManager */ // Open a "files" mode of the plugin to allow to select a file to // create a link to. MootoolsFileManager.prototype.OpenFileManager = function(link) { var editor = this.editor; var outparam = null; var self = this; if (typeof link == "undefined") { link = this.editor.getParentElement(); if (link) { if (/^img$/i.test(link.tagName)) link = link.parentNode; if (!/^a$/i.test(link.tagName)) link = null; } } // If the link wasn't provided, and no link is currently in focus, // make one from the selection. if (!link) { var sel = editor.getSelection(); var range = editor.createRange(sel); var compare = 0; if (Xinha.is_ie) { if ( sel.type == "Control" ) { compare = range.length; } else { compare = range.compareEndPoints("StartToEnd", range); } } else { compare = range.compareBoundaryPoints(range.START_TO_END, range); } if (compare == 0) { alert(Xinha._lc("You must select some text before making a new link.", 'MootoolsFileManager')); return; } outparam = { f_href : '', f_title : '', f_target : '', f_type: '', baseHref: editor.config.baseHref }; } else { outparam = { f_href : Xinha.is_ie ? link.href : link.getAttribute("href"), f_title : link.title, f_target : link.target, f_type : link.type ? link.type : '', baseHref: editor.config.baseHref }; } this.current_link = link; this.current_attributes = outparam; if(!this.FileManagerWidget) { this.FileManagerWidget = new FileManager({ url: this.editor.config.MootoolsFileManager.backend, assetBasePath: Xinha.getPluginDir('MootoolsFileManager')+'/mootools-filemanager/Assets', language: _editor_lang, selectable: true, upload: this.phpcfg.files_allow_upload, destroy: this.phpcfg.files_allow_delete, createFolders: this.phpcfg.files_allow_create_dir, rename: this.phpcfg.files_allow_move, move_or_copy: this.phpcfg.files_allow_move, download: this.phpcfg.files_allow_download, propagateData: Object.merge({'__function': 'file-manager'}, this.editor.config.MootoolsFileManager.backend_data), propagateType: 'POST', uploadAuthData: Object.merge({'__function': 'file-manager'}, this.editor.config.MootoolsFileManager.backend_data), onComplete: function(path, file, mgr) { self.FileManagerReturn(path,file); }, onHide: function() { if(this.swf && this.swf.box) this.swf.box.style.display = 'none'; }, onShow: function() { if(this.swf && this.swf.box) this.swf.box.style.display = ''; }, onDetails: function(details) { this.info.adopt(self.FileManagerAttributes(details)); return true; }, onHidePreview: function() { document.id(self.FileManagerAttributes().table).dispose(); return true; }, showDirGallery: false, keyboardNavigation: false, listType: this.phpcfg.files_list_type, listPaginationSize: this.phpcfg.files_pagination_size, listMaxSuggestedDirSizeForThumbnails: this.phpcfg.files_list_mode_over, directory: this.phpcfg.files_list_start_in }); } // IE11 which pretends it is "gecko" is particularly finicky // about losing selection other browsers not so much, but they // don't seem to mind saving and restoring it anyway, so we // will do that for everybody if(1||Xinha.is_ie) this.current_selection = this.editor.saveSelection(); if(link) { var src = Xinha.is_ie ? link.href : link.getAttribute("href"); if(!src.match(/^(([a-z]+:)|\/)/i)) { src = self.editor.config.baseHref.replace(/\/[^\/]*$/, '') + '/' + src; if(src.match(/^[a-z]+:/i) && !self.phpcfg.files_url.match(/^[a-z]:/i)) { src = src.replace(/^[a-z]+:(\/\/?)[^/]*/i, ''); } } // Get exploded path without the base url var path = src.replace(self.phpcfg.files_url+'/', '').split('/'); // Pull off the file var base = path.pop(); // Join the path back togethor (no base url, trailing slash if the path has any length) path = path.length ? (path.join('/') + '/') : ''; // feed to widget this.FileManagerWidget.show(null, path, base); } else { this.FileManagerWidget.show(); } }; // Take the values from the file selection and make it (or update) a link MootoolsFileManager.prototype.FileManagerReturn = function(path, file) { var editor = this.editor; var a = this.current_link; var param = this.FileManagerAttributes(); param.f_href = path; // IE11 which pretends it is "gecko" is particularly finicky // about losing selection other browsers not so much, but they // don't seem to mind saving and restoring it anyway, so we // will do that for everybody if(1||Xinha.is_ie) this.editor.restoreSelection(this.current_selection); if (!a) { try { editor._doc.execCommand("createlink", false, param.f_href); a = editor.getParentElement(); var sel = editor.getSelection(); var range = editor.createRange(sel); if (!Xinha.is_ie) { a = range.startContainer; if (!/^a$/i.test(a.tagName)) { a = a.nextSibling; if (a == null) { a = range.startContainer.parentNode; } } } } catch(e) {} } else { var href = param.f_href.trim(); editor.selectNodeContents(a); if (href == "") { editor._doc.execCommand("unlink", false, null); editor.updateToolbar(); return false; } else { a.href = href; } } if (!(a && /^a$/i.test(a.tagName))) { return false; } a.type = param.f_type.trim(); a.target = param.f_target.trim(); a.title = param.f_title.trim(); editor.selectNodeContents(a); editor.updateToolbar(); }; /** Return a DOM fragment which has all the fields needed to set the * attributes for a link given a structure of initial values. * * OR return a structure of values taken from the currently table. */ MootoolsFileManager.prototype.FileManagerAttributes = function (details) { var self = this; self._LastFileDetails = details; function f(name) { var e = self._FileManagerAttributesTable.getElementsByTagName('input'); for(var i = 0; i < e.length; i++) { if(e[i].name == name) return e[i]; } var e = self._FileManagerAttributesTable.getElementsByTagName('select'); for(var i = 0; i < e.length; i++) { if(e[i].name == name) return e[i]; } return null; } function s(name, value) { for(var i = 0; i < f(name).options.length; i++) { if(f(name).options[i].value == value) { // f(name).options[i].selected = true; f(name).selectedIndex = i; return true; } } return false; } if(!this._FileManagerAttributesTable) { this._FileManagerAttributesTable = (function() { var div = document.createElement('div'); var h2 = document.createElement('h2'); h2.appendChild(document.createTextNode('Link Attributes')); div.appendChild(h2); var table = document.createElement('table'); div.appendChild(table); table.className = 'filemanager-extended-options'; var tbody = table.appendChild(document.createElement('tbody')); { // Title var tr = tbody.appendChild(document.createElement('tr')); var th = tr.appendChild(document.createElement('th')); var label = th.appendChild(document.createTextNode('Title:')); var td = tr.appendChild(document.createElement('td')); var input = td.appendChild(document.createElement('input')); td.colSpan = 6; input.name = 'f_title'; input.type = 'text'; th.className = td.className = 'filemanager-f_title'; } { // Content Type var tr = tbody.appendChild(document.createElement('tr')); var th = tr.appendChild(document.createElement('th')); var label = th.appendChild(document.createTextNode('Type:')); var td = tr.appendChild(document.createElement('td')); var input = td.appendChild(document.createElement('input')); td.colSpan = 6; input.name = 'f_type'; input.type = 'text'; th.className = td.className = 'filemanager-f_type'; } { // Target var tr = tbody.appendChild(document.createElement('tr')); { // Target var th = tr.appendChild(document.createElement('th')); var label = th.appendChild(document.createTextNode('Open In:')); var td = tr.appendChild(document.createElement('td')); td.colSpan = 2; var input = td.appendChild(document.createElement('select')); input.name = 'f_target'; input.options[0] = new Option(''); input.options[1] = new Option('New Window', '_blank'); input.options[2] = new Option('Top Frame', '_top'); input.options[3] = new Option('Other Frame:', ''); Xinha._addEvent(input, 'change', function() { if(f('f_target').selectedIndex == 3) { f('f_otherTarget').style.visibility = 'visible'; } else { f('f_otherTarget').style.visibility = 'hidden'; } }); var input = td.appendChild(document.createElement('input')); input.name = 'f_otherTarget'; input.size = 7; input.type = 'text'; input.style.visibility = 'hidden'; th.className = td.className = 'filemanager-f_target'; } } return div; })(); } if(this.current_attributes) { f('f_title').value = this.current_attributes.f_title; f('f_type').value = this.current_attributes.f_type; if(this.current_attributes.f_target) { if(!s('f_target', this.current_attributes.f_target)) { f('f_target').selectedIndex = 3; f('f_otherTarget').value = this.current_attributes.f_target; } else { f('f_otherTarget').value = ''; } } this.current_attributes = null; } // If no details were supplied, we return the current ones if(!details) { var details = { f_title: f('f_title').value, f_type: f('f_type').value, f_target: f('f_target').selectedIndex < 3 ? f('f_target').options[f('f_target').selectedIndex].value : f('f_otherTarget').value, table: this._FileManagerAttributesTable } return details; } // If details were supplied, we set the appropriate ones. if(details.mime) f('f_type').value = details.mime; f('f_target').style.visibility = ''; // Ensure that the select hasn't been hidden by an overlay and not put back if(f('f_target').selectedIndex == 3) { f('f_otherTarget').style.visibility = 'visible'; } else { f('f_otherTarget').style.visibility = 'hidden'; } return this._FileManagerAttributesTable; };
katoy/rails4-teams
app/models/relationship.rb
<reponame>katoy/rails4-teams # people 1:<->:n (Developer, Staff) class Relationship < ActiveRecord::Base has_many :jobkinds, dependent: :destroy belongs_to :follower, class_name: 'Person' belongs_to :followed, class_name: 'Person' default_scope -> { order(created_at: :asc) } validates :follower_id, presence: true validates :followed_id, presence: true end
moogacs/aws-sdk-go-v2
service/internal/benchmark/dynamodb/customizations_test.go
<filename>service/internal/benchmark/dynamodb/customizations_test.go package benchmark import ( "bytes" "compress/gzip" "context" "fmt" "io" "io/ioutil" "net/http" "os" "path/filepath" "strconv" "testing" "github.com/aws/aws-sdk-go-v2/internal/awstesting/unit" "github.com/aws/aws-sdk-go-v2/service/dynamodb" awsOld "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/corehandlers" credsOld "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/aws/session" ddbOld "github.com/aws/aws-sdk-go/service/dynamodb" ) type testData struct { filename string respChecksum int respGzipChecksum int } func BenchmarkCustomizations(b *testing.B) { cases := map[string]testData{ "small": { filename: filepath.Join("testdata", "scan_response.short.json"), respChecksum: 512691431, respGzipChecksum: 891511383, }, "large": { filename: filepath.Join("testdata", "scan_response.json"), respChecksum: 4158286593, respGzipChecksum: 3095499784, }, } for name, c := range cases { b.Run(name, func(b *testing.B) { b.Run("old", func(b *testing.B) { benchCustomizationsOld(b, c) }) b.Run("smithy", func(b *testing.B) { benchCustomizationsSmithy(b, c) }) }) } } func benchCustomizationsOld(b *testing.B, c testData) { _, body, err := loadBenchTestData(c.filename) if err != nil { b.Fatalf("failed to load test data, %s, %v", c.filename, err) } sess, err := session.NewSession(&awsOld.Config{ Credentials: credsOld.NewStaticCredentials("AKID", "SECRET", ""), Region: awsOld.String("us-west-2"), }) sess.Handlers.Send.SwapNamed(request.NamedHandler{ Name: corehandlers.SendHandler.Name, Fn: func(r *request.Request) { r.HTTPResponse = &http.Response{ StatusCode: 200, Header: http.Header{ "X-Amz-Crc32": []string{strconv.Itoa(c.respChecksum)}, }, ContentLength: int64(len(body)), Body: ioutil.NopCloser(bytes.NewReader(body)), } }}) if err != nil { b.Fatalf("failed to load session, %v", err) } b.Run("default", func(b *testing.B) { client := ddbOld.New(sess) doBenchScanOld(b, client) }) b.Run("none enabled", func(b *testing.B) { client := ddbOld.New(sess, &awsOld.Config{ DisableComputeChecksums: awsOld.Bool(true), }) doBenchScanOld(b, client) }) } func doBenchScanOld(b *testing.B, client *ddbOld.DynamoDB) { b.Helper() tableName := "mockTable" params := ddbOld.ScanInput{ TableName: &tableName, } ctx := context.Background() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _, err := client.ScanWithContext(ctx, &params) if err != nil { b.Fatalf("expect no error, %v", err) } } }) } func benchCustomizationsSmithy(b *testing.B, c testData) { gzipBody, body, err := loadBenchTestData(c.filename) if err != nil { b.Fatalf("failed to load test data, %s, %v", c.filename, err) } options := dynamodb.Options{ Region: "us-west-2", Credentials: unit.StubCredentialsProvider{}, HTTPClient: &mockClient{ ChecksumHeaderValue: []string{strconv.Itoa(c.respChecksum)}, ScanRespBody: body, }, } b.Run("default", func(b *testing.B) { client := dynamodb.New(options) doBenchScan(b, client) }) b.Run("all enabled", func(b *testing.B) { client := dynamodb.New(options, func(o *dynamodb.Options) { o.HTTPClient = &mockClient{ ChecksumHeaderValue: []string{strconv.Itoa(c.respGzipChecksum)}, ScanRespGzipBody: gzipBody, } o.DisableValidateResponseChecksum = false o.EnableAcceptEncodingGzip = true }) doBenchScan(b, client) }) b.Run("none enabled", func(b *testing.B) { client := dynamodb.New(options, func(o *dynamodb.Options) { o.DisableValidateResponseChecksum = true o.EnableAcceptEncodingGzip = false }) doBenchScan(b, client) }) b.Run("checksum only", func(b *testing.B) { client := dynamodb.New(options) doBenchScan(b, client) }) b.Run("gzip only", func(b *testing.B) { client := dynamodb.New(options, func(o *dynamodb.Options) { o.HTTPClient = &mockClient{ ScanRespGzipBody: gzipBody, } o.DisableValidateResponseChecksum = true o.EnableAcceptEncodingGzip = true }) doBenchScan(b, client) }) } type mockClient struct { ChecksumHeaderValue []string ScanRespGzipBody []byte ScanRespBody []byte } func (m *mockClient) Do(r *http.Request) (*http.Response, error) { resp := &http.Response{ StatusCode: 200, Header: http.Header{ "Content-Type": []string{"application/x-amz-json-1.0"}, }, } if m.ChecksumHeaderValue != nil { resp.Header["X-Amz-Crc32"] = m.ChecksumHeaderValue } if m.ScanRespGzipBody != nil { resp.Header["Content-Encoding"] = []string{"gzip"} resp.ContentLength = int64(len(m.ScanRespGzipBody)) resp.Body = ioutil.NopCloser(bytes.NewReader(m.ScanRespGzipBody)) } else if m.ScanRespBody != nil { resp.ContentLength = int64(len(m.ScanRespBody)) resp.Body = ioutil.NopCloser(bytes.NewReader(m.ScanRespBody)) } else { return nil, fmt.Errorf("no client mock response body set") } return resp, nil } func doBenchScan(b *testing.B, client *dynamodb.Client) { b.Helper() tableName := "mockTable" params := dynamodb.ScanInput{ TableName: &tableName, } ctx := context.Background() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _, err := client.Scan(ctx, &params) if err != nil { b.Fatalf("expect no error, %v", err) } } }) } func loadBenchTestData(filename string) ([]byte, []byte, error) { f, err := os.Open(filename) if err != nil { return nil, nil, fmt.Errorf("failed to open test data %v", err) } defer f.Close() var body bytes.Buffer if _, err := io.Copy(&body, f); err != nil { return nil, nil, fmt.Errorf("failed to read test data %v", err) } var gzipBody bytes.Buffer w := gzip.NewWriter(&gzipBody) w.Write(body.Bytes()) w.Close() return gzipBody.Bytes(), body.Bytes(), nil }
sansergio/thread-example
myTempSensor_REED/middleware/wireless/nwk_ip_1.2.1/base/stack_globals/icmp_globals.c
/* * Copyright (c) 2014 - 2015, Freescale Semiconductor, Inc. * Copyright 2016-2017 NXP * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*! \file icmp_globals.c \brief This is the source file that contains parameters for the ICMP module that can be configured by the application */ /*================================================================================================== Include Files ==================================================================================================*/ #include "stack_config.h" #include "icmp.h" #include "ip.h" extern const icmpProtMsgTypeHandler_t gaIcmpProtMsgTypeHandlerTbl6[]; extern const uint8_t gIcmpProtMsgTypeHandlerTbl6Size; extern const icmpProtMsgTypeHandler_t gaThrRouterImcpErrorHandler[]; extern const uint8_t gThrRouterImcpErrorHandlerSize; extern const icmpProtMsgTypeHandler_t gaUdpMsgTypeHandlerTbl6[]; extern const uint8_t gUdpMsgTypeHandlerTbl6Size; extern const icmpProtMsgTypeHandler_t gaShellProtMsgTypeHandlerTbl6[]; extern const uint8_t gShellProtMsgTypeHandlerTbl6Size; extern const icmpProtMsgTypeHandler_t gaShellProtMsgTypeHandlerTbl4[]; extern const uint8_t gShellProtMsgTypeHandlerTbl4Size; #if IP_IP4_ENABLE extern const icmpProtMsgTypeHandler_t gaIcmpProtMsgTypeHandlerTbl4[]; extern const uint8_t gIcmpProtMsgTypeHandlerTbl4Size; #if UDP_TREAT_ICMP_PORT_UNR extern const icmpProtMsgTypeHandler_t gaUdpMsgTypeHandlerTbl4[]; extern const uint8_t gUdpMsgTypeHandlerTbl4Size; #endif #endif #if ND_ENABLED extern const icmpProtMsgTypeHandler_t gaNdIcmpProtMsgTypeHandlerTbl6[]; extern const uint8_t gNdIcmpProtMsgTypeHandlerTbl6Size; #endif #if PMTU_REGISTER_ICMP_PKT_TOO_BIG_HANDLER || PMTU_REGISTER_TCP_PKT_TOO_BIG_HANDLER || PMTU_REGISTER_UDP_PKT_TOO_BIG_HANDLER extern const icmpProtMsgTypeHandler_t gaPmtuIcmpProtMsgTypeHandlerTbl6[]; extern const uint8_t gPmtuIcmpProtMsgTypeHandlerTbl6Size; #endif /*================================================================================================== Private macros ==================================================================================================*/ /*================================================================================================== Private type definitions ==================================================================================================*/ /*================================================================================================== Private prototypes ==================================================================================================*/ /*================================================================================================== Private global variables declarations ==================================================================================================*/ /*================================================================================================== Public global variables declarations ==================================================================================================*/ /* Register ICMP receive callbacks */ const icmpMsgTypeHandler_t gaIcmpMsgTypeHandlerTable[]= { /*ICMP*/ {NULL, (icmpProtMsgTypeHandler_t*)&gaIcmpProtMsgTypeHandlerTbl6,IPPROTO_ICMPV6, (uint8_t*)&gIcmpProtMsgTypeHandlerTbl6Size}, /*THR*/ {NULL, (icmpProtMsgTypeHandler_t*)&gaThrRouterImcpErrorHandler,IPPROTO_ICMPV6, (uint8_t*)&gThrRouterImcpErrorHandlerSize}, {NULL, (icmpProtMsgTypeHandler_t*)&gaThrRouterImcpErrorHandler,IPPROTO_UDP, (uint8_t*)&gThrRouterImcpErrorHandlerSize}, /*UDP*/ {NULL, (icmpProtMsgTypeHandler_t*)&gaUdpMsgTypeHandlerTbl6, IPPROTO_UDP , (uint8_t*)&gUdpMsgTypeHandlerTbl6Size}, #if ND_ENABLED /*ND*/ {NULL, (icmpProtMsgTypeHandler_t*)&gaNdIcmpProtMsgTypeHandlerTbl6, IPPROTO_ICMPV6 , (uint8_t*)&gNdIcmpProtMsgTypeHandlerTbl6Size}, #if PMTU_REGISTER_ICMP_PKT_TOO_BIG_HANDLER {NULL, (icmpProtMsgTypeHandler_t*)&gaPmtuIcmpProtMsgTypeHandlerTbl6, IPPROTO_ICMPV6 , (uint8_t*)&gPmtuIcmpProtMsgTypeHandlerTbl6Size}, #endif #if PMTU_REGISTER_TCP_PKT_TOO_BIG_HANDLER {NULL, (icmpProtMsgTypeHandler_t*)&gaPmtuIcmpProtMsgTypeHandlerTbl6, IPPROTO_TCP , (uint8_t*)&gPmtuIcmpProtMsgTypeHandlerTbl6Size}, #endif #if PMTU_REGISTER_UDP_PKT_TOO_BIG_HANDLER {NULL, (icmpProtMsgTypeHandler_t*)&gaPmtuIcmpProtMsgTypeHandlerTbl6, IPPROTO_UDP , (uint8_t*)&gPmtuIcmpProtMsgTypeHandlerTbl6Size}, #endif #endif #if IP_IP4_ENABLE /* ICMP */ {NULL, (icmpProtMsgTypeHandler_t*)&gaIcmpProtMsgTypeHandlerTbl4, IPPROTO_ICMP , (uint8_t*)&gIcmpProtMsgTypeHandlerTbl4Size}, #if UDP_TREAT_ICMP_PORT_UNR /*UDP*/ {NULL, (icmpProtMsgTypeHandler_t*)&gaUdpMsgTypeHandlerTbl4, IPPROTO_UDP , (uint8_t*)&gUdpMsgTypeHandlerTbl4Size}, #endif #endif #if THREAD_USE_SHELL || THREAD_USE_THCI /*SHELL_APP OR THCI*/ {NULL, (icmpProtMsgTypeHandler_t*)&gaShellProtMsgTypeHandlerTbl6, IPPROTO_ICMPV6, (uint8_t*)&gShellProtMsgTypeHandlerTbl6Size}, /*SHELL_APP OR THCI*/ {NULL, (icmpProtMsgTypeHandler_t*)&gaShellProtMsgTypeHandlerTbl4, IPPROTO_ICMP, (uint8_t*)&gShellProtMsgTypeHandlerTbl4Size} #endif }; const uint8_t gIcmpMsgTypeHandlerSize = sizeof(gaIcmpMsgTypeHandlerTable)/ sizeof(icmpMsgTypeHandler_t); /*================================================================================================== Private functions ==================================================================================================*/ /*================================================================================================== Public functions ==================================================================================================*/
davidbhon/dpc-app
dpc-go/dpc-api/src/constants/constants.go
<filename>dpc-go/dpc-api/src/constants/constants.go package constants type contextKey int const ( // OrgHeader is used in place of a auth token until SSAS is implemented OrgHeader string = "X-ORG" // FwdHeader is used to pass on the requesting IP address to attribution FwdHeader string = "X-Forwarded-For" // RequestURLHeader is used to pass on the requestingUrl to attribution RequestURLHeader string = "X-Request-Url" // FhirNdjson is an allowed output format strings for export requests FhirNdjson string = "application/fhir+ndjson" // ApplicationNdjson is an allowed output format strings for export requests ApplicationNdjson string = "application/ndjson" // PatientString is the string constant for Patient PatientString string = "Patient" // EoBString is the string constant for ExplanationOfBenefit EoBString string = "ExplanationOfBenefit" // CoverageString is the string constant for Coverage CoverageString string = "Coverage" // AllResources is the list of allowed resources for export AllResources string = "Patient,Coverage,ExplanationOfBenefit" // SinceLayout is the time format for the since parameter SinceLayout string = "2006-01-02T15:04:05-07:00" // Ndjson is an allowed output format strings for export requests Ndjson string = "ndjson" // ProvenanceHeader is the provenance header ProvenanceHeader string = "X-Provenance" // FHIRIdentifierSystemHeader is the mbi identifier system FHIRIdentifierSystemHeader string = "identifier-system" // FHIRIdentifierValueHeader is the mbi identifier system FHIRIdentifierValueHeader string = "identifier-value" // APIScope is the api scope of this application APIScope string = "dpcv2-api" // ContextKeyOrganization is the key in the context to retrieve the organizationID ContextKeyOrganization contextKey = iota // ContextKeyRequestURL is the key in the context to retrieve the requestURL ContextKeyRequestURL // ContextKeyGroup is the key in the context to retrieve the groupID ContextKeyGroup // ContextKeyImplementer is the key in the context to retrieve the ImplementerID ContextKeyImplementer // ContextKeyRequestingIP is the key in the context to retrieve the requesting IP address ContextKeyRequestingIP // ContextKeyFileName is the key in the context to retrieve the file name ContextKeyFileName // ContextKeyJobID is the key in the context to retrieve the jobID ContextKeyJobID // ContextKeyResourceTypes is the key in the context to pass on the _types param values ContextKeyResourceTypes // ContextKeySince is the key in the context to pass on the _since param value ContextKeySince // ContextKeyImplementor is the key in the context to pass on the implementor path param value ContextKeyImplementor // ContextKeyTokenID is the key in the context to pass on the tokenID param value ContextKeyTokenID // ContextKeyKeyID is the key in the context to pass on the keyID param value ContextKeyKeyID // ContextKeyProvenanceHeader is the key in the context to pass on the provenance header ContextKeyProvenanceHeader // ContextKeyMBI is the key in the context to pass on the mbi header value ContextKeyMBI )
huizhongyu/tempProject
app/src/main/java/cn/closeli/rtc/VideoConferenceActivity.java
<gh_stars>0 package cn.closeli.rtc; import android.annotation.Nullable; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.PixelFormat; import android.hardware.display.DisplayManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.constraint.ConstraintLayout; import android.text.TextUtils; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.jaeger.library.StatusBarUtil; import com.neovisionaries.ws.client.WebSocketState; import com.vhd.base.util.LogUtil; import com.vhd.camera.CameraEncoderv2; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.webrtc.MediaStream; import org.webrtc.RendererCommon; import org.webrtc.SurfaceViewRenderer; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import cn.closeli.rtc.constract.Constract; import cn.closeli.rtc.constract.GlobalValue; import cn.closeli.rtc.constract.WsErrorCode; import cn.closeli.rtc.model.EventPublish; import cn.closeli.rtc.model.PadModel; import cn.closeli.rtc.model.ParticipantModel; import cn.closeli.rtc.model.ReplaceRollcallModel; import cn.closeli.rtc.model.RoomLayoutModel; import cn.closeli.rtc.model.RoomTimeModel; import cn.closeli.rtc.model.SlingModel; import cn.closeli.rtc.model.info.CompanyModel; import cn.closeli.rtc.model.info.GroupInfoModel; import cn.closeli.rtc.model.info.GroupListInfoModel; import cn.closeli.rtc.model.info.PartDeviceModel; import cn.closeli.rtc.model.info.ParticipantInfoModel; import cn.closeli.rtc.model.rtc.OrgList; import cn.closeli.rtc.model.rtc.UserDeviceList; import cn.closeli.rtc.model.ws.AudioStstusResp; import cn.closeli.rtc.model.ws.HandsStatusResp; import cn.closeli.rtc.model.ws.PresetInfoResp; import cn.closeli.rtc.model.ws.VideoStatusResp; import cn.closeli.rtc.model.ws.WsError; import cn.closeli.rtc.net.ServerManager; import cn.closeli.rtc.room.PadEvent; import cn.closeli.rtc.room.RoomClient; import cn.closeli.rtc.room.RoomEventAdapter; import cn.closeli.rtc.room.RoomEventCallback; import cn.closeli.rtc.room.WssMethodNames; import cn.closeli.rtc.sdk.CLRtcSinaling; import cn.closeli.rtc.sdk.IViewCallback; import cn.closeli.rtc.sdk.ProxyVideoSink; import cn.closeli.rtc.sdk.WebRTCManager; import cn.closeli.rtc.utils.ActivityUtils; import cn.closeli.rtc.utils.CallUtil; import cn.closeli.rtc.utils.Constants; import cn.closeli.rtc.utils.DeviceSettingManager; import cn.closeli.rtc.utils.L; import cn.closeli.rtc.utils.Operation; import cn.closeli.rtc.utils.PTZControlUtil; import cn.closeli.rtc.utils.RoomControl; import cn.closeli.rtc.utils.RoomManager; import cn.closeli.rtc.utils.SPEditor; import cn.closeli.rtc.utils.StringUtils; import cn.closeli.rtc.utils.SystemUtil; import cn.closeli.rtc.utils.UIUtils; import cn.closeli.rtc.utils.ViewUtils; import cn.closeli.rtc.utils.data_manager.VideoControlManager; import cn.closeli.rtc.widget.BoundShadowLayout; import cn.closeli.rtc.widget.DifferentDislay; import cn.closeli.rtc.widget.DynamicVideoLayout; import cn.closeli.rtc.widget.DynamicVideoLayout_; import cn.closeli.rtc.widget.FocusLayout; import cn.closeli.rtc.widget.ParticipantLayout; import cn.closeli.rtc.widget.UCToast; import cn.closeli.rtc.widget.VideoController; import cn.closeli.rtc.widget.VideoLayout; import cn.closeli.rtc.widget.dialog.InviteJoinDialog; import cn.closeli.rtc.widget.popwindow.HostInfoPopupWindow; import cn.closeli.rtc.widget.popwindow.InviteJoinInPopupWindow; import cn.closeli.rtc.widget.popwindow.LayoutChoosePopupWindow; import cn.closeli.rtc.widget.popwindow.MeetSettingPopupWindow; import cn.closeli.rtc.widget.popwindow.NetPopupWindow; import cn.closeli.rtc.widget.popwindow.ParticipantPopWindow; import cn.closeli.rtc.widget.popwindow.RollCallPopupWindow; import cn.closeli.rtc.widget.popwindow.TimeDownPopupWindow; import cn.closeli.rtc.widget.popwindow.VideoItemPopWindow; import me.jessyan.autosize.internal.CustomAdapt; import static cn.closeli.rtc.constract.Constract.MIX_MAJOR_AND_SHARING; import static cn.closeli.rtc.constract.Constract.change; import static cn.closeli.rtc.constract.Constract.replace; import static cn.closeli.rtc.constract.GlobalValue.KEY_PANTILT_CONTROL; import static cn.closeli.rtc.constract.GlobalValue.PANTILT_DOWN; import static cn.closeli.rtc.constract.GlobalValue.PANTILT_LEFT; import static cn.closeli.rtc.constract.GlobalValue.PANTILT_RIGHT; import static cn.closeli.rtc.constract.GlobalValue.PANTILT_STOP; import static cn.closeli.rtc.constract.GlobalValue.PANTILT_UP; import static cn.closeli.rtc.constract.GlobalValue.ZOOM_STOP; import static cn.closeli.rtc.constract.GlobalValue.ZOOM_TELE; import static cn.closeli.rtc.constract.GlobalValue.ZOOM_WIDE; import static cn.closeli.rtc.sdk.WebRTCManager.MAJOR; import static cn.closeli.rtc.sdk.WebRTCManager.ROLE_PUBLISHER; import static cn.closeli.rtc.sdk.WebRTCManager.ROLE_PUBLISHER_SUBSCRIBER; import static cn.closeli.rtc.sdk.WebRTCManager.SHARING; import static cn.closeli.rtc.utils.Constants.LOCAL_SCREEN; import static cn.closeli.rtc.utils.Constants.STREAM_MAJOR; import static cn.closeli.rtc.utils.Constants.STREAM_SHARING; public class VideoConferenceActivity extends BaseActivity implements DisplayManager.DisplayListener, VideoController.VideoPlayerControl, RoomClient.OnLocalShareJoinListener { //屏幕共享 requestCode private String logTag = this.getClass().getCanonicalName(); //key-value -> userId-FrameLayout private Map<String, ProxyVideoSink> _sinks = new HashMap<>(); //本地视频 ViewGroup @BindView(R.id.local_video_container) DynamicVideoLayout_ localVideoViewContainer; //本地视频 RelativeLayout @BindView(R.id.local_screen_container_out) RelativeLayout relativeLayout; @BindView(R.id.cl_main) ConstraintLayout cl_main; @BindView(R.id.shareHDMI) TextView shareHDMI; @BindView(R.id.all_frameLayout) FrameLayout all_frameLayout; @BindView(R.id.video_controller) VideoController videoController; private WebRTCManager webRTCManager; //本地视频 SurfaceView 视频源 摄像头 private SurfaceViewRenderer localHDMIVideoView; //分屏dialog DifferentDislay mPresentation; //屏幕管理类 DisplayManager mDisplayManager; private String connectId; private String userId; private String channelId; private String channelRole; private ParticipantPopWindow participantPopWindow; @Nullable private VideoItemPopWindow videoItemPopWindow; private NetPopupWindow netPopupWindow; /*本地基本属性初始化*/ private boolean enableShare = true; //共享 private boolean isLocalHas = false; //本地屏幕是否有人,回调addRemote需要 private boolean isShareHas = false; //分享屏幕是否有人,回调addRemote需要 private boolean isAllScreen = false; //是否全屏 private boolean isShareIng = false; //本人是否正在共享 private String screenId = ""; //加入房间后的主页面.用于换人 private String prensatationId = ""; //分屏的异屏显示Id; /** * 与会者 集合 */ private List<ParticipantInfoModel> participantModels; private List<ParticipantInfoModel> participantInfoModelsNoShare; private ArrayList<ParticipantInfoModel> tempParticpantModels = new ArrayList<>(); private FrameLayout.LayoutParams surfaceParams; private LinearLayout.LayoutParams localParams; //当前预览参数 private FrameLayout locaHDMIFramenLayout; private boolean supportHdmiIn = false; private MeetSettingPopupWindow meetSettingPopupWindow; private int choosePosition = Constract.AUDIO_STAND; private boolean useCamEncoded = false; private String lastBreakLineUserId = ""; private ArrayList<String> queues = new ArrayList<>(); private String currentSpeakUserId = ""; private String currentShareUser = ""; //当前正在发言的人 名称 private RoomLayoutModel roomLayoutModel; private ArrayList<String> roomLayouts = new ArrayList<>(); private String strOfKeySet; private boolean isCurrentAllScreenSelf = true; //当前全屏操作的是视图,是否是自己 private SurfaceViewRenderer presentationHDMIVideoView; private String currentAllscreenId = null; //当前全屏的ConnectionId private ParticipantInfoModel currentShareModel = null; public Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: setDuringTime(); handler.sendMessageDelayed(obtainMessage(1), 1000); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActivityUtils.getInstance().addActivity(this); mDisplayManager = (DisplayManager) this.getSystemService(Context.DISPLAY_SERVICE); mDisplayManager.registerDisplayListener(this, null); initPresentation(false); getWindow().setFormat(PixelFormat.TRANSPARENT); // showStatusBar(); StatusBarUtil.setColor(VideoConferenceActivity.this, getResources().getColor(R.color.color_translate)); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); ButterKnife.bind(this); Intent intent = getIntent(); userId = SPEditor.instance().getUserId(); connectId = RoomManager.get().getConnectionId(); channelId = RoomClient.get().getRoomId(); channelRole = intent.getStringExtra("channelRole"); RoomManager.get().setUserId(userId); RoomManager.get().setRole(channelRole); webRTCManager = WebRTCManager.get(); start(); //会议 回调 RoomClient.get().addRoomEventCallback(VideoConferenceActivity.class, roomEventCallback); RoomClient.get().addRoomEventCallback(PTZControlUtil.class, PTZControlUtil.INSTANCE); RoomClient.get().setOnLocalShareJoinListener(this); ServerManager.get().setPadEvent(padEvent); participantModels = getParticipant(); RoomManager.get().setRoomId(channelId); android.util.DisplayMetrics dm = getResources().getDisplayMetrics(); //屏幕高度 = 整个屏高 - top bar 高度 - bot bar 高度 initVideoControl(); //设置surfaceView 参数 surfaceParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); supportHdmiIn = SystemUtil.getSystemModel().equals("C9Z"); if (supportHdmiIn) { } else { videoController.setHDMIStatus(View.GONE); useCamEncoded = false; } // localVideoViewContainer.setInfoModels(participantModels, DynamicVideoLayout_.MODE_1); localVideoViewContainer.setInfoModels(participantModels); localVideoViewContainer.setOnItemVideoClickListener(this::showVideoItem); strOfKeySet = DeviceSettingManager.getInstance().getFromSp().getCurrentPreset(); Message msg = Message.obtain(); msg.what = 1; handler.sendMessage(msg); if (!RoomManager.get().isHost()) { localVideoViewContainer.setDefaultLayout(false); } EventBus.getDefault().register(this); } //根据当前participantModels 的顺序,获取connectionId并广播 private void firstLayoutParams() { if (RoomManager.get().isHost()) { ArrayList<String> connectIds = new ArrayList<>(); for (ParticipantInfoModel model : participantModels) { connectIds.add(model.getConnectionId()); } for (String s : connectIds) { Log.i("majorLayoutNotify", "firstLayoutParams......" + s); } if (mPresentation != null && mPresentation.isShowing() && currentShareModel != null && isShareHas == true) { connectIds.add(0, currentShareModel.getConnectionId()); } RoomClient.get().getBroadcastMajorLayout(localVideoViewContainer.getMode(), connectIds, "change"); } } /** * WebRtc * Web Real-Time Communication */ public void start() { webRTCManager.create(); webRTCManager.initWebRtc(channelId, userId, channelRole, useCamEncoded); if (channelRole.equals(ROLE_PUBLISHER) || channelRole.equals(ROLE_PUBLISHER_SUBSCRIBER)) { ParticipantInfoModel localParticipant = RoomClient.get().getLocalParticipant(); webRTCManager.createOffer(localParticipant); } webRTCManager.addViewCallback(VideoConferenceActivity.class, new IViewCallback() { @Override public void onSetLocalStream(MediaStream stream) { runOnUiThread(new Runnable() { @Override public void run() { Log.i("addNewView", "onSetLocalStream " + RoomClient.get().isHasHands() + " , " + channelRole + ", " + RoomClient.get().isHasHands()); // ServerManager.get().participantLocalJoin(RoomClient.get().getLocalParticipant()); //不是主持人, 就添加到小窗口 if (!channelRole.equals(ROLE_PUBLISHER_SUBSCRIBER)) { addOtherView(userId, stream, true, RoomClient.get().getLocalParticipant()); } else { //如果当前有人正在发言,就添加到小窗口 if (RoomClient.get().isHasHands()) { addOtherView(userId, stream, true, RoomClient.get().getLocalParticipant()); } else { addNewView(userId, stream, RoomClient.get().getLocalParticipant()); } } if (RoomManager.get().isHost()) { RoomClient.get().getRoomLayout(RoomManager.get().getRoomId()); } // if (_sinks.size() == participantModels.size()) { // L.d("do this ---addOtherView ---addOtherView ------layoutChange"); // if (!RoomManager.get().isHost()) { // layoutChange(RoomManager.get().getRoomLayoutModel()); // } else { // layoutChangeHost(); // } // } } }); } /** * * @param stream */ @Override public void onSetLocalScreenStream(MediaStream stream) { runOnUiThread(new Runnable() { @Override public void run() { } }); } /** * * @param stream */ @Override public void onSetLocalHDMIStream(MediaStream stream) { runOnUiThread(new Runnable() { @Override public void run() { Log.i("addNewlocalhdmiView", "onSetLocalScreenStream"); } }); } @Override public void onAddRemoteStream(MediaStream stream, ParticipantInfoModel participant) { runOnUiThread(new Runnable() { @Override public void run() { } }); } @Override public void onCloseRemoteStream(MediaStream stream, ParticipantInfoModel participant) { } @Override public void onMixStream(ParticipantInfoModel participant, boolean isHasShare) { } @Override public void publishParticipantInfo(ParticipantInfoModel participant) { } }); if (RoomManager.get().isHost()) { roomLayouts.clear(); } parseParticapantsInRooms(); } //添加到 主屏(大窗口) private void addNewView(String id, MediaStream stream, ParticipantInfoModel participant) { isLocalHas = true; if (TextUtils.isEmpty(screenId)) { screenId = id; } if (RoomManager.get().isHost()) { if (!queues.contains(id)) { queues.add(0, id); queueSend(); } } L.d("onAddRemoteStreamsNew >>>" + userId + " , " + participant.getUserId() + " , streamType : " + participant.getAppShowName()); // set render ProxyVideoSink sink = new ProxyVideoSink(); participantModels = getParticipant(); participant.setVideoSink(sink); localVideoViewContainer.notifyItemChanged(participant); if (stream.videoTracks.size() > 0) { stream.videoTracks.get(0).addSink(sink); } // localVideoViewContainer.notifyItemsChanged(); _sinks.put(id, sink); } //添加到小窗口 private void addOtherView(String id, MediaStream stream, boolean isLocal, ParticipantInfoModel participant) { if (RoomManager.get().isHost()) { if (!queues.contains(id)) { queues.add(id); queueSend(); } } L.d("onAddRemoteStreams >>>" + userId + " , " + participant.getUserId() + " , streamType : " + participant.getAppShowName() + "connectId" + participant.getConnectionId()); Log.i("addNewOtherView", "addNewOtherView" + participant.getConnectionId()); ProxyVideoSink sink = new ProxyVideoSink(); participantModels = getParticipant(); /** * 画中画基本功能 切换, 细节需要调试 */ if (participantModels != null) { for (ParticipantInfoModel participantInfoModel : participantModels) { if (participant.getConnectionId().equals(participantInfoModel.getConnectionId())) { participantInfoModel.setVideoSink(sink); break; } } } localVideoViewContainer.notifyItemChanged(participant); if (stream.videoTracks.size() > 0) { stream.videoTracks.get(0).addSink(sink); } // localVideoViewContainer.notifyItemsChanged(); Log.i("surfaceView", "addOther:" + id + ":" + participant.isVideoActive() + " , " + participant.getOnlineStatus()); _sinks.put(id, sink); } private void addOtherHDMIView(String id, MediaStream stream, boolean isLocal, ParticipantInfoModel participant) { isShareHas = true; Log.i("addNewShare", "addNewShare" + id); if (participant != null) { currentShareUser = participant.getAppShowName(); } prensatationId = id; if (RoomManager.get().isHost()) { queueSend(); } // set render ProxyVideoSink sink = new ProxyVideoSink(); /** * 画中画基本功能 切换, 细节需要调试 */ FrameLayout fl = new FrameLayout(this); LinearLayout.LayoutParams viewflp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1); fl.setLayoutParams(viewflp); viewflp.gravity = Gravity.CENTER; SurfaceViewRenderer surfaceView = webRTCManager.createRendererView(getApplication()); surfaceView.setTag(id); surfaceView.setLayoutParams(viewflp); //surfaceview 修改 自适配的时候得改回去 surfaceView.setLayoutParams(surfaceParams); sink.setTarget(surfaceView); participant.setVideoSink(sink); participantModels = getParticipant(); currentShareModel = participant; if (mPresentation != null && mPresentation.isShowing()) { surfaceView.setZOrderMediaOverlay(true); // presentationHDMIVideoView = surfaceView; mPresentation.getFrameLayout().addView(surfaceView, 0); mPresentation.getImageView().setVisibility(View.GONE); } else { localVideoViewContainer.notifyItemChanged(participant); } //更新当前正在共享的与会者 for (ParticipantInfoModel m : participantModels) { if (participant.getUserId().equals(m.getUserId()) && !SHARING.equals(m.getStreamType())) { m.setShareStatus("on"); localVideoViewContainer.notifyVideoStateChanged(m); } } //需要添加的验证数据 if (stream.videoTracks.size() > 0) { stream.videoTracks.get(0).addSink(sink); } if (mPresentation != null && mPresentation.isShowing()) { } else { _sinks.put(id, sink); } L.d("do this ----addOtherHdmi --11111---- : " + RoomManager.get().getRoomLayoutModel().getLayout().size() + " , participantModels.size():" + participantModels.size() + " , " + RoomManager.get().isHost()); } public void initHDMISurface() { localHDMIVideoView = webRTCManager.createRendererView(getApplicationContext()); // localHDMIVideoView = webRTCManager.createNoEGLRendererView(getApplication()); localHDMIVideoView.setLayoutParams(surfaceParams); // localHDMIVideoView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT); // localHDMIVideoView.setMirror(true); } public void initHDMISurface(SurfaceViewRenderer surfaceViewRenderer) { localHDMIVideoView = surfaceViewRenderer; // localHDMIVideoView = webRTCManager.createNoEGLRendererView(getApplication()); localHDMIVideoView.setLayoutParams(surfaceParams); // localHDMIVideoView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT); // localHDMIVideoView.setMirror(true); } public void initHDMIFrameLayout() { localParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1); locaHDMIFramenLayout = new FrameLayout(this); locaHDMIFramenLayout.setBackground(getDrawable(R.drawable.maininterface_list_video_frame)); locaHDMIFramenLayout.setPadding(1, 1, 1, 1); localParams.gravity = Gravity.CENTER; locaHDMIFramenLayout.setLayoutParams(localParams); locaHDMIFramenLayout.addView(localHDMIVideoView); } public int[] measureView(final View view) { ViewGroup.LayoutParams lp = view.getLayoutParams(); if (lp == null) { lp = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ); } int widthSpec = ViewGroup.getChildMeasureSpec(0, 0, lp.width); int lpHeight = lp.height; int heightSpec; if (lpHeight > 0) { heightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight, View.MeasureSpec.EXACTLY); } else { heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); } view.measure(widthSpec, heightSpec); return new int[]{view.getMeasuredWidth(), view.getMeasuredHeight()}; } /** * 解析: 房间内 已有 与会者 */ private void parseParticapantsInRooms() { ArrayList<ParticipantInfoModel> participants = RoomClient.get().getRemoteParticipants(); if (participants == null) { return; } for (ParticipantInfoModel tmpPart : participants) { if (!tmpPart.getConnectionId().equals(connectId)) { webRTCManager.onParticipantPublished(tmpPart); } } } /** * 离开 按钮 点击事件 * * @param view */ public void onHangup(View view) { finishAndRelease(); } private void finishAndRelease() { VideoControlManager.getInstance().finishAndReleaseDialog(this, () -> { doHangup(); leaveRoom(); finish(); RoomClient.get().setShowRollCall(false); RoomClient.get().setHasHands(false); lastBreakLineUserId = ""; }); } private void doHangup() { if (webRTCManager != null) { webRTCManager.leaveChannel(); if (!shareHDMI.getText().equals("共享屏幕")) { webRTCManager.stopShareHdmi(); RoomClient.get().leaveRoom(userId, channelId, STREAM_SHARING); } } webRTCManager.doDestroy(VideoConferenceActivity.class); localVideoViewContainer.removeAllViews(); _sinks.clear(); closePresentation(); RoomClient.get().setLocalHdmiParticipant(null); RoomClient.get().setLocalScreenParticipant(null); RoomClient.get().setLocalParticipant(null); RoomClient.get().getRemoteParticipant().clear(); RoomClient.get().removeRoomEventCallback(VideoConferenceActivity.class); RoomClient.get().setOnLocalShareJoinListener(null); } public void leaveRoom() { if (!channelRole.equals(ROLE_PUBLISHER_SUBSCRIBER)) { RoomClient.get().leaveRoom(userId, channelId, STREAM_MAJOR); } else { RoomClient.get().closeRoom(channelId); } } public void switchCamera(View view) { webRTCManager.switchCamera(); } public void roomSetting(View view) { boolean isHost = SPEditor.instance().getUserId().equals(RoomManager.get().getHostId()); meetSettingPopupWindow = new MeetSettingPopupWindow(this); meetSettingPopupWindow.showAsLeft(view); meetSettingPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { meetSettingPopupWindow = null; videoController.scheduleHide(); } }); CallUtil.asyncCall(400,()-> { videoController.reset(); }); } public void allScreen(View view) { isAllScreen = true; //SurfaceView 放大 SurfaceViewRenderer surfaceViewRenderer = WebRTCManager.get().createRendererView(getApplicationContext()); surfaceViewRenderer.setZOrderMediaOverlay(true); removeParent(surfaceViewRenderer); all_frameLayout.addView(surfaceViewRenderer, 0); } public void allScreen(String connectionId) { currentAllscreenId = connectionId; isAllScreen = true; //SurfaceView 放大 SurfaceViewRenderer surfaceViewRenderer = localVideoViewContainer.getSurfaceViewRender(currentAllscreenId); surfaceViewRenderer.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); surfaceViewRenderer.setZOrderMediaOverlay(true); all_frameLayout.addView(surfaceViewRenderer, 0); PTZControlUtil.INSTANCE.start(connectionId); } public void resetScreen(View view) { isAllScreen = false; SurfaceViewRenderer surfaceViewRenderer = null; if (all_frameLayout.getChildAt(0) instanceof SurfaceViewRenderer) { surfaceViewRenderer = (SurfaceViewRenderer) all_frameLayout.getChildAt(0); surfaceViewRenderer.setZOrderMediaOverlay(false); all_frameLayout.removeView(surfaceViewRenderer); localVideoViewContainer.resumeSurfaceViewRender(currentAllscreenId, surfaceViewRenderer); isAllScreen = false; currentAllscreenId = null; } PTZControlUtil.INSTANCE.release(); } /** * 参会人 * * @param view */ public void participant(View view) { showQueuePop(view); } public void showQueuePop(View view) { participantPopWindow = new ParticipantPopWindow(this, channelId, true); participantPopWindow.showAsDropUp(view); } //展示视频下方操作选项(由于位置会发生变化,每次需遍历) public void showVideoItem(View view, String id) { ArrayList<ParticipantInfoModel> participantInfoModels = RoomClient.get().getRemoteParticipants(); ParticipantInfoModel participantInfoModel = null; if (id.equals(RoomManager.get().getUserId())) { participantInfoModel = RoomClient.get().getLocalParticipant(); } else { for (ParticipantInfoModel participantInfoModel1 : participantInfoModels) { if (participantInfoModel1.getUserId().equals(id) || (participantInfoModel1.getUserId() + Constants.LOCAL_SCREEN).equals(id)) { participantInfoModel = participantInfoModel1; } } } if (participantInfoModel == null) { return; } videoItemPopWindow = new VideoItemPopWindow(this, participantInfoModel); videoItemPopWindow.initData(); videoItemPopWindow.showAsDropDown(view); } public void showVideoItem(ParticipantInfoModel item) { if (!RoomManager.get().isHost()) { return; } if (isAllScreen) { return; } if (item == null) { return; } String userId = item.getUserId(); ArrayList<ParticipantInfoModel> participantInfoModels = RoomClient.get().getRemoteParticipants(); ParticipantInfoModel participantInfoModel = null; if (userId.equals(RoomManager.get().getUserId())) { participantInfoModel = RoomClient.get().getLocalParticipant(); } else { for (ParticipantInfoModel participantInfoModel1 : participantInfoModels) { if (participantInfoModel1.getUserId().equals(userId) && (participantInfoModel1.getStreamType().equals(item.getStreamType()))) { participantInfoModel = participantInfoModel1; break; } } } if (participantInfoModel == null) { return; } VideoItemPopWindow videoItemPopWindow = new VideoItemPopWindow(this, participantInfoModel); videoItemPopWindow.initData(); videoItemPopWindow.setVideoItemPop(connectId -> { //如果是自己 , 本地云台控制,否则对面云台控制 isCurrentAllScreenSelf = RoomManager.get().getConnectionId().equals(connectId); if (isCurrentAllScreenSelf) { DeviceSettingManager.getInstance().startCameraControl(); } allScreen(connectId); }); int measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); videoItemPopWindow.getContentView().measure(measureSpec, measureSpec); int measuredWidth = videoItemPopWindow.getContentView().getMeasuredWidth(); videoItemPopWindow.showAtLocation(localVideoViewContainer, Gravity.NO_GRAVITY, item.getLayoutX() + (item.getLayoutWidth() - measuredWidth) / 2, item.getLayoutY()); videoController.getMenuManager().registerWindows(videoItemPopWindow); } public void removeParent(View view) { if (view != null) { ViewGroup parentViewGroup = (ViewGroup) view.getParent(); if (parentViewGroup != null) { parentViewGroup.removeView(view); } } } public ViewGroup getParent(View view) { if (view != null) { ViewGroup parentViewGroup = (ViewGroup) view.getParent(); return parentViewGroup; } return null; } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); mDisplayManager.unregisterDisplayListener(this); RoomClient.get().setLocalHdmiParticipant(null); RoomClient.get().setLocalScreenParticipant(null); RoomClient.get().setLocalParticipant(null); RoomClient.get().getRemoteParticipant().clear(); RoomClient.get().removeRoomEventCallback(VideoConferenceActivity.class); RoomClient.get().setOnLocalShareJoinListener(null); } @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void receiveSoundRecongnizedmsg(EventPublish eventPublish) { ParticipantInfoModel participant = eventPublish.getParticipantInfoModel(); MediaStream stream = eventPublish.getMediaStream(); EventBus.getDefault().removeStickyEvent(eventPublish); if (lastBreakLineUserId.equals(participant.getUserId())) { lastBreakLineUserId = ""; } L.d("onRemoteStreamAdded >>>" + "onAddRemoteStream" + " , " + participant.getConnectionId() + " , streamType : " + participant.getAppShowName()); L.d("onAddRemoteStreams >>>" + userId + " , " + participant.getUserId() + " , streamType : " + participant.getStreamType() + "connectId" + participant.getConnectionId()); if (userId.equals(participant.getUserId())) { if (participant.getStreamType().equals(MAJOR)) { getAllParticipants(channelId); // videoController.audioStatus(participant.isAudioActive()); videoController.videoStatus(participant.isVideoActive()); videoController.speakerStatus(true); RoomManager.get().setMediaStream(stream); inviteParticipantNow(); } return; } // 设置新入会者的音频状态(扬声器控制) if (stream.audioTracks.size() > 0) { stream.audioTracks.get(0).setEnabled(true); } if (!SHARING.equals(participant.getStreamType())) { videoController.updateJoinPersons(); } Log.i("addNewView", "RemoteStream ishands " + RoomClient.get().isHasHands() + " handsId " + RoomClient.get().getHandsId() + " ,userId " + participant.getUserId()); L.d("onAddRemoteStream: isHasHands " + RoomClient.get().isHasHands() + " , role " + participant.getRole() + " , isLocalHas:" + isLocalHas + ", isShareHas:" + isShareHas); //有人发言, 且进来的用户是举手用户 if (RoomClient.get().isHasHands() && participant.getUserId().equals(RoomClient.get().getHandsId()) && participant.getStreamType().equals(MAJOR)) { addNewView(participant.getUserId(), stream, participant); } else { L.d("onAddRemoteStream: isHasHands " + RoomClient.get().isHasHands() + " , role " + participant.getRole() + " , isLocalHas:" + isLocalHas + ", isShareHas:" + isShareHas); //无人发言且 进来的用户是主持人 if (!RoomClient.get().isHasHands() && participant.getRole().equals(ROLE_PUBLISHER_SUBSCRIBER)) { if (isLocalHas) { return; } addNewView(participant.getUserId(), stream, participant); } else { if (participant.getStreamType().equals(MAJOR)) { addOtherView(participant.getUserId(), stream, false, participant); } else { if (isShareHas) { //不能同时有两个SHARE return; } addOtherHDMIView(participant.getUserId() + Constants.LOCAL_SCREEN, stream, false, participant); } } } L.d("do this ----->>>>>>>>>>>>>" + participantModels.size() + " , " + _sinks.size()); L.d("do this ---addOtherView ---addOtherView ------layoutChange"); if (!RoomManager.get().isHost()) { layoutChange(RoomManager.get().getRoomLayoutModel()); } else { if (_sinks.size() == participantModels.size()) { layoutChangeHost(); } } if (_sinks.size() == participantModels.size()) { firstLayoutParams(); } } @Override public void onBackPressed() { // doHangup(); // stopShare(); // leaveRoom(); // finish(); if (isAllScreen) { resetScreen(all_frameLayout); } } @Override protected void onPause() { super.onPause(); if (mPresentation != null && mPresentation.isShowing()) { mPresentation.dismiss(); } } @Override protected void onResume() { super.onResume(); RoomClient.get().setCurrentActivity(this); registeNoFocusViewId(R.id.iv_see,R.id.fl_contair); // mFocusLayout = new FocusLayout(this); // bindListener();//绑定焦点变化事件 // addContentView(mFocusLayout, // new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, // ViewGroup.LayoutParams.MATCH_PARENT));//添加焦点层 // // mFocusLayout.addIngoreIds(R.id.iv_see); // mFocusLayout.addIngoreIds(R.id.more_menu); // mFocusLayout.addIngoreIds(R.id.remote_video_container2); // mFocusLayout.addIngoreIds(R.id.remote_top); // mFocusLayout.addIngoreIds(R.id.horizontal_scroll); // mFocusLayout.addIngoreIds(R.id.remote_video_container); // mFocusLayout.addIngoreIds(R.id.fl_contair); } @Override protected void onStop() { // doHangup(); super.onStop(); } /** * 是否 被 主持人 静音 * * @param status * @param type * @return */ private boolean getSlingStatus(String status, String type) { return status.equals(type); } public void removeView(String screenUid) { // FrameLayout frameLayout = remoteVideoViews.remove((screenUid)); // if (frameLayout == null) { // return; // } // removeParent(frameLayout); // remoteVideoViewSplite.removeView(frameLayout); // if (frameLayout.getChildAt(0) instanceof SurfaceViewRenderer) { // ((SurfaceViewRenderer) frameLayout.getChildAt(0)).release(); // } } //某userId 掉线,画面处理 public void setViewBreak(String screenUid) { if (screenUid.equals((screenId))) { isLocalHas = false; } if (participantModels != null) { for (ParticipantInfoModel participantInfoModel : participantModels) { if (participantInfoModel.getUserId().equals(screenUid) && !SHARING.equals(participantInfoModel.getStreamType())) { participantInfoModel.setOnlineStatus(Constract.offline); localVideoViewContainer.notifyVideoStateChanged(participantInfoModel); } } } } public void removeShareView(String screenUid) { if (mPresentation != null && mPresentation.isShowing()) { mPresentation.getFrameLayout().removeView(mPresentation.getFrameLayout().getChildAt(0)); mPresentation.getImageView().setVisibility(View.VISIBLE); } else { if (SHARING.equals(participantModels.get(0).getStreamType())) { localVideoViewContainer.stopShare(participantModels.get(0)); localVideoViewContainer.notifyItemRemoved(participantModels.get(0)); participantModels.remove(0); } // if (SHARING.equals(participantModels.get(0).getStreamType())) { // // } // remoteVideoViewSplite.removeView(remoteVideoViews.remove((screenUid))); } currentShareModel = null; if (localHDMIVideoView != null) { localHDMIVideoView.release(); localHDMIVideoView = null; } } /** * 获取所有与会的人 * * @param channelId -> roomId */ private void getAllParticipants(String channelId) { // clRtcAccess.getAllParticipants(channelId); RoomClient.get().getParticipants(channelId); } /** * 设置频道 音频 状态 * * @param roomId * @param sourceId * @param targetId * @param status */ private void setAudioStatus(String roomId, String sourceId, List<String> targetId, boolean status) { RoomClient.get().setAudioStatus(roomId, sourceId, targetId, status); } /** * 设置 频道 视频 状态 * * @param roomId * @param sourceId * @param targetId * @param status */ private void setVideoStatus(String roomId, String sourceId, List<String> targetId, boolean status) { RoomClient.get().setVideoStatus(roomId, sourceId, targetId, status); } /** * 举手 * * @param roomId * @param sourceId */ private void raiseHand(String roomId, String sourceId) { RoomClient.get().raiseHand(roomId, sourceId); } /** * 手放下 * * @param roomId * @param sourceId * @param targetId */ private void putDownHand(String roomId, String sourceId, String targetId) { RoomClient.get().putDownHand(roomId, sourceId, targetId); } /** * bot bar 锁定 * * @param sessionId * @param sourceId */ private void lockConference(String sessionId, String sourceId) { // clRtcAccess.lockConference(sessionId, sourceId, enable); RoomClient.get().lockSession(sessionId, sourceId); } /** * bot bar 锁定 * * @param sessionId * @param sourceId */ private void unlockConference(String sessionId, String sourceId) { // clRtcAccess.lockConference(sessionId, sourceId, enable); RoomClient.get().unlockSession(sessionId, sourceId); } /********************************平板会控相关************************************/ private PadEvent padEvent = new PadEvent() { @Override public void accessPadIn(PadModel padModel) { } @Override public void setAudio() { } @Override public void setVideo() { } @Override public void setSpeak() { } @Override public void leavePadRoom() { runOnUiThread(() -> { doHangup(); leaveRoom(); finish(); }); } @Override public void shareHDMI() { shareScreenHDMI(shareHDMI); } }; /********************************信令回调相关(包含会控)************************************/ private RoomEventCallback roomEventCallback = new RoomEventAdapter() { @Override public void onParticipantJoined(ParticipantInfoModel participant) { runOnUiThread(() -> { if (RoomManager.get().isHost()) { if (SHARING.equals(participant.getStreamType()) || queues.contains(participant.getUserId())) { return; } queues.add(participant.getUserId()); queueSend(); } }); } @Override public void closeRoomNotify() { runOnUiThread(new Runnable() { @Override public void run() { Log.i("GroupActivity......", "closeRoomNotify"); if (VideoConferenceActivity.this.isFinishing()) { return; } doHangup(); RoomClient.get().setHasHands(false); finish(); } }); } @Override public void onParticipantEvicted(ParticipantInfoModel participant, String connectId) { runOnUiThread(new Runnable() { @Override public void run() { if (participant == null) { return; } if (VideoConferenceActivity.this.isFinishing()) { return; } String userId = participant.getUserId(); if (connectId.equals(RoomManager.get().getConnectionId())) { doHangup(); RoomClient.get().setHasHands(false); finish(); } else { if (participant == null) { return; } if (!(screenId).equals(participant.getUserId())) { leftToChangeView(participant.getUserId()); } if (participant.getStreamType().equals(STREAM_SHARING)) { onStopShareScreen(participant.getUserId()); isShareHas = false; currentShareUser = ""; userId = userId + LOCAL_SCREEN; } else { removeView(userId); } if (RoomManager.get().isHost()) { if (queues.contains(userId)) { queues.remove(userId); queueSend(); } } leftSink(userId); webRTCManager.removePc(participant); videoController.updateJoinPersons(); } } }); } @Override public void onParticipantLeft(ParticipantInfoModel participant) { runOnUiThread(new Runnable() { @Override public void run() { if (participant == null) { return; } if (VideoConferenceActivity.this.isFinishing()) { return; } String userId = participant.getUserId(); if (!STREAM_SHARING.equals(participant.getStreamType())) { participantModels.remove(participant); leftToChangeView(userId); } if (STREAM_SHARING.equals(participant.getStreamType())) { onStopShareScreen(userId); isShareHas = false; currentShareUser = ""; userId = userId + LOCAL_SCREEN; } else { videoController.setCurrentHandUpNum(RoomClient.get().getCurrentLeftHandsUp()); videoController.showDotNumber(String.valueOf(RoomClient.get().getCurrentLeftHandsUp())); RoomClient.get().setShowRollCall(false); removeView(userId); } if (RoomManager.get().isHost()) { if (queues.contains(userId)) { queues.remove(userId); queueSend(); } } leftSink(userId); webRTCManager.removePc(participant); videoController.updateJoinPersons(); localVideoViewContainer.notifyItemRemoved(participant); firstLayoutParams(); } }); } @Override public void reconnectPartStopPublishSharing(ParticipantInfoModel participant) { runOnUiThread(new Runnable() { @Override public void run() { if (participant == null) { return; } String userId = participant.getUserId(); if (STREAM_SHARING.equals(participant.getStreamType())) { onStopShareScreen(userId); isShareHas = false; currentShareUser = ""; userId = userId + LOCAL_SCREEN; } else { removeView(participant.getUserId()); } if (RoomManager.get().isHost()) { if (queues.contains(userId)) { queues.remove(userId); queueSend(); } } leftSink(userId); webRTCManager.removePc(participant); //更新文字 videoController.updateJoinPersons(); if (participantModels.size() > 0 && SHARING.equals(participantModels.get(0).getStreamType())) { participantModels.remove(0); } currentShareModel = null; firstLayoutParams(); } }); } @Override public void onRaiseHandsSended() { L.d("会控 VideoConfAct onRaiseHandsSended()"); } @Override public void onPutDownHandsSended() { L.d("会控 VideoConfAct onPutDownHandsSended()"); } @Override public void onAudioStatusSwitchSuccess() { L.d("会控 VideoConfAct onAudioStatusSwitchSuccess()"); } @Override public void onVideoStatusSwitchSuccess() { L.d("会控 VideoConfAct onVideoStatusSwitchSuccess()"); } @Override public void onReceiveAudioStatusChange(AudioStstusResp audioStstusResp) { L.d("会控 VideoConfAct onReceiveAudioStatusChange()"); runOnUiThread(new Runnable() { @Override public void run() { onSetAudioStatus(audioStstusResp); } }); } @Override public void onReceiveVideoStatusChange(VideoStatusResp videoStatusResp) { L.d("会控 VideoConfAct onReceiveVideoStatusChange()"); runOnUiThread(new Runnable() { @Override public void run() { onSetVideoStatus(videoStatusResp); } }); } /** * 设置共享权限 * * @param model */ @Override public void onSharePower(SlingModel model) { L.d("会控 --->>> 共享权限设置"); runOnUiThread(() -> { // onSetShareStatus(model); }); } @Override public void onReceiveSpeakerStatusChange(SlingModel slingModel) { L.d("会控 VideoConfAct onReceiveSpeakerStatusChange()"); runOnUiThread(new Runnable() { @Override public void run() { onSetSpeakerStatus(slingModel); } }); } @Override public void onReceiveHandsUp(HandsStatusResp handsStatusResp) { L.d("会控 VideoConfAct onReceiveHandsUp()"); runOnUiThread(new Runnable() { @Override public void run() { if (SPEditor.instance().getUserId().equals(RoomManager.get().getHostId())) { //主持人端 String showName = !TextUtils.isEmpty(handsStatusResp.getUsername()) ? handsStatusResp.getUsername() : handsStatusResp.getAppShowName(); UCToast.showCustomToast(VideoConferenceActivity.this, showName + "申请发言", Gravity.BOTTOM, 200, 120); onRaiseHand(handsStatusResp); } } }); } @Override public void onReceiveHandsDown(HandsStatusResp handsStatusResp) { L.d("会控 VideoConfAct onReceiveHandsDown()"); runOnUiThread(new Runnable() { @Override public void run() { onPutDownHand(handsStatusResp); } }); } @Override public void onGetParticipantsResult(ArrayList<ParticipantInfoModel> participantsList) { runOnUiThread(() -> { onGetParticipants(participantsList); }); } @Override public void onLeaveRoomSuccess(String role) { //辅流 离开房间回调没有 sessionId App.post(() -> { if (role.equals(SHARING)) { onStopShareScreen(userId); } }); } @Override public void onTransferModerator(SlingModel model) { runOnUiThread(new Runnable() { @Override public void run() { // onLockConference(true, model); } }); } @Override public void onLockSession(SlingModel slingModel) { runOnUiThread(new Runnable() { @Override public void run() { onLockConference(true, slingModel); } }); } @Override public void unLockSession(SlingModel slingModel) { runOnUiThread(new Runnable() { @Override public void run() { onLockConference(false, slingModel); } }); } @Override public void onWebSocketFailMessage(WsError wsErrorr, String method) { if (RoomClient.get().getCurrentActivity() instanceof VideoConferenceActivity) { runOnUiThread(new Runnable() { @Override public void run() { if (wsErrorr.getCode() == WsErrorCode.ERROR_ROOM_CAPACITY_LIMITED) { //邀请入会 人数已达上限 UCToast.show(App.getInstance().getApplicationContext(), getString(R.string.str_error_room_capacity_limit)); } else if (wsErrorr.getCode() == WsErrorCode.ERROR_CONFERENCE_NOT_EXIST) { //会议已经关闭 UIUtils.toastMessage("会议已经关闭"); } else if (wsErrorr.getCode() == WsErrorCode.ERROR_ALREADY_ONLINE) { RoomClient.get().setAccessInSuccess(false); } else { UIUtils.toastMessage(wsErrorr.getMessage()); } } }); } } /** * 获取会议预设信息 * * @param resp */ @Override public void onGetPresetInfo(PresetInfoResp resp) { runOnUiThread(() -> { L.d("获取会议预设信息 " + resp.getSubject()); }); } @Override public void rollcall(SlingModel slingModel) { runOnUiThread(() -> { OnRollCall(slingModel); }); } /** * 替换发言 * * @param slingModel */ @Override public void replaceRollCall(ReplaceRollcallModel slingModel) { runOnUiThread(() -> { // replaceRollcall(slingModel); }); } @Override public void endRollcall(SlingModel slingModel) { runOnUiThread(() -> { EndRollCall(slingModel); }); } @Override public void getOrgList(OrgList orgList) { runOnUiThread(new Runnable() { @Override public void run() { } }); } @Override public void getUserDeviceList(UserDeviceList userDeviceList) { runOnUiThread(new Runnable() { @Override public void run() { } }); } @Override public void getRoomTimeCountDown(RoomTimeModel model) { runOnUiThread(new Runnable() { @Override public void run() { if (model.getRemainTime() == 1) { videoController.showTimeDownPopup(1); if (RoomManager.get().getHostId().equals(SPEditor.instance().getUserId())) { show1mDialog(); } } else if (model.getRemainTime() == 10) { videoController.showTimeDownPopup(10); } } }); } @Override public void onRoomDelay() { runOnUiThread(() -> { }); } /** * 广播参会者掉线 * * @param model */ @Override public void userBreakLine(ParticipantInfoModel model) { runOnUiThread(() -> { if (model == null) { return; } String userId = model.getUserId(); if (!lastBreakLineUserId.equals(userId)) { leftToChangeView(userId); setViewBreak(userId); leftSink(userId); lastBreakLineUserId = userId; } }); } /** * 被邀请人 拒绝 * * @param model */ @Override public void refuseInvite(SlingModel model) { runOnUiThread(() -> { if (SPEditor.instance().getUserId().equals(RoomManager.get().getHostId())) { UCToast.show(VideoConferenceActivity.this, "用户拒绝入会"); } }); } //发送成功 @Override public void onInviteJoinCallback() { runOnUiThread(() -> { }); } @Override public void majorLayoutNotify(RoomLayoutModel roomLayoutModel) { runOnUiThread(() -> { L.d("do this ------majorLayoutNotify>>>>>222222"); if (RoomManager.get().isHost()) { RoomManager.get().setRoomLayoutModel(roomLayoutModel); L.d("do this -------------------RoomManager.get() " + RoomManager.get().getRoomLayoutModel().getLayout()); return; } if (roomLayoutModel.getLayout().size() < participantModels.size()) { return; } layoutChange(roomLayoutModel); }); } @Override public void getSubDevOrUser(PartDeviceModel orgList) { runOnUiThread(() -> { if (RoomClient.get().getCurrentActivity() instanceof VideoConferenceActivity) { videoController.notifyDeviceData(orgList.getDeviceList()); } }); } @Override public void getDepartmentTree(CompanyModel companyModel) { runOnUiThread(() -> { if (RoomClient.get().getCurrentActivity() instanceof VideoConferenceActivity) { videoController.notifyOrgTreeList(companyModel); } }); } @Override public void getGroupList(GroupListInfoModel groupListInfoModel) { runOnUiThread(()->{ if (RoomClient.get().getCurrentActivity() instanceof VideoConferenceActivity) { videoController.setSubGroupItem(groupListInfoModel); } }); } @Override public void getGroupInfo(GroupInfoModel groupInfoModel) { runOnUiThread(()->{ if (RoomClient.get().getCurrentActivity() instanceof VideoConferenceActivity) { videoController.notifyGroupDeviceData(groupInfoModel.getGroupInfo()); } }); } @Override public void getRoomLayoutCallback(RoomLayoutModel model) { runOnUiThread(() -> { if (RoomManager.get().getRoomLayoutModel() != null) { if (RoomManager.get().isHost()) { if (_sinks.size() == participantModels.size()) { layoutChangeHost(); } } } }); } @Override public void sharingControlNotify(SlingModel slingModel) { if (slingModel != null) { App.post(() -> { if (userId.equals(slingModel.targetId) && slingModel.sourceId.equals(slingModel.targetId)) { if (videoController != null) { videoController.shareHDMI(); } } else { onSetShareStatus(slingModel); } }); } } }; //主持人同步布局(断线重连时) private void layoutChangeHost() { roomLayoutModel = RoomManager.get().getRoomLayoutModel(); if (roomLayoutModel.getLayout() == null || roomLayoutModel.getLayout().size() == 0) { return; } if (roomLayoutModel.getModeratorIndex() != -1) { //如果是断线重连 if (RoomManager.get().isHostFirst() && !RoomClient.get().isHasHands()) { //当前房间没有共享或发言的 人 if (roomLayoutModel.getLayout().contains(RoomManager.get().getConnectionId())) { roomLayoutModel.getLayout().remove(RoomManager.get().getConnectionId()); } roomLayoutModel.getLayout().add(0, RoomManager.get().getConnectionId()); roomLayoutModel.setMode(roomLayoutModel.getMode() + 1); RoomManager.get().setRoomLayoutModel(roomLayoutModel); acceptRoomLayoutMode(roomLayoutModel); L.d("do this ------------------layoutChangeHost0000--------------" + RoomManager.get().getConnectionId() + " ----" + RoomManager.get().getRoomLayoutModel().getLayout() + " ----- " + roomLayoutModel.getLayout()); return; } roomLayoutModel.setMode(participantModels.size()); if (roomLayoutModel.getModeratorIndex() >= participantModels.size()) { roomLayoutModel.setModeratorIndex(participantModels.size() - 1); } if (!roomLayoutModel.getLayout().contains(RoomManager.get().getConnectionId())) { roomLayoutModel.getLayout().add(roomLayoutModel.getModeratorIndex(), RoomManager.get().getConnectionId()); } RoomManager.get().setRoomLayoutModel(roomLayoutModel); } else { return; } L.d("do this ------------------layoutChangeHost--------------" + RoomManager.get().getRoomLayoutModel().getLayout()); acceptRoomLayoutMode(roomLayoutModel); } //普通与会者更改同步布局 private void layoutChange(RoomLayoutModel roomLayoutModel) { if (roomLayoutModel != null) { if (roomLayoutModel.getLayout() == null || roomLayoutModel.getLayout().size() == 0) { return; } Log.i("roomLayoutModel","roomLayoutModel..."+roomLayoutModel.getLayout().size()); if (roomLayoutModel.getLayout().size() == 1 && roomLayoutModel.getMode() == 0 && replace.equals(roomLayoutModel.getType())) { if (roomLayoutModel.getLayout().get(0).equals(userId)) { webRTCManager.changeCaptureFormat(true); } else { webRTCManager.changeCaptureFormat(false); } if (isAllScreen) { //先结束全屏再 resetScreen(all_frameLayout); } return; } queues.clear(); if (roomLayoutModel.getLayout() != null) { queues.addAll(roomLayoutModel.getLayout()); } if (isAllScreen) { //先结束全屏再 resetScreen(all_frameLayout); } acceptRoomLayoutMode(roomLayoutModel); } } //同步布局 private void acceptRoomLayoutMode(RoomLayoutModel roomLayoutModel) { swapParticipantModels(roomLayoutModel); localVideoViewContainer.acceptRoomLayoutMode(roomLayoutModel); } //主持人 接收到与会者信息后 按布局layout中的顺序 同步与会者信息 private void swapModels(RoomLayoutModel roomLayoutModel) { ParticipantInfoModel shareModel = null; if (!RoomManager.get().isHost()) { return; } if (roomLayoutModel == null) { return; } if (roomLayoutModel.getLayout() == null || roomLayoutModel.getLayout().size() == 0) { return; } if (mPresentation != null && mPresentation.isShowing()) { if (RoomClient.get().getRemoteParticipant().get(roomLayoutModel.getLayout().get(0)) != null) { if (roomLayoutModel.getLayout().size() > 0 && SHARING.equals(RoomClient.get().getRemoteParticipant().get(roomLayoutModel.getLayout().get(0)).getStreamType())) { roomLayoutModel.getLayout().remove(0); } } } //如果第0个是分享,先取出,再放回 if (participantModels.size() > 0 && SHARING.equals(participantModels.get(0).getStreamType())) { if (!roomLayoutModel.getLayout().contains(participantModels.get(0).getConnectionId())) { shareModel = participantModels.get(0); participantModels.remove(0); } } //todo 12301652 //按照roomLayoutModel中的顺序,排列participantModels List<String> connections = roomLayoutModel.getLayout(); L.d("do this ----------------swapModels "+roomLayoutModel.getLayout()); for (int i = 0; i < connections.size(); i++) { for (int j = 0; j < participantModels.size(); j++) { if (connections.get(i).equals(participantModels.get(j).getConnectionId())) { if (i != j) { if (i < participantModels.size()) { Collections.swap(participantModels, i, j); } } } } } for (ParticipantInfoModel m : participantModels) { L.d("do this ---------------swap ----- "+m.getAppShowName()+" , "+m.getConnectionId()); } if (shareModel != null) { participantModels.add(0, shareModel); shareModel = null; } } // 按照RoomLayoutModel中的顺序 交换 participantModels private void swapParticipantModels(RoomLayoutModel roomLayoutModel) { if (roomLayoutModel == null) { return; } if (roomLayoutModel.getLayout() == null || roomLayoutModel.getLayout().size() == 0) { return; } if (mPresentation != null && mPresentation.isShowing()) { if (RoomClient.get().getRemoteParticipant().get(roomLayoutModel.getLayout().get(0)) != null) { if (roomLayoutModel.getLayout().size() > 0 && SHARING.equals(RoomClient.get().getRemoteParticipant().get(roomLayoutModel.getLayout().get(0)).getStreamType())) { roomLayoutModel.getLayout().remove(0); } } } //todo 12301652 //按照roomLayoutModel中的顺序,排列participantModels List<String> connections = roomLayoutModel.getLayout(); if (connections.size() < participantModels.size()) { return; } L.d("do this --------------------------------------swapParticipantModels"); for (int i = 0; i < connections.size(); i++) { for (int j = 0; j < participantModels.size(); j++) { if (connections.get(i).equals(participantModels.get(j).getConnectionId())) { if (i != j) { if (i < participantModels.size()) { Collections.swap(participantModels, i, j); } } } } } } //掉线,被踢出,离开统一处理逻辑 public void leftToChangeView(String userId) { if (TextUtils.isEmpty(userId)) { return; } L.d("do this ---leftToChangeView>>>" + userId + ", " + (screenId) + " , hostId : " + RoomManager.get().getHostId()); if (!userId.equals(RoomManager.get().getHostId())) { L.d("do this ---leftToChangeView>>>" + userId + ", " + (screenId)); if (userId.equals((screenId))) { // newChangeFrame((RoomManager.get().getHostId()), screenId); SlingModel slingModel = new SlingModel(); slingModel.sourceId = RoomManager.get().getHostId(); slingModel.targetId = userId; EndRollCall(slingModel); } } } //掉线,被踢出,离开统一处理逻辑 移除流 public void leftSink(String userId) { ProxyVideoSink sink = _sinks.get(userId); if (sink != null) { sink.setTarget(null); } _sinks.remove(userId); } /** * 收到 与会者 信息 */ public void onGetParticipants(ArrayList<ParticipantInfoModel> models) { Log.i(logTag, "join...onGetParticipants:"); //json 处理,所有与会者 if (participantInfoModelsNoShare != null) { participantInfoModelsNoShare.clear(); } if (tempParticpantModels != null) { tempParticpantModels.clear(); } if (models != null) { RoomManager.get().setParticipants(models); } L.d("do this --------------------onGetParticipants"); participantModels = getParticipant(); participantInfoModelsNoShare = RoomManager.get().getFilterParticipants(participantModels); tempParticpantModels.addAll(participantInfoModelsNoShare); videoController.refreshParticipant(participantInfoModelsNoShare); videoController.refreshRollCallPop(); // swapParticipantModels(RoomManager.get().getRoomLayoutModel()); if (meetSettingPopupWindow != null) { int myIndex = -1; for (int i = 0; i < tempParticpantModels.size(); i++) { if (SPEditor.instance().getUserId().equals(tempParticpantModels.get(i).getUserId())) { myIndex = i; } } if (myIndex != -1) { tempParticpantModels.remove(myIndex); } meetSettingPopupWindow.showNextPopup(tempParticpantModels); } } /** * 语音 状态 变更 */ public void onSetAudioStatus(AudioStstusResp audioStatus) { String sourceId = audioStatus.getSourceId(); boolean status = getSlingStatus(audioStatus.getStatus(), CLRtcSinaling.VALUE_STATUS_ON); String[] targetIds = audioStatus.getTargetIds(); //web 会控 targetIds 为空,默认全体操作 if (targetIds == null || targetIds.length == 0) { if (!RoomManager.get().isHost()) { if (status == RoomClient.get().getRemoteParticipant().get(connectId).isAudioActive()) { L.d("do this ----->>>" + RoomClient.get().getRemoteParticipant().get(connectId).isAudioActive() + " , " + status); return; } UIUtils.toastMessage(status ? "主持人打开了您的麦克风" : "主持人关闭了您的麦克风"); RoomManager.get().setHostByClose(!status); videoController.audioStatus(status); } for (ParticipantInfoModel participantModel : participantModels) { if (sourceId.equals(participantModel.getUserId())) { continue; } if (!SHARING.equals(participantModel.getStreamType())) { participantModel.setAudioActive(status); } } // TODO: 2019/12/19 // boundShadowLayout.setData(RoomClient.get().getLayoutData()); return; } for (String targetId : targetIds) { L.d("onSetAudioStatus " + audioStatus.toString() + RoomManager.get().getUserId()); /** * pop打开更新popupwindow状态 */ if (participantPopWindow != null && participantPopWindow.isShowing()) { // participantPopWindow.setAudioStatus(targetId, status); //改变与会者状态 } /** * 底部控件(自己的状态更新) */ if (RoomManager.get().isAllMute(targetId) || userId.equals(targetId)) { videoController.audioStatus(status); if (!sourceId.equals(targetId)) { if (status == RoomClient.get().getRemoteParticipant().get(connectId).isAudioActive()) { L.d("do this ----->>>" + RoomClient.get().getRemoteParticipant().get(connectId).isAudioActive() + " , " + status); return; } UIUtils.toastMessage(status ? "主持人打开了您的麦克风" : "主持人关闭了您的麦克风"); } } /** * 修改加入房间 */ for (ParticipantInfoModel participantModel : participantModels) { if ((TextUtils.isEmpty(targetId) || participantModel.getUserId().equals(targetId) && !SHARING.equals(participantModel.getStreamType()))) { participantModel.setAudioActive(status); localVideoViewContainer.notifyVideoStateChanged(participantModel); } } } } /** * 视频 状态 变更 */ public void onSetVideoStatus(VideoStatusResp videoStatus) { String[] targetIds = videoStatus.getTargetIds(); if (targetIds == null) { return; } for (String targetId : targetIds) { boolean status = getSlingStatus(videoStatus.getStatus(), CLRtcSinaling.VALUE_STATUS_ON); L.d("onSetAudioStatusV2: " + videoStatus.toString()); if (userId.equals(targetId)) { videoController.videoStatus(status); } for (ParticipantInfoModel participantModel : participantModels) { if ((TextUtils.isEmpty(targetId) || participantModel.getUserId().equals(targetId) && !SHARING.equals(participantModel.getStreamType()))) { participantModel.setVideoActive(status); localVideoViewContainer.notifyVideoStateChanged(participantModel); } } } } /** * 共享状态变更 */ public void onSetShareStatus(SlingModel model) { // String[] targetIds = model.getTargetIds(); // if (targetIds == null) { // return; // } String targetId = model.getTargetId(); if (TextUtils.isEmpty(targetId)) { return; } // for (String targetId : targetIds) { boolean status = getSlingStatus(model.getStatus(), CLRtcSinaling.VALUE_STATUS_ON); L.d("onSetShareStatusV2: " + model.toString()); if (userId.equals(targetId)) { stopShareScreen2Other(); // enableShare = status; } // for (Map.Entry<String, FrameLayout> entry : remoteVideoViews.entrySet()) { // if (entry.getKey().equals((targetId))) { // if (status) { // entry.getValue().getChildAt(0).setVisibility(View.VISIBLE); // if (entry.getValue().getChildCount() > 2) { // entry.getValue().getChildAt(2).setVisibility(View.INVISIBLE); // } // } else { // entry.getValue().getChildAt(0).setVisibility(View.INVISIBLE); // if (entry.getValue().getChildCount() > 2) { // entry.getValue().getChildAt(2).setVisibility(View.VISIBLE); // } // } // } // } for (ParticipantInfoModel participantModel : participantModels) { if ((TextUtils.isEmpty(targetId) || participantModel.getUserId().equals(targetId)) && SHARING.equals(participantModel.getStreamType())) { participantModel.setShareStatus("off"); } } // } } private void stopShareScreen2Other() { isShareIng = false; isShareHas = false; onStopShareScreen(userId); webRTCManager.stopShareHdmi(); shareHDMI.setText("共享屏幕"); RoomClient.get().leaveRoom(userId, channelId, STREAM_SHARING); } /** * @param videoStatus */ public void onSetSpeakerStatus(SlingModel videoStatus) { String targetId = videoStatus.targetId; boolean status = getSlingStatus(videoStatus.status, CLRtcSinaling.VALUE_STATUS_ON); L.d("onSetAudioStatusV2: " + videoStatus.toString()); if (userId.equals(targetId)) { videoController.speakerStatus(status); // speakerStatus(status); } for (ParticipantInfoModel participantModel : participantModels) { if ((TextUtils.isEmpty(targetId) || participantModel.getUserId().equals(targetId) && !SHARING.equals(participantModel.getStreamType()))) { participantModel.setSpeakerActive(status); localVideoViewContainer.notifyVideoStateChanged(participantModel); } } } /** * @param videoStatus */ public void OnRollCall(SlingModel videoStatus) { ParticipantInfoModel infoModel = null; int index = -1; videoController.setCurrentSpeakNum(1); RoomClient.get().setHasHands(true); String targetId = videoStatus.targetId; String sourceId = videoStatus.sourceId; currentSpeakUserId = targetId; boolean status = getSlingStatus(videoStatus.status, CLRtcSinaling.VALUE_STATUS_ON); L.d("onSetAudioStatusV2:OnRollCall " + videoStatus.toString()); if (targetId.equals(userId)) { webRTCManager.changeCaptureFormat(true); } else if (RoomManager.get().getHostId().equals(userId)) { webRTCManager.changeCaptureFormat(false); } if (isAllScreen) { //先结束全屏再 resetScreen(all_frameLayout); } if (targetId.equals(userId)) { videoController.rollCallByMe(); } //获取targetID 对应的model,下标 for (int i = 0; i < participantModels.size(); i++) { L.d("do this ------rollcall ---- " + participantModels.get(i).getAppShowName()); if (targetId.equals(participantModels.get(i).getUserId()) && !SHARING.equals(participantModels.get(i).getStreamType())) { participantModels.get(i).setHandStatus("speaker"); infoModel = participantModels.get(i); index = i; } } videoController.showDotNumber(videoStatus.getRaiseHandNum()); // if ((targetId).equals(screenId)) { // return; // } if (RoomManager.get().isHost()) { swapQueue(targetId, (screenId)); } /** * 画中画基本功能 切换, 细节需要调试 */ //如果开启辅流,则当点名发言时,与第一位交换,否则与主窗口交换 if (RoomManager.get().isHost()) { if (isShareHas || isShareIng) { if (participantModels.size() > 1) { //双屏 if (mPresentation != null && mPresentation.isShowing()) { if (infoModel != null && index != -1) { Collections.swap(participantModels, 0, index); localVideoViewContainer.swap2Main(infoModel); } } else { ParticipantInfoModel firstModel = participantModels.get(1); L.d("do this ---rollcall >>>>" + participantModels.size()); L.d("do this --->>>>> >" + infoModel.getUserId() + " , " + firstModel.getUserId() + ", first model StreamType:" + firstModel.getStreamType()); if (!SHARING.equals(firstModel.getStreamType()) && index != -1) { Collections.swap(participantModels, 1, index); localVideoViewContainer.swap(firstModel, infoModel); } } } } else { if (infoModel != null && index != -1) { L.d("do this -----rollcall -------------------------" + index); Collections.swap(participantModels, 0, index); localVideoViewContainer.swap2Main(infoModel); } } firstLayoutParams(); } localVideoViewContainer.notifyVideoStateChanged(infoModel); } /** * 交换 */ private void swapQueue(String targetId, String sourceId) { for (String s : queues) { Log.i("swapQueue", "swapQueue...." + s); } //定义第三方变量 int index1 = 0; int index2 = 0; for (int i = 0; i < queues.size(); i++) { if (sourceId.equals(queues.get(i))) { index1 = i; continue; } if (targetId.equals(queues.get(i))) { index2 = i; continue; } } Collections.swap(queues, index1, index2); for (String s : queues) { Log.i("swapQueue", "swapQueue...." + s); } } public void replaceRollcall(ReplaceRollcallModel replaceRollcallModel) { String endUserId = replaceRollcallModel.getEndTargetId(); //被替换者 String startUserId = replaceRollcallModel.getStartTargetId(); //替换人员 if (isAllScreen) { //先结束全屏再 resetScreen(all_frameLayout); } if (endUserId.equals(userId)) { webRTCManager.changeCaptureFormat(false); } else if (RoomManager.get().getHostId().equals(userId)) { webRTCManager.changeCaptureFormat(true); } if (startUserId.equals(userId)) { webRTCManager.changeCaptureFormat(true); } else if (RoomManager.get().getHostId().equals(userId)) { webRTCManager.changeCaptureFormat(false); } if ((startUserId).equals(screenId) || (endUserId).equals(screenId)) { return; } if (endUserId.equals(userId)) { // raise_hand.setCompoundDrawablesWithIntrinsicBounds(null, // getResources().getDrawable(R.drawable.maininterface_menu_icon_speak, null), null, null); // putDownHand(RoomClient.get().getRoomId(), // SPEditor.instance().getUserId(), // SPEditor.instance().getUserId()); // raise_hand.setText("申请发言"); } if (startUserId.equals(userId)) { videoController.rollCallByMe(); } if (!TextUtils.isEmpty(replaceRollcallModel.raiseHandNum)) { videoController.setCurrentHandUpNum(Integer.parseInt(replaceRollcallModel.raiseHandNum)); videoController.showDotNumber(replaceRollcallModel.raiseHandNum); } } public void EndRollCall(SlingModel videoStatus) { ParticipantInfoModel infoModel = null; ParticipantInfoModel hostModel = null; int index = 0; int hostIndex = 0; videoController.setCurrentSpeakNum(0); RoomClient.get().setShowRollCall(false); RoomClient.get().setHasHands(false); String targetId = videoStatus.targetId; String sourceId = TextUtils.isEmpty(videoStatus.sourceId) ? RoomManager.get().getHostId() : videoStatus.sourceId; currentSpeakUserId = ""; //找到当前正在发言的与会者 for (int i = 0; i < participantModels.size(); i++) { if (RoomManager.get().getHostId().equals(participantModels.get(i).getUserId()) && !SHARING.equals(participantModels.get(i).getStreamType())) { hostModel = participantModels.get(i); hostIndex = i; } if (targetId.equals(participantModels.get(i).getUserId()) && !SHARING.equals(participantModels.get(i).getStreamType())) { participantModels.get(i).setHandStatus("down"); infoModel = participantModels.get(i); index = i; } } boolean status = getSlingStatus(videoStatus.status, CLRtcSinaling.VALUE_STATUS_ON); L.d("onSetAudioStatusV2: " + videoStatus.toString()); if (isAllScreen) { //先结束全屏再 resetScreen(all_frameLayout); } if (targetId.equals(userId)) { webRTCManager.changeCaptureFormat(false); } else if (RoomManager.get().getHostId().equals(userId)) { webRTCManager.changeCaptureFormat(true); } // if ((sourceId).equals(screenId)) { // return; // } if (targetId.equals(userId)) { videoController.endCallByMe(); } if (!TextUtils.isEmpty(videoStatus.raiseHandNum)) { videoController.setCurrentHandUpNum(Integer.parseInt(videoStatus.raiseHandNum)); videoController.showDotNumber(videoStatus.raiseHandNum); } if (RoomManager.get().isHost()) { swapQueue(sourceId, (screenId)); } L.d("do this -------EndRollCall>>> " + hostIndex + " , " + index); if (RoomManager.get().isHost()) { if (hostModel != null && infoModel != null) { Collections.swap(participantModels, hostIndex, index); localVideoViewContainer.swap(hostModel, infoModel); } firstLayoutParams(); } if (infoModel != null) { localVideoViewContainer.notifyVideoStateChanged(infoModel); } } /** * 发起 举手 后 回调 */ public void onRaiseHand(HandsStatusResp handsStatus) { L.d("onRaiseHandV2: " + handsStatus.toString()); videoController.setCurrentHandUpNum(Integer.parseInt(handsStatus.getRaiseHandNum())); videoController.showDotNumber(handsStatus.getRaiseHandNum()); } /** * 手放下 回调 */ public void onPutDownHand(HandsStatusResp videoStatus) { videoController.setCurrentHandUpNum(Integer.parseInt(videoStatus.getRaiseHandNum())); RoomClient.get().setShowRollCall(false); if (!TextUtils.isEmpty(videoStatus.getRaiseHandNum())) { videoController.showDotNumber(videoStatus.getRaiseHandNum()); } if (!userId.equals(videoStatus.getTargetId())) { return; } videoController.endCallByMe(); String targetId = videoStatus.getTargetId(); String sourceId = videoStatus.getSourceId(); L.d("onSetAudioStatusV2: " + videoStatus.toString()); if (sourceId.equals(targetId)) { return; } /* A更换B*/ // newChangeFrame(sourceId, targetId); } /** * 会议锁定 回调 * * @param slingModel */ public void onLockConference(boolean lock, SlingModel slingModel) { String sessionId = slingModel.sessionId; Log.e(logTag, "onLockConference: sessionId = " + sessionId); } /** * 停止共享 回调 */ public void onStopShareScreen(String userId) { String sessionId = userId; Log.e(logTag, "onStopShareScreen: sessionId = " + sessionId + ", sourceId = " + userId); String screenUid = sessionId + Constants.LOCAL_SCREEN; for (ParticipantInfoModel m : participantModels) { if (userId.equals(m.getUserId()) && !SHARING.equals(m.getStreamType())) { m.setShareStatus("off"); localVideoViewContainer.notifyVideoStateChanged(m); } } Map<String, ParticipantInfoModel> participantMap = RoomClient.get().getRemoteParticipant(); if (currentShareModel != null) { participantMap.remove(currentShareModel.getConnectionId()); _sinks.remove(currentShareModel.getUserId() + Constants.LOCAL_SCREEN); } L.d("do this ------.>>>websocket broad : " + participantMap.keySet().size() + " , " + _sinks.size()); removeShareView(screenUid); // for (Map.Entry<String, ParticipantInfoModel> entry : participantMap.entrySet()) { // if (SHARING.equals(entry.getValue().getStreamType())) { // participantMap.remove(entry.getKey()); // break; // } // } firstLayoutParams(); } /************************************HDMI***********************************/ public void shareScreenHDMI(View view) { if (!enableShare && shareHDMI.getText().equals("共享屏幕") && !RoomManager.get().isRoomAllowShare()) { UCToast.show(VideoConferenceActivity.this, "主持人已关闭共享操作"); return; } if (ViewUtils.isFastClickLong()) { return; } // RoomClient.get().inviteParticipant(channelId,SPEditor.instance().getAccount(),list); if (!supportHdmiIn) { UIUtils.toastMessage("目前只支持vhd设备"); return; } // initLocalScreen(); int[] idArray = new int[2]; if (!CameraEncoderv2.hasValidCamera(idArray)) { Toast.makeText(VideoConferenceActivity.this, "no vhd camera", Toast.LENGTH_LONG).show(); LogUtil.LOG_WARN("shareScreenHDMI", this.getClass().toString(), "not find vhd camera"); return; } else { LogUtil.LOG_WARN("shareScreenHDMI", this.getClass().toString(), "find vhd camera vid:pid(" + String.format("%04x", idArray[0]) + ":" + String.format("%04x", idArray[1]) + ")"); } Log.i("shareScreenHDMI", "shareScreenHDMI..." + isShareHas + "...." + isShareIng); if (isShareHas && !isShareIng) { UIUtils.toastMessage(currentShareUser + "正在共享屏幕,请稍后再试"); return; } if (shareHDMI.getText().equals("共享屏幕")) { if (!SystemUtil.isHdmiinConnected()) { UIUtils.toastMessage("请检查您的HDMI IN连接"); return; } isShareIng = true; isShareHas = true; if (mPresentation != null && mPresentation.isShowing()) { presentAdd(false, null); } webRTCManager.shareHdmiJoin(); shareHDMI.setText("结束共享"); } else { isShareIng = false; isShareHas = false; if (mPresentation != null && mPresentation.isShowing()) { ((SurfaceViewRenderer) mPresentation.getFrameLayout().getChildAt(0)).release(); mPresentation.getFrameLayout().removeView(mPresentation.getFrameLayout().getChildAt(0)); mPresentation.getImageView().setVisibility(View.VISIBLE); } else { // onStopShareScreen(userId); if (RoomManager.get().isHost()) { if (queues.contains(userId + LOCAL_SCREEN)) { queues.remove(userId + LOCAL_SCREEN); // RoomClient.get().getBroadcastMajorLayout(screenSplitType, queues, change); } } //移除共享 // removeShareSingleScreenLocal(); } webRTCManager.stopShareHdmi(); shareHDMI.setText("共享屏幕"); RoomClient.get().leaveRoom(userId, channelId, STREAM_SHARING); } } public void presentAdd(boolean insert, SurfaceViewRenderer surfaceViewRenderer) { if (isShareHas) { if (insert) { removeParent(surfaceViewRenderer); presentationHDMIVideoView = surfaceViewRenderer; } else { presentationHDMIVideoView = webRTCManager.createRendererView(getApplicationContext()); } presentationHDMIVideoView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); presentationHDMIVideoView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT); mPresentation.getFrameLayout().addView(presentationHDMIVideoView, 0); mPresentation.getImageView().setVisibility(View.GONE); if (isShareIng) { prensatationId = userId + LOCAL_SCREEN; } if (RoomManager.get().isHost()) { queueSend(); } webRTCManager.shareHdmi(presentationHDMIVideoView); } } public void HDMIAdd(boolean insert, SurfaceViewRenderer surfaceViewRenderer) { if (isShareHas) { if (insert) { removeParent(surfaceViewRenderer); initHDMISurface(surfaceViewRenderer); } else { initHDMISurface(); } initHDMIFrameLayout(); if (isShareIng) { prensatationId = userId + LOCAL_SCREEN; } if (RoomManager.get().isHost()) { queueSend(); } localVideoViewContainer.addView(locaHDMIFramenLayout); webRTCManager.shareHdmi(localHDMIVideoView); } } /** * */ public void queueSend() { if (isShareHas) { /** * 有分享加上分享 */ if (!TextUtils.isEmpty(prensatationId) && !queues.contains(prensatationId)) { if (queues.size() > 1) { queues.add(1, prensatationId); } else { queues.add(prensatationId); } // RoomClient.get().getBroadcastMajorLayout(screenSplitType, queues, change); } else { // RoomClient.get().getBroadcastMajorLayout(screenSplitType, queues, change); } /** * 先发送正确的列表,然后移除分屏Id */ for (int i = 0; i < queues.size(); i++) { Log.i("splitequeues", "s....." + queues.get(i)); if (queues.get(i).contains(LOCAL_SCREEN) && mPresentation != null && mPresentation.isShowing()) { queues.remove(i); break; } } for (int i = 0; i < queues.size(); i++) { Log.i("splitequeuesAfter", "s....." + queues.get(i)); } } else { // RoomClient.get().getBroadcastMajorLayout(screenSplitType, queues, change); } } /************************************分屏相关***********************************/ public void initPresentation(boolean insert) { Display[] displays;//屏幕数组 displays = mDisplayManager.getDisplays(); L.d("initPresentation: " + displays.length); if (displays.length > 1) { //链接设备大于1 开启分屏 mPresentation = new DifferentDislay(this, displays[1]);//displays[1]是副屏 mPresentation.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST); mPresentation.show(); if (insert) { addPresentMedia(); } // mPresentation.setOnclickForDifferent(new DifferentDislay.OnclickForDifferent() { // @Override // public void onclickDiff() { // UIUtils.toastMessage("分屏显示"); // } // }); } } public void addPresentMedia() { Log.i("closePresentMedia", "addPresentMedia" + isShareIng); if (isShareIng) { if (mPresentation != null && mPresentation.isShowing()) { initPresentSurface(); } if (participantModels.size() > 0 && SHARING.equals(participantModels.get(0).getStreamType())) { localVideoViewContainer.stopShare(participantModels.get(0)); } webRTCManager.shareHdmi(presentationHDMIVideoView); } else { if (mPresentation != null && mPresentation.isShowing()) { //接上辅屏,先展示图片 initPresentSurface(); if (isShareHas) { //移除主屏的共享流画面initPresentSurface if (participantModels.size() > 0 && SHARING.equals(participantModels.get(0).getStreamType())) { localVideoViewContainer.stopShare(participantModels.get(0)); } participantModels.get(0).getVideoSink().setTarget(presentationHDMIVideoView); } } } } public void closePresentation() { if (mPresentation != null) { mPresentation.dismiss(); } } public void initPresentSurface() { if (presentationHDMIVideoView == null) { Log.i("initPresentSurface", "initPresentSurface"); presentationHDMIVideoView = webRTCManager.createRendererView(getApplicationContext()); presentationHDMIVideoView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); presentationHDMIVideoView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT); } removeParent(presentationHDMIVideoView); mPresentation.getFrameLayout().addView(presentationHDMIVideoView, 0); mPresentation.getImageView().setVisibility(View.GONE); } public void closePresentMedia() { Log.i("closePresentMedia", "closePresentMedia" + isShareIng); // if (isShareIng) { // webRTCManager.shareHdmi(null); // } else { // if (isShareHas) { //将分享流重新显示到主屏第0个 if (participantModels.size() > 0 && SHARING.equals(participantModels.get(0).getStreamType())) { localVideoViewContainer.shareScreen(participantModels.get(0)); } // } // } } /****************************************屏幕适配相关*******************************/ /** * 万能适配 * * @return */ @Override public Resources getResources() { // AutoSizeCompat.autoConvertDensityOfGlobal((super.getResources())); return super.getResources(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // videoController.showMenu(); switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (isAllScreen) { if (isCurrentAllScreenSelf) { DeviceSettingManager.getInstance().endCameraControl(); } isCurrentAllScreenSelf = true; resetScreen(all_frameLayout); break; } finishAndRelease(); break; case KeyEvent.KEYCODE_ZOOM_IN: if (isAllScreen) { if (isCurrentAllScreenSelf) { DeviceSettingManager.getInstance().setCameraControl(GlobalValue.KEY_ZOOM_CONTROL, ZOOM_TELE); } else { PTZControlUtil.INSTANCE.operate(Operation.SMALL); } } break; case KeyEvent.KEYCODE_ZOOM_OUT: if (isAllScreen) { if (isCurrentAllScreenSelf) { DeviceSettingManager.getInstance().setCameraControl(GlobalValue.KEY_ZOOM_CONTROL, ZOOM_WIDE); } else { PTZControlUtil.INSTANCE.operate(Operation.LARGE); } } break; case KeyEvent.KEYCODE_DPAD_UP: videoController.showMenu(); if (isAllScreen) { if (isCurrentAllScreenSelf && event.getRepeatCount() == 0) { DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_UP); return true; } else if (!isCurrentAllScreenSelf && event.getRepeatCount() == 0) { PTZControlUtil.INSTANCE.operate(Operation.UP); } else { } } break; case KeyEvent.KEYCODE_DPAD_DOWN: videoController.showMenu(); if (isAllScreen) { if (isCurrentAllScreenSelf && event.getRepeatCount() == 0) { DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_DOWN); } else if (!isCurrentAllScreenSelf && event.getRepeatCount() == 0) { PTZControlUtil.INSTANCE.operate(Operation.DOWN); } else { } } break; case KeyEvent.KEYCODE_DPAD_LEFT: videoController.showMenu(); if (isAllScreen) { if (isCurrentAllScreenSelf && event.getRepeatCount() == 0) { DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_LEFT); return true; } else if (!isCurrentAllScreenSelf && event.getRepeatCount() == 0) { PTZControlUtil.INSTANCE.operate(Operation.LEFT); } else { } } break; case KeyEvent.KEYCODE_DPAD_RIGHT: videoController.showMenu(); if (isAllScreen) { if (isCurrentAllScreenSelf && event.getRepeatCount() == 0) { DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_RIGHT); return true; } else if (!isCurrentAllScreenSelf && event.getRepeatCount() == 0) { PTZControlUtil.INSTANCE.operate(Operation.RIGHT); } else { } } break; case KeyEvent.KEYCODE_0: setMemoryConfig(0); break; case KeyEvent.KEYCODE_1: setMemoryConfig(1); break; case KeyEvent.KEYCODE_2: setMemoryConfig(2); break; case KeyEvent.KEYCODE_3: setMemoryConfig(3); break; case KeyEvent.KEYCODE_4: setMemoryConfig(4); break; case KeyEvent.KEYCODE_5: setMemoryConfig(5); break; case KeyEvent.KEYCODE_6: setMemoryConfig(6); break; case KeyEvent.KEYCODE_7: setMemoryConfig(7); break; case KeyEvent.KEYCODE_8: setMemoryConfig(8); break; case KeyEvent.KEYCODE_9: setMemoryConfig(9); break; default: // videoController.reset(); break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_UP: if (isAllScreen) { if (isCurrentAllScreenSelf) { DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_STOP); } else { PTZControlUtil.INSTANCE.stop(); } } break; case KeyEvent.KEYCODE_DPAD_DOWN: if (isAllScreen) { if (isCurrentAllScreenSelf) { DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_STOP); } else { PTZControlUtil.INSTANCE.stop(); } } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (isAllScreen) { if (isCurrentAllScreenSelf) { DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_STOP); } else { PTZControlUtil.INSTANCE.stop(); } } break; case KeyEvent.KEYCODE_DPAD_RIGHT: if (isAllScreen) { if (isCurrentAllScreenSelf) { DeviceSettingManager.getInstance().setCameraControl(KEY_PANTILT_CONTROL, PANTILT_STOP); } else { PTZControlUtil.INSTANCE.stop(); } } break; case KeyEvent.KEYCODE_ZOOM_IN: if (isAllScreen) { if (isCurrentAllScreenSelf) { DeviceSettingManager.getInstance().setCameraControl(GlobalValue.KEY_ZOOM_CONTROL, ZOOM_STOP); } else { PTZControlUtil.INSTANCE.stop(); } } break; case KeyEvent.KEYCODE_ZOOM_OUT: if (isAllScreen) { if (isCurrentAllScreenSelf) { DeviceSettingManager.getInstance().setCameraControl(GlobalValue.KEY_ZOOM_CONTROL, ZOOM_STOP); } else { PTZControlUtil.INSTANCE.stop(); } } break; case KeyEvent.KEYCODE_CUT: shareScreenHDMI(shareHDMI); break; default: // videoController.getMenuManager().scheduleHide(); break; } return super.onKeyUp(keyCode, event); } /** * 会控 设置 重写fv * * @param id * @param <T> * @return */ @Override public <T extends View> T findViewById(int id) { if (id == R.id.fl_contair && meetSettingPopupWindow != null) { return meetSettingPopupWindow.getContentView().findViewById(R.id.fl_contair); } return super.findViewById(id); } //展示倒计时1m 弹框提醒 private void show1mDialog() { if (isFinishing()) { return; } VideoControlManager.getInstance().show1mDialog(this); } //WebSocket 网络状态变化监听 @Override public void onStateChange(WebSocketState socketState) { if (socketState == WebSocketState.OPEN) { runOnUiThread(() -> { if (ActivityUtils.getInstance().getStackCount() > 0) { if (ActivityUtils.getInstance().getCurrent() instanceof VideoConferenceActivity) { VideoControlManager.getInstance().dismissNetErrorPopup(); // dismissNetError(); } } }); } } //socket 连接次数 @Override protected void onSockedConnectFail() { super.onSockedConnectFail(); runOnUiThread(() -> { UIUtils.toastMessage("连接已断开"); if (ActivityUtils.getInstance().getStackCount() > 0) { if (ActivityUtils.getInstance().getCurrent() instanceof VideoConferenceActivity) { showNetError(); CallUtil.asyncCall(1000, () -> { RoomClient.get().setWebSocketStateListener(null); VideoControlManager.getInstance().dismissNetErrorPopup(); // dismissNetError(); doHangup(); releaseView(); L.d("onSockedConnectFail >>>>>" + currentSpeakUserId + " , userId: " + userId); if (userId.equals(currentSpeakUserId)) { RoomClient.get().setHasHands(false); } }); } } }); } //网络异常弹窗 private void showNetError() { if (isFinishing()) { return; } VideoControlManager.getInstance().showNetErrorPopup(this, cl_main); } private void releaseView() { localVideoViewContainer.removeAllViews(); _sinks.clear(); queues.clear(); finish(); // ActivityUtils.getInstance().finishUnitActivity(GroupActivity.class); } private List<ParticipantInfoModel> getParticipant() { if (mPresentation != null && mPresentation.isShowing()) { participantModels = RoomManager.get().getParticipants(); } else { participantModels = RoomManager.get().getParticipantsWithShare(); } for (ParticipantInfoModel model : participantModels) { L.d("do this ----getParticipant >>>>>>> " + model.getAppShowName() + " , " + model.getConnectionId()); } L.d("do this ----------getParticipant-------" + RoomManager.get().getRoomLayoutModel().getLayout()); swapModels(RoomManager.get().getRoomLayoutModel()); return participantModels; } /** * Called whenever a logical display has been added to the system. * Use {@link DisplayManager#getDisplay} to get more information about * the display. * * @param displayId The id of the logical display that was added. */ @Override public void onDisplayAdded(int displayId) { L.d("onDisplayAdded>>> " + displayId + ", " + mDisplayManager.getDisplays().length); initPresentation(true); //todo 添加辅屏, 主屏显示主流,辅屏显示辅流(主辅混叠能否显示) } /** * Called whenever a logical display has been removed from the system. * * @param displayId The id of the logical display that was removed. */ @Override public void onDisplayRemoved(int displayId) { L.d("onDisplayRemoved>>> " + displayId + ", " + mDisplayManager.getDisplays().length); L.d("onDisplayRemoved>>>" + mPresentation.getWindow().isActive()); closePresentation(); closePresentMedia(); if (presentationHDMIVideoView != null) { presentationHDMIVideoView.release(); presentationHDMIVideoView = null; } //todo 主屏拉取 主辅混叠 // changeShareView(true, true, userId + LOCAL_SCREEN); // HDMIAdd(true, presentationHDMIVideoView); } /** * Called whenever the properties of a logical display have changed. * * @param displayId The id of the logical display that changed. */ @Override public void onDisplayChanged(int displayId) { L.d("onDisplayChanged>>> " + displayId + ", " + mDisplayManager.getDisplays().length); } /************************************************* SFU新UI *********************************************/ //单屏接入共享(本地) private void addShareSingleScreenLocal(ParticipantInfoModel participantInfoModel) { L.d("do this ---addShareSingleScreenLocal>>>>"); ProxyVideoSink pvs = new ProxyVideoSink(); participantInfoModel.setVideoSink(pvs); if (mPresentation != null && mPresentation.isShowing()) { } else { _sinks.put(participantInfoModel.getUserId() + Constants.LOCAL_SCREEN, pvs); } currentShareModel = participantInfoModel; //更新当前正在共享的与会者 for (ParticipantInfoModel m : participantModels) { if (participantInfoModel.getUserId().equals(m.getUserId()) && !SHARING.equals(m.getStreamType())) { localVideoViewContainer.notifyVideoStateChanged(m); } } if (mPresentation != null && mPresentation.isShowing()) { firstLayoutParams(); return; } participantModels.add(0, participantInfoModel); localVideoViewContainer.shareScreen(participantInfoModel); firstLayoutParams(); } //单屏移除共享(本地) private void removeShareSingleScreenLocal() { int currentMode = localVideoViewContainer.getMode(); if (SHARING.equals(participantModels.get(0).getStreamType())) { localVideoViewContainer.stopShare(participantModels.get(0)); participantModels.remove(0); } } public void initVideoControl() { videoController.setVideoPlayControl(this); videoController.setViewData(channelId); videoController.initBasis(); videoController.initData(); videoController.setBaseActivity(this); videoController.setRoleViewStatus(); try { getLifecycle().addObserver(videoController); } catch (Exception e) { } } private void inviteParticipantNow() { if (RoomManager.get().getListOfInvited().size() > 0) { RoomClient.get().inviteParticipant(channelId, RoomManager.get().getUserId(), RoomManager.get().getListOfInvited()); RoomManager.get().getListOfInvited().clear(); } } //设置会议时间 private void setDuringTime() { long time = new Date(System.currentTimeMillis() - RoomManager.get().getCreateAt()).getTime(); //获取的服务器时间戳 快了本地获取系统时间 3s long m = time / (1000); if (m < 0) { m = 0; } videoController.setMeetDuring(m); } //重新读取预置点 private void setMemoryConfig(int key) { if (isCurrentAllScreenSelf && StringUtils.isIndexEqual1(strOfKeySet, key)) { DeviceSettingManager.getInstance().setCameraControl(GlobalValue.MEMORY_RECALL, String.valueOf(key)); } } public void onRemoteLoginNotify() { doHangup(); RoomClient.get().setShowRollCall(false); RoomClient.get().setHasHands(false); lastBreakLineUserId = ""; CallUtil.asyncCall(500, () -> { RoomClient.get().accessOut(); }); } @Override public void roomSettingControl(View view) { roomSetting(view); } @Override public void splitScreen0Control() { if (RoomManager.get().isHost()) { RoomClient.get().setConferenceLayout(4, false); } } @Override public void splitScreen4Control(int count, boolean b) { L.d("do this ----splitScreen4Control"); if (RoomManager.get().isHost()) { if (b) { localVideoViewContainer.autoLayout(); } else { localVideoViewContainer.setMode(count); } ArrayList<String> connectIds = new ArrayList<>(); for (ParticipantInfoModel model : participantModels) { connectIds.add(model.getConnectionId()); } if (mPresentation != null && mPresentation.isShowing() && currentShareModel != null) { connectIds.add(0, currentShareModel.getConnectionId()); } RoomClient.get().getBroadcastMajorLayout(localVideoViewContainer.getMode(), connectIds, "change"); } } @Override public void roomClosed() { finishAndRelease(); } @Override public void shareControl(View view) { shareHDMI = (TextView) view; shareScreenHDMI(view); } @Override public void OnLocalShareJoin(ParticipantInfoModel participantInfoModel) { runOnUiThread(() -> { addShareSingleScreenLocal(participantInfoModel); }); } }
terceiro/rmagick
spec/rmagick/draw/circle_spec.rb
RSpec.describe Magick::Draw, '#circle' do it 'works' do draw = described_class.new image = Magick::Image.new(200, 200) draw.circle(10, '20.5', 30, 40.5) expect(draw.inspect).to eq('circle 10,20.5 30,40.5') expect { draw.draw(image) }.not_to raise_error expect { draw.circle('x', 20, 30, 40) }.to raise_error(ArgumentError) expect { draw.circle(10, 'x', 30, 40) }.to raise_error(ArgumentError) expect { draw.circle(10, 20, 'x', 40) }.to raise_error(ArgumentError) expect { draw.circle(10, 20, 30, 'x') }.to raise_error(ArgumentError) end end
GhostMachineSoftware/SPFX_UsefulLinks
node_modules/office-ui-fabric-react/lib-amd/utilities/keytips/index.js
<filename>node_modules/office-ui-fabric-react/lib-amd/utilities/keytips/index.js define(["require", "exports", "tslib", "./IKeytipTransitionKey", "./KeytipConfig", "./KeytipConstants", "./KeytipManager", "./KeytipUtils"], function (require, exports, tslib_1, IKeytipTransitionKey_1, KeytipConfig_1, KeytipConstants_1, KeytipManager_1, KeytipUtils_1) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(IKeytipTransitionKey_1, exports); tslib_1.__exportStar(KeytipConfig_1, exports); tslib_1.__exportStar(KeytipConstants_1, exports); tslib_1.__exportStar(KeytipManager_1, exports); tslib_1.__exportStar(KeytipUtils_1, exports); }); //# sourceMappingURL=index.js.map
jeffposnick/ioweb2015
app/elements/webgl-globe/sol.js
/* global IOWA */ /** * Copyright 2015 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Returns the unit vector from the center of the earth to the position of the * sun on the celestial sphere at the specified time. The positive x-axis * emerges from 90˚E on the equator, the posizitve y-axis emerges from the * north pole, and the positive z-axis emerges from the prime meridian at the * equator. * The time is assumed to be specified under the Gregorian Calendar. * An optional output array can be provided to avoid an array allocation. * Solar position accurate to within 0.01˚. * @param {!Date} time * @param {!Array<number>} opt_output * @return {!Array<number>} */ IOWA.WebglGlobe.getSolarPosition = (function() { // Based on Meeus, <NAME>. Astronomical algorithms. 1991. /** * Calculates the sun's mean anomaly at time t. * @param {number} t * @return {number} */ function solarMeanAnomaly(t) { return 6.24006 + t * (628.3019552 - 2.6825711e-6 * t); } /** * Calculates the equation of the center of the sun in radians at time t: the * difference between the mean anomaly and the true anomaly. Relatively low * accuracy. * @param {number} t * @return {number} */ function sunEqOfCenter(t) { var m = solarMeanAnomaly(t); return Math.sin(m) * (0.03341611 + t * (-0.0000840725 - t * 2.443461e-7)) + Math.sin(2 * m) * (0.0003489437 - t * 1.7627825e-6) + Math.sin(3 * m) * 5.0440015e-6; } /** * Calculate the sun's true anomaly in radians at time t. Relatively low * accuracy. * @param {number} t * @return {number} */ function solarTrueAnomaly(t) { return solarMeanAnomaly(t) + sunEqOfCenter(t); } /** * Calculate the sun's mean longitude in radians at time t. NOTE: result has * not had its range reduced, so use with caution. * @param {number} t * @return {number} */ function solarMeanLongitude(t) { // VSOP87 return 4.8950631108 + t * (628.3319667 + t * (5.291887161e-6 + t * (3.49548227e-10 + t * (-1.1407381e-10 - t * 8.72664626e-14)))); } /** * Calculates the sun's true longitude in radians at time t. Relatively low * accuracy. * @param {number} t * @return {number} */ function solarTrueLongitude(t) { return solarMeanLongitude(t) + sunEqOfCenter(t); } /** * Calculates the eccentricty of the Earth's orbit at time t. Currently about * 0.0167. * @param {number} t * @return {number} */ function earthOrbitEccentricty(t) { return 0.016708634 - t * (0.000042037 + t * 0.0000001267); } /** * Calculates the distance from the Earth to the sun in AUs at time t. * @param {number} t * @return {number} */ function solarDistance(t) { var e = earthOrbitEccentricty(t); var radius = (1.000001018 * (1 - e * e)) / (1 + e * Math.cos(solarTrueAnomaly(t))); return radius; } /** * Calculates the sun's apparent longitude in radians at time t. Relatively * low accuracy. * @param {number} t * @return {number} */ function solarApparentLongitude(t) { var aberration = -0.00009933735 / solarDistance(t); // Single term of longitude nutation. var nutation = -0.000083388 * Math.sin(2.1824386 - 33.75704594 * t); return solarTrueLongitude(t) + aberration + nutation; } /** * Returns true obliquity at time t in radians. Calculated as mean ecliptic * obliquity plus a smaller nutation correction. Relatively low accuracy. * @param {number} t * @return {number} */ function obliquity(t) { // Mean obliquity in radians. Jet Propulsion Laboratory's DE200, from 1984. // Error reaches 1" over 2000 years from J2000. var meanObliquity = 0.409093 + t * (-0.000226966 + t * (-2.8604e-9 + t * 8.789672e-9)); // Two terms of obliquity nutation. var nutation = 0.0000446029 * Math.cos(2.1824386 - 33.75704594 * t) + 2.76344e-6 * Math.cos(9.7901277 + 1256.66393 * t); return meanObliquity + nutation; } /** * Calculates the sun's declination in radians at time t. Relatively low * accuracy. * @param {number} t * @return {number} */ function solarDeclination(t) { return Math.asin(Math.sin(obliquity(t)) * Math.sin(solarApparentLongitude(t))); } /** * Calculates the equation of time -- the difference between the hour angles * of the true Sun and the mean Sun -- in radians at time t. * @param {number} t * @return {number} */ function equationOfTime(t) { // Approximation from <NAME>. Textbook on Spherical Astronomy. 1956. // Variable names matching Meeus. var y = Math.tan(obliquity(t) / 2); y *= y; var l0 = solarMeanLongitude(t); var e = earthOrbitEccentricty(t); var m = solarMeanAnomaly(t); return y * Math.sin(2 * l0) - 2 * e * Math.sin(m) + 4 * e * y * Math.sin(m) * Math.cos(2 * l0) - y * y * 0.5 * Math.sin(4 * l0) - 5 / 4 * e * e * Math.sin(2 * m); } /** * Convert from the given time to a time in Julian Centuries (36,525 Julian * Days) since the epoch J2000.0. Assumes date is provided in the Gregorian * calendar. * @param {!Date} time * @return {number} */ function getJulianCentury(time) { var year = time.getUTCFullYear(); var month = time.getUTCMonth() + 1; var day = time.getUTCDate() + (((time.getUTCMilliseconds() / 1000 + time.getUTCSeconds()) / 60 + time.getUTCMinutes()) / 60 + time.getUTCHours()) / 24; // Include January and February as the end of the previous year. if (month < 3) { year -= 1; month += 12; } var century = Math.floor(year / 100); var julianDay = Math.floor(365.25 * (year + 4716)) + Math.floor(30.6001 * (month + 1)) + day + 2 - century + Math.floor(century / 4) - 1524.5; return (julianDay - 2451545) / 36525; } return function getSolarPosition(time, opt_output) { var t = getJulianCentury(time); // Time since midnight, UTC. var msSinceMidnight = time % 86400000; var meanSolarHourAngle = (msSinceMidnight / 43200000 + 1) * Math.PI; var greenwichHourAngle = meanSolarHourAngle + equationOfTime(t); var declination = solarDeclination(t); // From LHA/dec to celestial sphere coordinate system. var output = opt_output || []; output[0] = -Math.sin(greenwichHourAngle) * Math.cos(declination); output[1] = Math.sin(declination); output[2] = Math.cos(greenwichHourAngle) * Math.cos(declination); return output; }; })();
yyc-git/YYCToolBox
control/paging/pagingServer/createPage/PagingBuilder.js
(function () { //*方法库 function extend(destination, source) { // var temp = {}; var property = ""; for (property in source) { // temp[property] = source[property]; //用中间对象来保存source destination[property] = source[property]; } return destination; }; // var IPagingBuilder = YYC.Interface("builDdiv", "getOnlyOne", "getFirst", "getPrev", "getPrevShow", "getMiddle", "getNext", "getNextShow", "getLast", "getInfo", "getJumpTo", "getProduct"); // { Interface: IPagingBuilder }, var APagingBuilder = YYC.AClass({ Protected: { Abstract: { //*子类实现 P_product: null } }, Public: { // buildDiv: function () { // // this.P_element = $("<div class='page_nav'/>"); // this.P_product.setDiv(); // }, buildOnlyOne: function () { // if (this.P_config.pageCount <= 1) { // this.P_element.append($("<span>共" + this.P_config.totalCount + "条</span>")); this.P_product.add(this.P_product.getOnlyOne()); // } }, buildFirst: function () { this.P_product.add(this.P_product.getFirst()); }, buildPrev: function () { this.P_product.add(this.P_product.getPrev()); }, buildPrevShow: function () { this.P_product.add(this.P_product.getPrevShow()); }, buildMiddle: function () { this.P_product.add(this.P_product.getMiddle()); }, buildNextShow: function () { this.P_product.add(this.P_product.getNextShow()); }, buildNext: function () { this.P_product.add(this.P_product.getNext()); }, buildLast: function () { this.P_product.add(this.P_product.getLast()); }, buildJumpTo: function () { this.P_product.add(this.P_product.getJumpTo()); }, buildInfo: function () { // this._info = $(tool.format("<span> 共{0}条 每页显示{1}条 当前第{2}/{3}页</span>", this.P_config.totalCount, this.P_config.pageSize, this.P_config.pageNumber, this.P_config.pageCount)); // var info = $(tool.format("<span> 共{0}条 每页显示{1}条 当前第{2}/{3}页</span>", this.P_config.totalCount, this.P_config.pageSize, this.P_config.pageNumber, this.P_config.pageCount)); // this.P_element.append(info); this.P_product.add(this.P_product.getInfo()); }, getProduct: function () { // return this.P_element; return this.P_product.getProduct(); } } }); var PagingBuilderNoStr = YYC.Class(APagingBuilder, { Init: function (config) { // this.P_config = extend({}, config); var className = ""; this.P_product = new YYC.Control.Paging.PagingProductNoStr(config); if (config.className === undefined) { className = "page_nav"; } else { className = config.className; } this.P_product.setDiv(className); } //Protected: { // //*实现父类抽象成员 // P_product: null //} }); var PagingBuilderWithStr = YYC.Class(APagingBuilder, { Init: function (config) { this.P_product = new YYC.Control.Paging.PagingProductWithStr(config); if (config.className === undefined) { className = "page_nav"; } else { className = config.className; } this.P_product.setDiv(className); } //Protected: { // //*实现父类抽象成员 // P_product: null //} }); YYC.namespace("Control.Paging").PagingBuilderNoStr = PagingBuilderNoStr; YYC.namespace("Control.Paging").PagingBuilderWithStr = PagingBuilderWithStr; } ());
bbcawodu/careadvisors-backend
picbackend/views/v2/nav_location_views/views.py
from django.views.generic import View from picbackend.views.utils import JSONGETRspMixin from picbackend.views.utils import JSONPUTRspMixin from picmodels.models import NavMetricsLocation from .tools import validate_put_rqst_params # Need to abstract common variables in get and post class methods into class attributes class NavHubLocationManagementView(JSONPUTRspMixin, JSONGETRspMixin, View): """ Defines views that handles Patient Innovation Center navigator hub location instance related requests """ def nav_hub_location_management_put_logic(self, rqst_body, response_raw_data, rqst_errors): validated_put_rqst_params = validate_put_rqst_params(rqst_body, rqst_errors) rqst_action = validated_put_rqst_params['rqst_action'] if not rqst_errors: if rqst_action == "create": location_instance = NavMetricsLocation.create_row_w_validated_params( validated_put_rqst_params, rqst_errors ) if location_instance: response_raw_data['Data']["row"] = location_instance.return_values_dict() elif rqst_action == "update": location_instance = NavMetricsLocation.update_row_w_validated_params( validated_put_rqst_params, rqst_errors ) if location_instance: response_raw_data['Data']["row"] = location_instance.return_values_dict() elif rqst_action == "delete": NavMetricsLocation.delete_row_w_validated_params(validated_put_rqst_params, rqst_errors) if not rqst_errors: response_raw_data['Data']["row"] = "Deleted" else: rqst_errors.append("No valid 'db_action' provided.") def nav_hub_location_management_get_logic(self, request, validated_GET_rqst_params, response_raw_data, rqst_errors): def retrieve_data_and_add_to_response(): if 'id' in validated_GET_rqst_params: rqst_nav_hub_location_id = validated_GET_rqst_params['id'] if rqst_nav_hub_location_id != 'all': list_of_ids = validated_GET_rqst_params['id_list'] else: list_of_ids = None else: rqst_nav_hub_location_id = 'all' list_of_ids = None data_list = NavMetricsLocation.retrieve_nav_hub_location_data_by_id( validated_GET_rqst_params, rqst_nav_hub_location_id, list_of_ids, rqst_errors ) response_raw_data["Data"] = data_list retrieve_data_and_add_to_response() parse_PUT_request_and_add_response = nav_hub_location_management_put_logic accepted_GET_request_parameters = [ "is_cps_location", "id" ] parse_GET_request_and_add_response = nav_hub_location_management_get_logic
kozanitis/adam
adam-core/src/test/scala/org/bdgenomics/adam/models/FeatureHierarchySuite.scala
/** * Licensed to Big Data Genomics (BDG) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The BDG 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.bdgenomics.adam.models import org.bdgenomics.formats.avro.{ Contig, Feature } import org.scalatest.FunSuite class FeatureHierarchySuite extends FunSuite { test("Feature values converted into GTFFeatures retain their aligned positions in the fields of ReferenceRegion") { val contig = Contig.newBuilder().setContigName("chr1").build() val f = Feature.newBuilder() .setContig(contig) .setStart(1000L) .setEnd(2000L) .setFeatureId("id") .build() val bf = new GTFFeature(f) assert(bf.getSeqname === "chr1") assert(bf.getStart === 1000L) assert(bf.getEnd === 2000L) assert(bf.feature.getFeatureId === "id") } }
MrCreosote/execution_engine2
lib/execution_engine2/authorization/roles.py
""" A utility class for fetching roles for a token and caching them. This makes use of the TokenCache in the built-in service auth client. This is an SDK-based service, so auth token validation is handled through the Server. This just takes an auth token and discerns whether there's a valid EE2 admin role attached to the user. """ from json import JSONDecodeError from typing import List, Set, Optional import requests from lib.execution_engine2.exceptions import AuthError from lib.installed_clients.authclient import TokenCache IS_ADMIN = "EE2_ADMIN" NOT_ADMIN = "NOT_ADMIN" _admin_cache = TokenCache() class AdminAuthUtil: """ A simple Auth utility. This is NOT an auth client, but a utility class that's used to look up user roles. """ def __init__(self, auth_url: str, admin_roles: List): """ :param auth_url: string - the base url of the KBase auth2 service. :param admin_roles: List - a list of roles that are allowed to be EE2 admins """ # Use the token cache from the service's authclient, but put in strings for whether the # token's account is an admin or not. self.auth_url = auth_url self.admin_roles = set(admin_roles) def is_admin(self, token: str) -> bool: """ Fetches the admin role information from the cache, or from the auth server. will raise a ValueError if: * token is None will raise an AuthError if: * token is invalid (401 from auth server) will raise a RuntimeError if: * any other auth server error * auth service times out :param token: an auth Token :return: boolean - True if the user has EE2 admin privs, False otherwise. """ if not token: raise ValueError("Must supply token to check privileges") is_admin = _admin_cache.get_user(token) # is_admin will be a string if present, either IS_ADMIN or NOT_ADMIN if is_admin is not None: return is_admin == IS_ADMIN # if we don't have the info, go fetch it roles = self._fetch_user_roles(token) if self.admin_roles.intersection(set(roles)): _admin_cache.add_valid_token(token, IS_ADMIN) return True else: _admin_cache.add_valid_token(token, NOT_ADMIN) return False def get_admin_role(self, token: str, read_role, write_role) -> Optional[str]: roles = self._fetch_user_roles(token) if write_role in roles: return write_role if read_role in roles: return read_role return None def get_user_roles(self, token: str) -> List: return list(self._fetch_user_roles(token=token)) def _fetch_user_roles(self, token: str) -> Set: """ Returns the user's custom roles from the auth server as a Set. :param token: the Auth token :returns: Set - the set of customroles assigned to the user """ if not token: raise ValueError("Must supply a token to fetch user roles") try: ret = requests.get( self.auth_url + "/api/V2/me", headers={"Authorization": token} ) ret.raise_for_status() # this is a no-op if all is well user_info = ret.json() return set(user_info.get("customroles", [])) except requests.HTTPError as e: err_msg = dict() try: err_msg = e.response.json().get("error", {}) except JSONDecodeError: pass if e.response.status_code == 401: raise AuthError("Token is not valid") raise RuntimeError( "An error occurred while fetching user roles from auth service: {} {}\n{}".format( e.response.status_code, e.response.reason, err_msg.get("message", "Unknown Auth error"), ) ) except requests.exceptions.ConnectTimeout: raise RuntimeError("The auth service timed out while fetching user roles.")
Khalid-Sultan/Algorithms-Prep
Leetcode/Array/2_-_Medium/1442._Count_Triplets_That_Can_Form_Two_Arrays_of_Equal_XOR.py
class Solution: def countTriplets(self, A): res = cur = 0 count = {0: [1, 0]} for i, a in enumerate(A): cur ^= a n, total = count.get(cur, [0, 0]) res += i * n - total count[cur] = [n + 1, total + i + 1] return res
krisjin/uis
luban-common/src/main/java/org/luban/common/web/json/JsonHelper.java
package org.luban.common.web.json; /** * User: krisjin * Date: 2016/10/8 */ public final class JsonHelper { // private static final ObjectMapper objectMapper = new ObjectMapper(); // private static final JsonFactory jsonFactory = new JsonFactory(); // // static { // //设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性 // objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); // } // // // public static <T> T fromJson(String jsonAsString, Class<T> clazz) throws Exception { // return (T) objectMapper.readValue(jsonAsString, clazz); // } // // public static String toJson(Object object, boolean prettyPrint) { // StringWriter stringWriter = new StringWriter(); // try { // JsonGenerator jg = jsonFactory.createJsonGenerator(stringWriter); // if (prettyPrint) { // jg.useDefaultPrettyPrinter(); // } // objectMapper.writeValue(jg, object); // } catch (IOException e) { // e.printStackTrace(); // } // return stringWriter.toString(); // } // // // public static String toJson(Object object) { // return toJson(object, false); // } // // public static <T> T fromJson(String jsonContent, TypeReference typeReference) { // T rtnRst = null; // try { // rtnRst = (T) objectMapper.readValue(jsonContent, typeReference); // } catch (Exception e) { // e.printStackTrace(); // } // return rtnRst; // } }
28Smiles/jdbi-modules
src/main/java/jdbi_modules/internal/CollectorImpl.java
<filename>src/main/java/jdbi_modules/internal/CollectorImpl.java<gh_stars>1-10 package jdbi_modules.internal; import jdbi_modules.Collector; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.function.BiFunction; import java.util.function.Consumer; /** * @param <CollectionType> the type of the collection the collector handles * @param <Type> the type of elements in the collection * @since 14.04.2018 */ class CollectorImpl<CollectionType extends Collection<Type>, Type> implements Collector<CollectionType, Type> { private final RowView rowView; private final ResultSet resultSet; private final StatementContext context; private CollectionType collection; private BiFunction<Type, Type, Boolean> comparator = Object::equals; private List<Type> added = new ArrayList<>(); private List<Type> accessed = new ArrayList<>(); CollectorImpl(final CollectionType collection, final RowView rowView, final ResultSet resultSet, final StatementContext context) { this.collection = collection; this.rowView = rowView; this.resultSet = resultSet; this.context = context; } @Override public Collector<CollectionType, Type> setComparator(@NotNull final BiFunction<Type, Type, Boolean> comparator) { this.comparator = comparator; return this; } @Override public CollectionType get() { return collection; } @Override public CollectorImpl<CollectionType, Type> appendUnique(@Nullable final Type type, @NotNull final Consumer<Type> applier) { if (Objects.isNull(type)) { return this; } final Type found = collection.stream().filter(b -> comparator.apply(b, type)).findFirst().orElseGet(() -> { collection.add(type); added.add(type); return type; }); accessed.add(found); applier.accept(found); return this; } @Override public CollectorImpl<CollectionType, Type> appendUnique(@Nullable final Type type) { if (Objects.isNull(type)) { return this; } accessed.add(collection.stream().filter(b -> comparator.apply(b, type)).findFirst().orElseGet(() -> { collection.add(type); added.add(type); return type; })); return this; } @Override public CollectorImpl<CollectionType, Type> append(@Nullable final Type type, @NotNull final Consumer<Type> applyer) { if (Objects.isNull(type)) { return this; } collection.add(type); applyer.accept(type); added.add(type); accessed.add(type); return this; } @Override public CollectorImpl<CollectionType, Type> append(@Nullable final Type type) { if (Objects.isNull(type)) { return this; } collection.add(type); added.add(type); accessed.add(type); return this; } @Override public CollectorImpl<CollectionType, Type> appendUniqueWithRowView(@NotNull final Class<Type> clazz, @NotNull final Consumer<Type> applier) { final Type type = rowView.getRow(clazz); return appendUnique(type, applier); } @Override public CollectorImpl<CollectionType, Type> appendUniqueWithRowView(@NotNull final Class<Type> clazz) { final Type type = rowView.getRow(clazz); return appendUnique(type); } @Override public CollectorImpl<CollectionType, Type> appendWithRowView(@NotNull final Class<Type> clazz, @NotNull final Consumer<Type> applier) { final Type type = rowView.getRow(clazz); return append(type, applier); } @Override public CollectorImpl<CollectionType, Type> appendWithRowView(@NotNull final Class<Type> clazz) { final Type type = rowView.getRow(clazz); return append(type); } @Override public CollectorImpl<CollectionType, Type> appendWithRowMapper(@NotNull final RowMapper<Type> rowMapper, @NotNull final Consumer<Type> applier) throws SQLException { final Type type = rowMapper.map(resultSet, context); return append(type, applier); } @Override public CollectorImpl<CollectionType, Type> appendWithRowMapper(@NotNull final RowMapper<Type> rowMapper) throws SQLException { final Type type = rowMapper.map(resultSet, context); return append(type); } @Override public Collector<CollectionType, Type> appendUniqueWithRowMapper(@NotNull final RowMapper<Type> rowMapper, @NotNull final Consumer<Type> applier) throws SQLException { final Type type = rowMapper.map(resultSet, context); return appendUnique(type, applier); } @Override public Collector<CollectionType, Type> appendUniqueWithRowMapper(@NotNull final RowMapper<Type> rowMapper) throws SQLException { final Type type = rowMapper.map(resultSet, context); return appendUnique(type); } void useCollection(final CollectionType collection) { this.collection = collection; this.added.clear(); this.accessed.clear(); } void applyOnAdded(@NotNull final Consumer<Type> consumer) { added.forEach(consumer); } void applyOnAccessed(@NotNull final Consumer<Type> consumer) { accessed.forEach(consumer); } }
EvanTich/WASPBot
src/evan/tichenor/bot/commands/util/BigText.java
package bot.evan.tichenor.commands.util; import de.btobastian.javacord.entities.User; import de.btobastian.sdcf4j.Command; import de.btobastian.sdcf4j.CommandExecutor; /** * @author <NAME> (<EMAIL>) * @version 1.0, 9/9/2017 */ public class BigText implements CommandExecutor { @Command(aliases = {"big", "bigtext"}, description = "Make big text.", usage = "!big <text>") public String onCommand(String[] args) { StringBuilder nStr = new StringBuilder(); for(String str : args) { for (char c : str.toCharArray()) nStr.append(toBig(c)); nStr.append(" "); } return nStr.toString(); } public String toBig(char c) { c = Character.toLowerCase(c); if(c >= 'a' && c <= 'z') return String.format(":regional_indicator_%s:", c); else if (Character.isDigit(c)) switch (c) { case '0': return ":zero:"; case '1': return ":one:"; case '2': return ":two:"; case '3': return ":three:"; case '4': return ":four:"; case '5': return ":five:"; case '6': return ":six:"; case '7': return ":seven:"; case '8': return ":eight:"; case '9': return ":nine:"; } return c + ""; } }
Ccloud0302/seata
serializer/seata-serializer-kryo/src/main/java/io/seata/serializer/kryo/KryoInnerSerializer.java
/* * Copyright 1999-2019 Seata.io Group. * * 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.seata.serializer.kryo; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Objects; /** * @author jsbxyyx */ public class KryoInnerSerializer { private final Kryo kryo; public KryoInnerSerializer(Kryo kryo) { this.kryo = Objects.requireNonNull(kryo); } public Kryo getKryo() { return kryo; } public <T> byte[] serialize(T t) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Output output = new Output(baos); kryo.writeClassAndObject(output, t); output.close(); return baos.toByteArray(); } public <T> T deserialize(byte[] bytes) { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); Input input = new Input(bais); input.close(); return (T) kryo.readClassAndObject(input); } }
liangxiaoqiao/LeetCodeDay
src/main/java/com/liangxiaoqiao/leetcode/day/hard/WordSearchIi.java
package com.liangxiaoqiao.leetcode.day.hard; import java.util.List; /* * English * id: 212 * title: Word Search II * href: https://leetcode.com/problems/word-search-ii * desc: Given a 2D board and a list of words from the dictionary, find all words in the board.\nEach word must be constructed from letters of sequentially adjacent cell, where \"adjacent\" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.\nExample:\nInput: \nwords = [\"oath\",\"pea\",\"eat\",\"rain\"] and board =\n[\n [\'o\',\'a\',\'a\',\'n\'],\n [\'e\',\'t\',\'a\',\'e\'],\n [\'i\',\'h\',\'k\',\'r\'],\n [\'i\',\'f\',\'l\',\'v\']\n]\n\nOutput: [\"eat\",\"oath\"]\nNote:\nYou may assume that all inputs are consist of lowercase letters a-z. * <p> * 中文 * 序号: 212 * 标题: 单词搜索 II * 链接: https://leetcode-cn.com/problems/word-search-ii * 描述: 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。\n单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。\n示例:\n输入: \nwords = [\"oath\",\"pea\",\"eat\",\"rain\"] and board =\n[\n [\'o\',\'a\',\'a\',\'n\'],\n [\'e\',\'t\',\'a\',\'e\'],\n [\'i\',\'h\',\'k\',\'r\'],\n [\'i\',\'f\',\'l\',\'v\']\n]\n\n输出: [\"eat\",\"oath\"]\n说明:\n你可以假设所有输入都由小写字母 a-z 组成。\n提示:\n你需要优化回溯算法以通过更大数据量的测试。你能否早点停止回溯?\n如果当前单词不存在于所有单词的前缀中,则可以立即停止回溯。什么样的数据结构可以有效地执行这样的操作?散列表是否可行?为什么? 前缀树如何?如果你想学习如何实现一个基本的前缀树,请先查看这个问题: 实现Trie(前缀树)。 * <p> * acceptance: 31.4% * difficulty: Hard * private: False */ //TODO init public class WordSearchIi { public List<String> findWords(char[][] board, String[] words) { return null; } }
banderous/nfdiv-case-api
src/main/java/uk/gov/hmcts/divorce/document/content/provider/ApplicantTemplateDataProvider.java
package uk.gov.hmcts.divorce.document.content.provider; import org.springframework.stereotype.Component; import uk.gov.hmcts.ccd.sdk.type.AddressGlobalUK; import uk.gov.hmcts.divorce.divorcecase.model.Applicant; import uk.gov.hmcts.divorce.divorcecase.model.Application; import java.util.stream.Stream; import static java.util.stream.Collectors.joining; @Component public class ApplicantTemplateDataProvider { public String deriveApplicantPostalAddress(final Applicant applicant) { final AddressGlobalUK applicantHomeAddress = applicant.getHomeAddress(); if (applicant.isRepresented()) { return applicant.getSolicitor().getAddress(); } else if (null != applicantHomeAddress && !applicant.isConfidentialContactDetails()) { return Stream.of( applicantHomeAddress.getAddressLine1(), applicantHomeAddress.getAddressLine2(), applicantHomeAddress.getAddressLine3(), applicantHomeAddress.getPostTown(), applicantHomeAddress.getCounty(), applicantHomeAddress.getPostCode(), applicantHomeAddress.getCountry()) .filter(value -> null != value && !value.isEmpty()) .collect(joining("\n")); } return null; } public String deriveApplicant2PostalAddress(final Applicant applicant, final Application application) { if (applicant.isRepresented()) { return applicant.getSolicitor().getAddress(); } else if (!applicant.isConfidentialContactDetails()) { final AddressGlobalUK applicantHomeAddress = application.isSolicitorApplication() ? applicant.getCorrespondenceAddress() : applicant.getHomeAddress(); if (null != applicantHomeAddress) { return Stream.of( applicantHomeAddress.getAddressLine1(), applicantHomeAddress.getAddressLine2(), applicantHomeAddress.getAddressLine3(), applicantHomeAddress.getPostTown(), applicantHomeAddress.getCounty(), applicantHomeAddress.getPostCode(), applicantHomeAddress.getCountry() ) .filter(value -> value != null && !value.isEmpty()) .collect(joining("\n")); } } return null; } }
hiyouga/CPP-Learning
buaaoj/1335.cpp
<reponame>hiyouga/CPP-Learning<gh_stars>0 #include <iostream> using namespace std; int n, s = 0; void step(int t) { if (t >= n) { s += (t == n); return; } step(t+1); step(t+2); } int main() { cin >> n; step(0); cout << s << endl; return 0; }
1690296356/jdk
test/jdk/java/time/test/java/time/format/TestLocalizedOffsetPrinterParser.java
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 8154520 * @summary This test verifies that the localized text for "GMT" from CLDR is * applied/recognized during printing/parsing timestamps. For example, the * localized text for "GMT" on some particular locale may be "UTC", and the * resulting formatted string should have UTC+<offset> (instead of GMT+<offset>). * Since the test relies on CLDR data, the "expected" text in the test data may * require to be modified in accordance with changes to CLDR, if any. * @modules jdk.localedata */ package test.java.time.format; import static org.testng.Assert.assertEquals; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.TextStyle; import java.util.Locale; import java.util.Objects; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Test DateTimeFormatterBuilder.appendOffset(). */ @Test public class TestLocalizedOffsetPrinterParser { private static final LocalDateTime DT_2012_06_30_12_30_40 = LocalDateTime.of(2012, 6, 30, 12, 30, 40); private static final Locale LOCALE_GA = new Locale("ga"); @DataProvider(name="print_localized_custom_locale") Object[][] data_print_localized_custom_locale() { return new Object[][] { {TextStyle.FULL, DT_2012_06_30_12_30_40, ZoneOffset.UTC, LOCALE_GA, "MAG"}, {TextStyle.SHORT, DT_2012_06_30_12_30_40, ZoneOffset.ofHours(1), LOCALE_GA, "MAG+1"}, {TextStyle.FULL, DT_2012_06_30_12_30_40, ZoneOffset.ofHours(-1), LOCALE_GA, "MAG-01:00"} }; } @Test(dataProvider="print_localized_custom_locale") public void test_print_localized_custom_locale(TextStyle style, LocalDateTime ldt, ZoneOffset offset, Locale locale, String expected) { Objects.requireNonNull(locale, "Locale must not be null"); OffsetDateTime odt = OffsetDateTime.of(ldt, offset); ZonedDateTime zdt = ldt.atZone(offset); DateTimeFormatter f = new DateTimeFormatterBuilder().appendLocalizedOffset(style).toFormatter(locale); assertEquals(f.format(odt), expected); assertEquals(f.format(zdt), expected); assertEquals(f.parse(expected, ZoneOffset::from), offset); if (style == TextStyle.FULL) { f = new DateTimeFormatterBuilder().appendPattern("ZZZZ").toFormatter(locale); assertEquals(f.format(odt), expected); assertEquals(f.format(zdt), expected); assertEquals(f.parse(expected, ZoneOffset::from), offset); f = new DateTimeFormatterBuilder().appendPattern("OOOO").toFormatter(locale); assertEquals(f.format(odt), expected); assertEquals(f.format(zdt), expected); assertEquals(f.parse(expected, ZoneOffset::from), offset); } if (style == TextStyle.SHORT) { f = new DateTimeFormatterBuilder().appendPattern("O").toFormatter(locale); assertEquals(f.format(odt), expected); assertEquals(f.format(zdt), expected); assertEquals(f.parse(expected, ZoneOffset::from), offset); } } }
gompus/gompus
models/gateway/events/integration.go
package events import ( "github.com/gompus/gompus/models/guild/integration" "github.com/gompus/snowflake" ) // IntegrationCreateEvent is the event sent when an integration is created. type IntegrationCreateEvent struct { integration.Integration // GuildID is the id of the guild for which the integration was created. GuildID snowflake.Snowflake `json:"guild_id,omitempty"` } // IntegrationUpdateEvent is the event sent when an integration is updated. type IntegrationUpdateEvent struct { integration.Integration // GuildID is the id of the guild for which the integration was updated. GuildID snowflake.Snowflake `json:"guild_id,omitempty"` } // IntegrationDeleteEvent is the event sent when an integration is deleted. type IntegrationDeleteEvent struct { // ID is the id of the deleted integration. ID snowflake.Snowflake `json:"id,omitempty"` // GuildID is the id of the guild for which the integration was deleted. GuildID snowflake.Snowflake `json:"guild_id,omitempty"` // ApplicationID is the id of the bot/OAuth2 // application associated with the integration. ApplicationID snowflake.Snowflake `json:"application_id,omitempty"` }
hepingood/bmp388
doc/html/driver__bmp388__register__test_8c.js
<reponame>hepingood/bmp388 var driver__bmp388__register__test_8c = [ [ "bmp388_register_test", "group__bmp388__test__driver.html#ga1b2fb20362f53dcf2392bb517529dd3e", null ] ];
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
argouml/org/argouml/uml/ui/UMLClassifierListModel.java
<gh_stars>10-100 // Copyright (c) 1996-2001 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.uml.ui; import ru.novosoft.uml.*; import javax.swing.*; import ru.novosoft.uml.foundation.core.*; import java.util.*; import java.awt.*; import java.lang.reflect.*; public class UMLClassifierListModel extends UMLModelElementCachedListModel { final private static String _nullLabel = "null"; private java.util.List _classes; private Class _classifierType; private Class _implClass; public UMLClassifierListModel(UMLUserInterfaceContainer container,String property,boolean showNone,Class classifierType,Class implClass) { super(container,property,showNone); _classifierType = classifierType; _implClass = implClass; } protected void resetCache() { _classes = null; } public boolean isProperClass(Object obj) { return _classifierType.isInstance(obj); } public Collection getRawCollection() { Collection raw = null; Object target = getTarget(); if(target instanceof MNamespace) { raw = ((MNamespace) target).getOwnedElements(); } return raw; } protected java.util.List getCache() { if(_classes == null) { _classes = buildCache(); } return _classes; } public void add(int index) { Object target = getTarget(); if(target instanceof MNamespace) { MNamespace namespace = (MNamespace) target; MClassifier newClass = null; try { Class[] noClasses = {}; Constructor constructor = _implClass.getConstructor(noClasses); Object[] noArgs = {}; newClass = (MClassifier) constructor.newInstance(noArgs); newClass.setNamespace(namespace); int oldSize = getModelElementSize(); namespace.addOwnedElement(newClass); if(_classes != null) { _classes.add(newClass); } fireIntervalAdded(this,oldSize,oldSize); navigateTo(newClass); } catch(Exception e) { System.out.println(e.toString() + " in UMLClassifierListModel.add()"); } } } public void delete(int index) { Object target = getTarget(); if(target instanceof MNamespace && _classes != null) { Object clas = _classes.get(index); if(clas != null) { _classes.remove(index); ((MNamespace) target).removeOwnedElement((MClassifier) clas); resetSize(); fireIntervalRemoved(this,index,index); } } } public boolean buildPopup(JPopupMenu popup,int index) { UMLUserInterfaceContainer container = getContainer(); UMLListMenuItem open = new UMLListMenuItem(container.localize("Open"),this,"open",index); UMLListMenuItem delete = new UMLListMenuItem(container.localize("Delete"),this,"delete",index); if(getModelElementSize() <= 0) { open.setEnabled(false); delete.setEnabled(false); } popup.add(open); popup.add(new UMLListMenuItem(container.localize("Add"),this,"add",index)); popup.add(delete); return true; } java.util.Collection createCollection(int initialSize) { return new TreeSet(new UMLClassifierNameComparator()); } }
ericdriggs/ragnarok
reportcard-server/src/generated/java/io/github/ericdriggs/reportcard/gen/db/tables/records/BranchRecord.java
/* * This file is generated by jOOQ. */ package io.github.ericdriggs.reportcard.gen.db.tables.records; import io.github.ericdriggs.reportcard.gen.db.tables.Branch; import javax.annotation.processing.Generated; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record3; import org.jooq.Row3; import org.jooq.impl.UpdatableRecordImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "https://www.jooq.org", "jOOQ version:3.14.9" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes", "javadoc" }) public class BranchRecord extends UpdatableRecordImpl<BranchRecord> implements Record3<Integer, String, Integer> { private static final long serialVersionUID = 1L; /** * Setter for <code>reportcard.branch.branch_id</code>. */ public BranchRecord setBranchId(Integer value) { set(0, value); return this; } /** * Getter for <code>reportcard.branch.branch_id</code>. */ public Integer getBranchId() { return (Integer) get(0); } /** * Setter for <code>reportcard.branch.branch_name</code>. */ public BranchRecord setBranchName(String value) { set(1, value); return this; } /** * Getter for <code>reportcard.branch.branch_name</code>. */ public String getBranchName() { return (String) get(1); } /** * Setter for <code>reportcard.branch.repo_fk</code>. */ public BranchRecord setRepoFk(Integer value) { set(2, value); return this; } /** * Getter for <code>reportcard.branch.repo_fk</code>. */ public Integer getRepoFk() { return (Integer) get(2); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record3 type implementation // ------------------------------------------------------------------------- @Override public Row3<Integer, String, Integer> fieldsRow() { return (Row3) super.fieldsRow(); } @Override public Row3<Integer, String, Integer> valuesRow() { return (Row3) super.valuesRow(); } @Override public Field<Integer> field1() { return Branch.BRANCH.BRANCH_ID; } @Override public Field<String> field2() { return Branch.BRANCH.BRANCH_NAME; } @Override public Field<Integer> field3() { return Branch.BRANCH.REPO_FK; } @Override public Integer component1() { return getBranchId(); } @Override public String component2() { return getBranchName(); } @Override public Integer component3() { return getRepoFk(); } @Override public Integer value1() { return getBranchId(); } @Override public String value2() { return getBranchName(); } @Override public Integer value3() { return getRepoFk(); } @Override public BranchRecord value1(Integer value) { setBranchId(value); return this; } @Override public BranchRecord value2(String value) { setBranchName(value); return this; } @Override public BranchRecord value3(Integer value) { setRepoFk(value); return this; } @Override public BranchRecord values(Integer value1, String value2, Integer value3) { value1(value1); value2(value2); value3(value3); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached BranchRecord */ public BranchRecord() { super(Branch.BRANCH); } /** * Create a detached, initialised BranchRecord */ public BranchRecord(Integer branchId, String branchName, Integer repoFk) { super(Branch.BRANCH); setBranchId(branchId); setBranchName(branchName); setRepoFk(repoFk); } }
mrouhi13/my-mit-python-practice
MIT/ps3_template.py
<filename>MIT/ps3_template.py from string import * # this is a code file that you can use as a template for submitting your # solutions # these are some example strings for use in testing your code # target strings target1 = 'atgacatgcacaagtatgcat' target2 = 'atgaatgcatggatgtaaatgcag' # key strings key10 = 'a' key11 = 'atg' key12 = 'atgc' key13 = 'atgca' ### the following procedure you will use in Problem 3 def subStringMatchOneSub(key,target): """search for all locations of key in target, with one substitution""" allAnswers = () for miss in range(0,len(key)): # miss picks location for missing element # key1 and key2 are substrings to match key1 = key[:miss] key2 = key[miss+1:] print 'breaking key',key,'into',key1,key2 # match1 and match2 are tuples of locations of start of matches # for each substring in target match1 = subStringMatchExact(target,key1) match2 = subStringMatchExact(target,key2) # when we get here, we have two tuples of start points # need to filter pairs to decide which are correct filtered = constrainedMatchPair(match1,match2,len(key1)) allAnswers = allAnswers + filtered print 'match1',match1 print 'match2',match2 print 'possible matches for',key1,key2,'start at',filtered return allAnswers
kaolalib/kaola
httpserver/src/main/java/org/grain/httpserver/FileHttpFilter.java
<filename>httpserver/src/main/java/org/grain/httpserver/FileHttpFilter.java package org.grain.httpserver; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.servlet.ServletRequestContext; public class FileHttpFilter implements IHttpFilter { private String tempPath; private DiskFileItemFactory diskFileItemFactory; /** * 初始化缓存文件夹 */ public FileHttpFilter() { tempPath = HttpConfig.PROJECT_PATH + "/" + HttpConfig.PROJECT_NAME + "_TEMP"; if (HttpConfig.log != null) { HttpConfig.log.info("缓存文件路径为:" + tempPath); } File file = new File(tempPath); if (!file.exists()) { file.mkdirs(); } diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(1024); diskFileItemFactory.setRepository(file); } /** * 解析from表单类型的 */ @Override public boolean httpFilter(HttpPacket httpPacket) { // 是表单类型的 if (ServletFileUpload.isMultipartContent(httpPacket.hSession.request)) { // 设置已经用表单方式解析,不需要后续进行json解析 httpPacket.isFromAnalysis = true; IUploadProgress uploadProgress = null; try { // 进度类 if (HttpConfig.UPLOAD_PROGRESS_CLASS != null) { uploadProgress = HttpConfig.UPLOAD_PROGRESS_CLASS.newInstance(); uploadProgress.init(httpPacket.hSession.headParam.fileUuid); } ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setSizeMax(1024 * 1024 * 1024 * 1024L); ServletRequestContext servletRequestContext = new ServletRequestContext(httpPacket.hSession.request); if (uploadProgress != null) { servletFileUpload.setProgressListener(uploadProgress); } // 解析 List<FileItem> list = servletFileUpload.parseRequest(servletRequestContext); if (list == null || list.size() == 0) { if (HttpConfig.log != null) { HttpConfig.log.warn("解析的文件个数为0,未解析出文件,请查问题"); } return false; } List<FileData> fileList = new ArrayList<FileData>(); for (FileItem fileItem : list) { // 文件 if (!fileItem.isFormField()) { String name = fileItem.getName(); int postfixIndex = name.lastIndexOf("."); String newName; if (postfixIndex != -1) { String postfix = name.substring(postfixIndex); newName = UUID.randomUUID().toString().trim().replaceAll("-", "") + postfix; } else { newName = UUID.randomUUID().toString().trim().replaceAll("-", ""); } // 保存上传文件 File file = new File(tempPath, newName); fileItem.write(file); FileData fileData = new FileData(file, name); fileList.add(fileData); } else { // 参数 String name = fileItem.getFieldName(); String value = fileItem.getString(); // 找关键字 if (value != null && !value.equals("")) { if (name.equals(AllowParam.HOPCODE)) { httpPacket.hSession.headParam.hOpCode = value; } else if (name.equals(AllowParam.TOKEN)) { httpPacket.hSession.headParam.token = value; } else if (name.equals(AllowParam.FILE_UUID)) { httpPacket.hSession.headParam.fileUuid = value; } else if (name.equals(AllowParam.PACKET)) { httpPacket.hSession.headParam.packet = value; } httpPacket.hSession.headParam.parameterParam.put(name, value); } } } // 上传完成 httpPacket.fileList = fileList; if (uploadProgress != null) { uploadProgress.finish(); } httpPacket.putMonitor("读取文件流完成"); return true; } catch (Exception e) { if (uploadProgress != null) { uploadProgress.fail(); } if (HttpConfig.log != null) { HttpConfig.log.error("上传文件异常", e); } httpPacket.putMonitor("读取文件流失败"); return false; } } return true; } }
WilSenwish/zipkin
zipkin-server/src/main/java/zipkin2/server/internal/prometheus/ZipkinMetricsController.java
/* * Copyright 2015-2019 The OpenZipkin 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 zipkin2.server.internal.prometheus; import com.fasterxml.jackson.core.JsonGenerator; import com.linecorp.armeria.common.HttpResponse; import com.linecorp.armeria.common.HttpStatus; import com.linecorp.armeria.common.MediaType; import com.linecorp.armeria.server.annotation.Get; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.Meter; import io.micrometer.core.instrument.MeterRegistry; import io.prometheus.client.CollectorRegistry; import java.io.IOException; import java.io.StringWriter; import zipkin2.server.internal.JsonUtil; public class ZipkinMetricsController { final MeterRegistry meterRegistry; final CollectorRegistry collectorRegistry; ZipkinMetricsController(MeterRegistry meterRegistry, CollectorRegistry collectorRegistry) { this.meterRegistry = meterRegistry; this.collectorRegistry = collectorRegistry; } // Extracts Zipkin metrics to provide backward compatibility @Get("/metrics") public HttpResponse fetchMetricsFromMicrometer() throws IOException { StringWriter writer = new StringWriter(); JsonGenerator generator = JsonUtil.createGenerator(writer); generator.writeStartObject(); // Get the Zipkin Custom meters for constructing the Metrics endpoint for (Meter meter : meterRegistry.getMeters()) { String name = meter.getId().getName(); if (!name.startsWith("zipkin_collector")) continue; String transport = meter.getId().getTag("transport"); if (transport == null) continue; Meter.Type type = meter.getId().getType(); if (type == Meter.Type.COUNTER) { generator.writeNumberField("counter." + name + "." + transport, ((Counter) meter).count()); } else if (type == Meter.Type.GAUGE) { generator.writeNumberField("gauge." + name + "." + transport, ((Gauge) meter).value()); } // We only use counters and gauges } generator.writeEndObject(); generator.flush(); // instead of using try/finally as extra indent causes lines to wrap return HttpResponse.of(HttpStatus.OK, MediaType.JSON, writer.toString()); } }
netrek/netrek-client-mactrek
netrek-server-vanilla/ntserv/phaser.c
<gh_stars>0 /* * phaser.c */ #include "copyright.h" #include <stdio.h> #include <math.h> #include <signal.h> #include <stdlib.h> #include <time.h> #include <sys/types.h> #include <unistd.h> #include "defs.h" #include "struct.h" #include "data.h" #include "packets.h" #include "proto.h" #include "ltd_stats.h" #include "util.h" void phaser(u_char course) { struct player *j, *target_player = NULL; struct torp *t, *target_plasma = NULL; int pstatus; double s, C,D; LONG A,B, E,F; LONG dx, dy, myphrange, range; U_LONG range_sq, this_range_sq; struct phaser *mine = &phasers[me->p_no]; if (status->gameup & GU_CONQUER) return; if (mine->ph_status != PHFREE) { new_warning(32, "Phasers have not recharged."); return; } if (me->p_fuel < myship->s_phasercost) { new_warning(33, "Not enough fuel for phaser."); return; } if (me->p_flags & PFREPAIR) { new_warning(34, "Can't fire while repairing."); return; } if (me->p_flags & PFWEP) { new_warning(35, "Weapons overheated"); if (!chaosmode) return; } /***** The following should really test a ship attribute, not type. */ if ((me->p_cloakphase) && (me->p_ship.s_type != ATT)) { new_warning(36, "Cannot fire while cloaked"); return; } if (myship->s_phasercost < 0) { new_warning(31, "Weapons Officer: This ship is not armed with phasers, captain!"); return; } /* * (C, D) is a point on the my phaser line, relative to me. It * doesn't matter what point is used, so long as it is reasonably * far from me (to prevent round-off error problems). */ C = Cos[course]*10*PHASEDIST; D = Sin[course]*10*PHASEDIST; /* * Establish necessary preconditions for for-loops: */ myphrange = (PHASEDIST * me->p_ship.s_phaserdamage) / 100; range = myphrange + 1; range_sq = myphrange*myphrange + 1; pstatus = PHMISS; /* * See if phaser hit a player: */ for (j = firstPlayer; j <= lastPlayer; j++) { /* * Don't check dead players or me: */ if ((j->p_status != PALIVE) || (j == me)) continue; /* * Make sure we are not mutually at peace: */ if ((!(j->p_war & me->p_team)) && (!(me->p_war & j->p_team))) continue; /* Idle ships cannot be phasered */ if (is_idle(j)) continue; /* * (A, B) is the position of the possible target relative to me. */ A = j->p_x - me->p_x; /* * Make sure (A,B) is close enough to me to probably be in * my phaser range. (I am at (0,0).) */ if ((A >= range) || (A <= -range)) continue; B = j->p_y - me->p_y; if ((B >= range) || (B <= -range)) continue; /* * Possibly close enough for a hit. * Check to make sure this target is closer to me than the current * target. This is also the exact check for phaser range, because * we initialized range_sq to 1+myphrange^2 */ this_range_sq = A*A + B*B; if (range_sq <= this_range_sq) continue; /* * The criterion for netrek phaser hits is that the phaser line * is within an arc such that it passes through the circle with * radius ZAPPLAYERDIST centered on the target. This is equivalanet * to determining if (E,F), the point on the phaser line nearest * the target, is within ZAPPLAYERDIST of the target. */ /* * Parametrically determine (E,F) * Here is a sketch of how s is derived: * We have two unknowns: E and F. But we have two equations that * relate them: * (1) the slope of vector [C,D] has to be equal to the negative * reciprical of the slope of [A-E,B-F] * (2) [E,F] = s * [C,D] * From (2) we derive the expression E=(F*C)/D. We then plug that * into the equation derived from one. Then, solve for F. * The resulting equation is * F = D * (A*C + B*D) / (C^2 * D^2) * One last step is to recall [C,D] has a constant length. */ s = (A*C + B*D) / (10.0*PHASEDIST * 10.0*PHASEDIST); if (s < 0) /* KOC 12/95 - hack to stop 180 phaser bug */ s = 0; /* If enemy ship overlaps ship - autotarget it */ E = (LONG) (C * s); /* * Check if (E,F) is probably close enough to (A,B) for a hit: */ dx = E - A; if ((dx > ZAPPLAYERDIST) || (dx < -ZAPPLAYERDIST)) continue; F = (LONG) (D * s); dy = F - B; if ((dy > ZAPPLAYERDIST) || (dy < -ZAPPLAYERDIST)) continue; /* * Probably close enough. * Now the circular range check: */ if (dx*dx + dy*dy <= ZAPPLAYERDIST*ZAPPLAYERDIST) { /* A hit! */ pstatus = PHHIT; target_player = j; /* * Adjust range and range_sq in order to narrow the search area * for later hit checks. */ range_sq = this_range_sq; range = rint(sqrt((double)range_sq)); } } /* See if the phaser hit a plasma torpedo: */ for (t = firstPlasma; t <= lastPlasma; t++) { /* Don't check non-plasmas or my plasmas: */ if ((t->t_status != TMOVE) || (t->t_owner == me->p_no)) continue; if (!pingpong_plasma) { /* Dont check if in pingpong plasma mode */ if ((!(t->t_war & me->p_team)) && (!(me->p_war & t->t_team))) continue; } /* * The code that checks for player hits (above) is practically * identical to this code. So read the comments up there if you * want to know what is going on down here. */ A = t->t_x - me->p_x; if ((A >= range) || (A <= -range)) continue; B = t->t_y - me->p_y; if ((B >= range) || (B <= -range)) continue; this_range_sq = A*A + B*B; if (range_sq <= this_range_sq) continue; s = (A*C + B*D) / (10.0*PHASEDIST * 10.0*PHASEDIST); if (s < 0) /* KOC 12/95 - hack to stop 180 phaser bug */ continue; E = (LONG) (C * s); dx = E - A; if ((dx > ZAPPLASMADIST) || (dx < -ZAPPLASMADIST)) continue; F = (LONG) (D * s); dy = F - B; if ((dy > ZAPPLASMADIST) || (dy < -ZAPPLASMADIST)) continue; if (dx*dx + dy*dy <= ZAPPLASMADIST*ZAPPLASMADIST) { pstatus = PHHIT2; target_plasma = t; range_sq = this_range_sq; range = rint(sqrt((double)range_sq)); } } /* * Adjust my phaser and me to reflect new conditions. */ mine->ph_status = pstatus; mine->ph_dir = course; mine->ph_fuse = me->p_ship.s_phaserfuse; me->p_fuel -= myship->s_phasercost; me->p_wtemp += myship->s_phasercost / 10; #ifdef LTD_STATS /* Phaser was fired at this point */ ltd_update_phaser_fired(me); #endif if (pstatus == PHMISS) { #ifdef STURGEON /* s_phaserdamage varies, which varies end coordinate of a phaser miss, so we must calculate the coordinate */ if (sturgeon) { mine->ph_x = me->p_x + (int) (PHASEDIST * me->p_ship.s_phaserdamage / 100 * Cos[course]); mine->ph_y = me->p_y + (int) (PHASEDIST * me->p_ship.s_phaserdamage / 100 * Sin[course]); } #endif new_warning(37, "Phaser missed."); return; } #ifdef LTD_STATS /* Phaser either hit a player or hit plasma, give credit for both cases */ ltd_update_phaser_hit(me); #endif if (pstatus == PHHIT) { mine->ph_target = target_player->p_no; mine->ph_damage = me->p_ship.s_phaserdamage * (1.0 - range / ((double) (myphrange))); #ifdef LTD_STATS /* update phaser damage for shooter and victim */ ltd_update_phaser_damage(me, target_player, mine->ph_damage); #endif if (send_short && (target_player->p_no < 64) && (mine->ph_damage < 1024)) { swarning(PHASER_HIT_TEXT, (target_player->p_no & 0x3f) | ((mine->ph_damage & 768) >> 2), (unsigned char) mine->ph_damage & 0xff); return; } new_warning(UNDEF, "Phaser burst hit %s for %d points", target_player->p_name, mine->ph_damage); return; } /* pstatus == PHHIT2 */ { #ifdef LTD_STATS /* phaser hit plasma */ ltd_update_plasma_phasered(&(players[target_plasma->t_owner])); #endif if (pingpong_plasma) { mine->ph_damage = me->p_ship.s_phaserdamage * (1.0-((float) range/(float) myphrange)); if ((target_plasma->t_war & me->p_team) || (me->p_hostile & target_plasma->t_team)) { int rand_plasmadir; int rand_plasmaturns; mine->ph_x = target_plasma->t_x; mine->ph_y = target_plasma->t_y; mine->ph_status = PHHIT2; target_plasma->t_damage+=mine->ph_damage/4; target_plasma->t_gspeed+=mine->ph_damage/100; srandom(getpid() * time((time_t *) 0)); rand_plasmadir = random() % 9; rand_plasmaturns = random() % 9; if (rand_plasmadir < 8) rand_plasmadir = 128; else rand_plasmadir = 80; if (rand_plasmaturns < 7) target_plasma->t_turns++; target_plasma->t_dir = (target_plasma->t_dir+rand_plasmadir)%256; players[target_plasma->t_owner].p_nplasmatorp--; target_plasma->t_owner=me->p_no; me->p_nplasmatorp++; target_plasma->t_team=me->p_team; target_plasma->t_war=me->p_hostile; target_plasma->t_fuse+=(mine->ph_damage * .25 + 5) * T_FUSE_SCALE; new_warning(UNDEF, "Ping-Pong!"); } else { mine->ph_x = target_plasma->t_x; mine->ph_y = target_plasma->t_y; mine->ph_status = PHHIT2; target_plasma->t_damage+=mine->ph_damage; target_plasma->t_gspeed+=mine->ph_damage/100; target_plasma->t_turns++; target_plasma->t_dir = me->p_dir; players[target_plasma->t_owner].p_nplasmatorp--; target_plasma->t_owner=me->p_no; me->p_nplasmatorp++; target_plasma->t_team=me->p_team; target_plasma->t_war=me->p_hostile; target_plasma->t_fuse+=(mine->ph_damage * .25 + 5) * T_FUSE_SCALE; new_warning(UNDEF, "You deflected the plasma!"); } } if (!pingpong_plasma) { mine->ph_x = target_plasma->t_x; mine->ph_y = target_plasma->t_y; target_plasma->t_status = TDET; target_plasma->t_whodet = me->p_no; new_warning(38, "You destroyed the plasma torpedo!"); } } }
tterem/Resteasy
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/core/servlet/resource/UndertowServlet.java
package org.jboss.resteasy.test.core.servlet.resource; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import java.io.IOException; public class UndertowServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { RequestDispatcher dispatcher = req.getRequestDispatcher("/forward"); try { dispatcher.forward(req, res); } catch (Exception e) { throw new RuntimeException(e); } } }
polarpathgames/Polar-Path
Final_Fantasy_Mystery_World/Final_Fantasy_Mystery_World/p2PerfTimer.cpp
// ---------------------------------------------------- // p2PerfTimer.cpp // Slow timer with microsecond precision // ---------------------------------------------------- #include "p2PerfTimer.h" #include "SDL\include\SDL_timer.h" uint64 p2PerfTimer::frequency = 0; // --------------------------------------------- p2PerfTimer::p2PerfTimer() { if(frequency == 0) frequency = SDL_GetPerformanceFrequency(); Start(); } // --------------------------------------------- void p2PerfTimer::Start() { started_at = SDL_GetPerformanceCounter(); } // --------------------------------------------- double p2PerfTimer::ReadMs() const { return 1000.0 * (double(SDL_GetPerformanceCounter() - started_at) / double(frequency)); } // --------------------------------------------- uint64 p2PerfTimer::ReadTicks() const { return SDL_GetPerformanceCounter() - started_at; } double p2PerfTimer::StartedAt() { return started_at; }
yannikbehr/seiscomp3
src/seedlink/plugins/libgcf2-2.3.2/examples/g2ints.c
/* * g2ints.c: * * examples of how to use the endian-aware non-aligned * integer functions. * * Copyright (c) 2004 Guralp Systems Limited * Author <NAME>, contact <<EMAIL>> * 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ static char rcsid[] = "$Id: g2ints.c,v 1.1 2004/05/01 23:46:03 root Exp $"; /* * $Log: g2ints.c,v $ * Revision 1.1 2004/05/01 23:46:03 root * *** empty log message *** * */ #include <gcf2.h> /* libgcf2 makes sure that all the usual integer types are defined */ /* (u)int8/16/32, and provides these utility functions to convert */ /* between the unaligned network byte order that GCF uses and */ /* the host's integer types */ int main (int argc, char *argv[]) { printf ("%s\n", rcsid); { uint8_t buf[] = { 0x81 }; int val; val = G2uint8 (buf); printf ("G2uint8(0x81)=%d (%x)\n", val, val); val = G2int8 (buf); printf ("G2int8(0x81)=%d\n", val); } { uint8_t buf[] = { 0x81, 0x02 }; int val; val = G2uint16 (buf); printf ("G2uint16(0x81,0x02)=%d (%x)\n", val, val); val = G2int16 (buf); printf ("G2int16(0x81,0x02)=%d\n", val); } { uint8_t buf[] = { 0x81, 0x02, 0x03 }; int val; val = G2uint24 (buf); printf ("G2uint24(0x81,0x02,0x03)=%d (%x)\n", val, val); val = G2int24 (buf); printf ("G2int24(0x81,0x02,0x03)=%d\n", val); } { uint8_t buf[] = { 0x81, 0x02, 0x03, 0x04 }; int val; unsigned int uval; uval = G2uint32 (buf); printf ("G2uint32(0x81,0x02,0x03,0x04)=%u (%x)\n", uval, uval); val = G2int32 (buf); printf ("G2int32(0x81,0x02,0x03,0x04)=%d\n", val); } return 0; }
ratchapol-an/autorest
PackageTest/Generated/NodeJS/models/index.js
<gh_stars>10-100 /* jshint latedef:false */ /* jshint forin:false */ /* jshint noempty:false */ 'use strict'; exports.ErrorModel = require('./ErrorModel');
wandisuh/wiploo
public/assets/frontend/assets/node_modules/jit-grunt/lib/jit-grunt.js
'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var fs = require('fs'); var path = require('path'); var PREFIXES = ['', 'grunt-', 'grunt-contrib-']; var EXTENSIONS = ['.coffee', '.js']; var jit = { pluginsRoot: 'node_modules', mappings: {}, cwd: process.cwd() }; jit.findUp = function (cwd, iterator) { var result = iterator(cwd); if (result) { return result; } var parent = path.resolve(cwd, '..'); return parent !== cwd ? jit.findUp(parent, iterator) : null; }; jit.findPlugin = function (taskName) { var _this = this; var pluginName = undefined, taskPath = undefined; // Static Mappings if (this.mappings.hasOwnProperty(taskName)) { pluginName = this.mappings[taskName]; if (pluginName.indexOf('/') >= 0 && pluginName.indexOf('@') !== 0) { taskPath = path.resolve(this.cwd, pluginName); if (fs.existsSync(taskPath)) { return this.loadPlugin(taskName, taskPath, true); } } else { var _ret = function () { var dir = path.join(_this.pluginsRoot, pluginName, 'tasks'); taskPath = _this.findUp(_this.cwd, function (cwd) { var findPath = path.join(cwd, dir); return fs.existsSync(findPath) ? findPath : null; }); if (taskPath) { return { v: _this.loadPlugin(pluginName, taskPath) }; } }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } } // Custom Tasks if (this.customTasksDir) { for (var i = EXTENSIONS.length; i--;) { taskPath = path.join(this.customTasksDir, taskName + EXTENSIONS[i]); if (fs.existsSync(taskPath)) { return this.loadPlugin(taskName, taskPath, true); } } } // Auto Mappings var dashedName = taskName.replace(/([A-Z])/g, '-$1').replace(/_+/g, '-').toLowerCase(); taskPath = this.findUp(this.cwd, function (cwd) { for (var p = PREFIXES.length; p--;) { pluginName = PREFIXES[p] + dashedName; var findPath = path.join(cwd, _this.pluginsRoot, pluginName, 'tasks'); if (fs.existsSync(findPath)) { return findPath; } } }); if (taskPath) { return this.loadPlugin(pluginName, taskPath); } this.grunt.log.writeln(('\njit-grunt: Plugin for the "' + taskName + '" task not found.\nIf you have installed the plugin already, please setting the static mapping.\nSee').yellow, 'https://github.com/shootaroo/jit-grunt#static-mappings\n'.cyan); }; jit.loadPlugin = function (name, path, isFile) { var grunt = this.grunt; var _write = grunt.log._write; var _nameArgs = grunt.task.current.nameArgs; grunt.task.current.nameArgs = 'loading ' + name; if (this.hideHeader) { grunt.log._write = function () {}; } grunt.log.header('Loading "' + name + '" plugin'); grunt.log._write = _write; if (isFile) { var fn = require(path); if (typeof fn === 'function') { fn.call(grunt, grunt); } } else { grunt.loadTasks(path); } grunt.task.current.nameArgs = _nameArgs; }; jit.proxy = function (name) { return { task: { name: name, fn: function fn() { var thing = jit._taskPlusArgs.call(jit.grunt.task, name); if (!thing.task) { jit.findPlugin(thing.args[0]); thing = jit._taskPlusArgs.call(jit.grunt.task, name); if (!thing.task) { return new Error('Task "' + name + '" failed.'); } } this.nameArgs = thing.nameArgs; this.name = thing.task.name; this.args = thing.args; this.flags = thing.flags; return thing.task.fn.apply(this, this.args); } }, nameArgs: name, args: null, flags: null }; }; module.exports = function (grunt, mappings) { if (!jit.grunt) { jit.grunt = grunt; jit.hideHeader = !grunt.option('verbose'); // Override _taskPlusArgs jit._taskPlusArgs = grunt.util.task.Task.prototype._taskPlusArgs; grunt.util.task.Task.prototype._taskPlusArgs = jit.proxy; } for (var key in mappings) { if (mappings.hasOwnProperty(key)) { jit.mappings[key] = mappings[key]; } } return jit; };
hockbene/motis
modules/path/test/aggregate_osm_ways_test.cc
#include "gtest/gtest.h" #include "utl/to_vec.h" #include "utl/verify.h" #include "motis/path/prepare/osm/osm_way.h" namespace mp = motis::path; mp::osm_way make_way(mcd::vector<int64_t> const& ids, mp::source_bits const sb) { utl::verify(ids.size() >= 2, "make_ways: invalid input"); mp::osm_path path{ids.size()}; path.osm_node_ids_ = ids; path.polyline_.resize(ids.size()); return mp::osm_way{{0}, sb, std::move(path)}; } mcd::vector<mp::osm_way> make_ways(mcd::vector<mcd::vector<int64_t>> const& in, bool oneway = false) { return mcd ::to_vec(in, [&](auto const& ids) { return make_way( ids, oneway ? mp::source_bits::ONEWAY : mp::source_bits::NO_SOURCE); }); } #define COUNT_WAY(vec, from_expected, to_expected) \ (std::count_if(begin(vec), end(vec), [](auto const& e) { \ return (e.from() == (from_expected) && e.to() == (to_expected)) || \ (e.from() == (to_expected) && e.to() == (from_expected)); \ })) TEST(aggregate_osm_ways, pairwise) { { auto input = make_ways({{0, 1}, {2, 3}}); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(make_ways({{0, 1}, {2, 3}}), output); EXPECT_EQ(mp::source_bits::NO_SOURCE, output[0].source_bits_); } { auto input = make_ways({{0, 1}, {1, 2}}); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(1, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 0, 2)); } { auto input = make_ways({{0, 1}, {2, 1}}); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(1, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 0, 2)); } { auto input = make_ways({{1, 0}, {1, 2}}); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(1, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 0, 2)); } { auto input = make_ways({{1, 0}, {2, 1}}); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(1, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 0, 2)); } } TEST(aggregate_osm_ways, pairwise_oneway) { { auto input = make_ways({{0, 1}, {1, 2}}, true); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(1, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 0, 2)); EXPECT_EQ(mp::source_bits::ONEWAY, output[0].source_bits_); } { auto input = make_ways({{0, 1}, {2, 1}}, true); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(2, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 0, 1)); EXPECT_EQ(1, COUNT_WAY(output, 2, 1)); EXPECT_EQ(mp::source_bits::ONEWAY, output[0].source_bits_); EXPECT_EQ(mp::source_bits::ONEWAY, output[1].source_bits_); } { auto input = make_ways({{1, 0}, {1, 2}}, true); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(2, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 1, 0)); EXPECT_EQ(1, COUNT_WAY(output, 1, 2)); EXPECT_EQ(mp::source_bits::ONEWAY, output[0].source_bits_); EXPECT_EQ(mp::source_bits::ONEWAY, output[1].source_bits_); } { auto input = make_ways({{1, 0}, {2, 1}}, true); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(1, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 0, 2)); EXPECT_EQ(mp::source_bits::ONEWAY, output[0].source_bits_); } } TEST(aggregate_osm_ways, pairwise_source_bits) { { auto input = mcd::vector<mp::osm_way>{make_way({0, 1}, mp::source_bits::RAIL), make_way({2, 1}, mp::source_bits::TRAM)}; auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(2, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 1, 0)); EXPECT_EQ(1, COUNT_WAY(output, 1, 2)); EXPECT_EQ(input[output[0].from() == 0 ? 0 : 1].source_bits_, output[0].source_bits_); EXPECT_EQ(input[output[1].from() == 2 ? 1 : 0].source_bits_, output[1].source_bits_); } { auto input = mcd::vector<mp::osm_way>{ make_way({0, 1}, mp::source_bits::RAIL | mp::source_bits::ONEWAY), make_way({2, 1}, mp::source_bits::RAIL | mp::source_bits::ONEWAY)}; auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(2, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 1, 0)); EXPECT_EQ(1, COUNT_WAY(output, 1, 2)); EXPECT_EQ(mp::source_bits::RAIL | mp::source_bits::ONEWAY, output[0].source_bits_); EXPECT_EQ(mp::source_bits::RAIL | mp::source_bits::ONEWAY, output[0].source_bits_); } } TEST(aggregate_osm_ways, three_star) { { auto input = make_ways({{0, 3}, {1, 3}, {2, 3}}); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(3, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 0, 3)); EXPECT_EQ(1, COUNT_WAY(output, 1, 3)); EXPECT_EQ(1, COUNT_WAY(output, 2, 3)); } { auto input = make_ways({{0, 3}, {1, 3}, {2, 3}, {2, 4}}); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(3, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 0, 3)); EXPECT_EQ(1, COUNT_WAY(output, 1, 3)); EXPECT_EQ(1, COUNT_WAY(output, 4, 3)); } } TEST(aggregate_osm_ways, loop) { { auto input = make_ways({{1, 0}, // {2, 1}, // {3, 2}, // loop part 1 {3, 2}, // loop part 2 {4, 2}, // {5, 4}, // {5, 6}}); auto output = mp::aggregate_osm_ways(input); ASSERT_EQ(3, output.size()); EXPECT_EQ(1, COUNT_WAY(output, 0, 2)); EXPECT_EQ(1, COUNT_WAY(output, 2, 2)); // the loop EXPECT_EQ(1, COUNT_WAY(output, 2, 6)); } }
guoshucan/mpaas
ghost.framework.data.mongodb/src/main/java/ghost/framework/data/mongodb/core/aggregation/Field.java
<filename>ghost.framework.data.mongodb/src/main/java/ghost/framework/data/mongodb/core/aggregation/Field.java<gh_stars>1-10 /* * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 ghost.framework.data.mongodb.core.aggregation; /** * Abstraction for a field. * * @author <NAME> * @since 1.3 */ public interface Field { /** * Returns the name of the field. * * @return must not be {@literal null}. */ String getName(); /** * Returns the target of the field. In case no explicit target is available {@link #getName()} should be returned. * * @return must not be {@literal null}. */ String getTarget(); /** * Returns whether the Field is aliased, which means it has a name set different from the target. * * @return */ boolean isAliased(); /** * @return true if the field name references a local value such as {@code $$this}. * @since 2.2 */ default boolean isInternal() { return false; } }
AkshatSh/iSeqL
iseql_front_end/src/components/labeling/surprising_labels.js
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import ListItem from '@material-ui/core/ListItem'; import Typography from '@material-ui/core/Typography'; import List from '@material-ui/core/List'; import Divider from '@material-ui/core/Divider'; import ListItemText from '@material-ui/core/ListItemText'; import blueGrey from '@material-ui/core/colors/blueGrey'; import Tooltip from '@material-ui/core/Tooltip'; import IconButton from '@material-ui/core/IconButton'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@material-ui/core/MenuItem'; import MoreVertIcon from '@material-ui/icons/MoreVert'; import ArrowUpward from '@material-ui/icons/ArrowUpward'; import ArrowDownward from '@material-ui/icons/ArrowDownward'; // import NewReleasesOutlined from '@material-ui/icons/NewReleasesOutlined'; import Select from '@material-ui/core/Select'; import FiberNewOutlined from '@material-ui/icons/FiberNewOutlined' import StarRate from '@material-ui/icons/StarRate'; import withRoot from '../../withRoot'; import red from '@material-ui/core/colors/red'; import green from '@material-ui/core/colors/green' import purple from '@material-ui/core/colors/purple'; import MultiLineGraphVis from '../../visualizations/core/vega_lite_multi_line_graph'; import SortableTable from '../core/sortable_table'; import {getLast, is_valid, get_index, get_items, get_percentage} from '../../utils'; const NewReleasesOutlined = FiberNewOutlined; const SHADE = 700; const styles = theme => ({ root: { textAlign: 'center', paddingTop: theme.spacing.unit * 20, }, list: { backgroundColor: theme.palette.background.paper, marginLeft: theme.spacing.unit * 1, marginRight: theme.spacing.unit * 1, overflow: "scroll", } }); const ITEM_HEIGHT = 48; const OPTIONS = [ "Predicted Entities", "Labeled Entities", "Discovered Entities", ]; class SurprsingLabels extends React.Component { state = { selected_menu_option: OPTIONS[0], menu_open: false, anchorEl: null, } surprising_words(prediction_data) { const ent_count = {}; const label_count = {}; const prev_ent_count = {}; for (const i in prediction_data) { const pred_data = prediction_data[i][1]; if (!is_valid(pred_data)) { break; } const entities = getLast(pred_data.entities); const prev_entities = get_index(pred_data.entities, pred_data.entities.length - 2); const label_entities = pred_data.real_entities; for (const ei in entities) { const ent_data = entities[ei]; if (!(ent_data in ent_count)) { ent_count[ent_data] = {count: 0, prev_count: 0, discovered: true}; } ent_count[ent_data].count++; } if (is_valid(prev_entities)) { for (const ei in prev_entities) { const ent_data = prev_entities[ei]; if (!(ent_data in prev_ent_count)) { prev_ent_count[ent_data] = {count: 0, prev_count: 0}; } prev_ent_count[ent_data].count++; } } for (const li in label_entities) { const label_ent_data = label_entities[li]; if (!(label_ent_data in label_count)) { label_count[label_ent_data] = {count: 0, prev_count: 0}; } label_count[label_ent_data].count++; label_count[label_ent_data].prev_count++; } } const discovered_count = Object.assign({}, ent_count); for (const label_ent in label_count) { if (label_ent in discovered_count) { delete discovered_count[label_ent]; ent_count[label_ent].discovered = false; } } const prev_res = get_items(prev_ent_count); prev_res.sort(function(a, b){return b[1].count - a[1].count;}); for (let i = 0; i < prev_res.length; i++ ){ const rank = i + 1; const ent_data = prev_res[i]; const ent_name = ent_data[0]; const ent_dat_count = ent_data[1].count; if (ent_name in ent_count) { ent_count[ent_name].prev_rank = rank; ent_count[ent_name].prev_count = ent_dat_count; } } const ent_res = get_items(ent_count); ent_res.sort(function(a, b){return b[1].count - a[1].count;}); const label_res = get_items(label_count); label_res.sort(function(a, b){return b[1].count - a[1].count;}); const discovered_res = get_items(discovered_count); discovered_res.sort(function(a, b) {return b[1].count - a[1].count;}); return {ent_res, label_res, discovered_res}; } handleMenuOpen(event) { //console.log(event.currentTarget); //this.setState({selected_menu_option: event.currentTarget, menu_open: true}); this.setState({anchorEl: event.currentTarget, menu_open: true}); } handleMenuClick = option => (event) => { this.setState({selected_menu_option: option, anchorEl: null, menu_open: true}); } handleMenuClose() { this.setState({anchorEl: null, menu_open: false}); } componentDidMount() { const {predictions} = this.props; if (is_valid(predictions)) { let {ent_res, label_res, discovered_res} = this.surprising_words(predictions); this.props.updateTopEntities(ent_res.map(ent_data => ent_data[0]).slice(0, 3)); this.setState({ent_res, label_res, discovered_res}); } } componentWillReceiveProps(newProps) { const {predictions} = newProps; if (is_valid(predictions) && JSON.stringify(predictions) !== JSON.stringify(this.props.predictions)) { let {ent_res, label_res, discovered_res} = this.surprising_words(predictions); this.props.updateTopEntities(ent_res.map(ent_data => ent_data[0]).slice(0, 3)); this.setState({ent_res, label_res, discovered_res}); } } construct_menu() { const {selected_menu_option,anchorEl, menu_open} = this.state; const open = is_valid(anchorEl); return (<span> <IconButton aria-label="More" aria-owns={open ? 'long-menu' : undefined} aria-haspopup="true" onClick={this.handleMenuOpen.bind(this)} style={{padding: 8}} > <MoreVertIcon /> </IconButton> <Menu id="long-menu" anchorEl={anchorEl} open={open} onClose={this.handleMenuClose.bind(this)} PaperProps={{ style: { maxHeight: ITEM_HEIGHT * 4.5, width: 200, }, }} > {OPTIONS.map(option => ( <MenuItem key={option} selected={option === selected_menu_option} onClick={this.handleMenuClick(option).bind(this)}> {option} </MenuItem> ))} </Menu> </span> ); } get_icon(delta, fontSize) { // delta > 0 ? // <ArrowUpward style={{color: green[SHADE], fontSize}} /> : // (delta === 0 ? null : <ArrowDownward style={{color: red[SHADE], fontSize}} />); if (isNaN(delta)) { return this.new_rank_icon(fontSize) } if (delta > 0) { return this.increase_rank_icon(fontSize); } else if (delta < 0) { return this.decrease_rank_icon(fontSize); } else if (delta === 0) { return null; } } new_rank_icon(fontSize) { return <Tooltip title={ <React.Fragment> No previous rank </React.Fragment> } animation="zoom" > <NewReleasesOutlined style={{fontSize: fontSize + 5}}/> </Tooltip>; } increase_rank_icon(fontSize) { return <Tooltip title={ <React.Fragment> Went up in rank </React.Fragment> } animation="zoom" > <ArrowUpward style={{color: green[SHADE], fontSize}} /> </Tooltip>; } decrease_rank_icon(fontSize) { return <Tooltip title={ <React.Fragment> Went down in rank </React.Fragment> } animation="zoom" > <ArrowDownward style={{color: red[SHADE], fontSize}} /> </Tooltip>; } discovered_icon(fontSize) { return <Tooltip title={ <React.Fragment> Discovered (not labeled) </React.Fragment> } animation="zoom" > <StarRate style={{fontSize}} /> </Tooltip>; } render() { const {classes, predictions, height, updateTopEntities} = this.props; if (!is_valid(predictions)) { return null; } const {selected_menu_option, ent_res, label_res, discovered_res} = this.state; let res = []; switch(selected_menu_option) { case OPTIONS[0]: res = ent_res; break; case OPTIONS[1]: res = label_res; break; case OPTIONS[2]: res = discovered_res; break; default: break; } if (!is_valid(res)) { res = []; } res = res.filter(x => x[1].count > 0); const max_count = is_valid(res) && res.length >= 0 && is_valid(res[0]) ? res[0][1].count : 0; res = res.slice(0, res.length >= 100 ? 100 : res.length); return ( <div> <Typography variant="h6" gutterBottom style={{borderBottom: purple[100], margin: 0}}> {selected_menu_option} {this.construct_menu()} </Typography> {max_count === 0 ? <Typography variant="subtitle2" gutterBottom style={{top: "50%", textAlign: "center"}}> No Results </Typography>: <List className={classes.list} style={{height, padding: 0, paddingRight: 10}} dense={true}> {res.map((ent_data, index) => { // const delta = ent_data[1].count - ent_data[1].prev_count; let delta = (index + 1) - ent_data[1].prev_rank; // delta = is_valid(delta) && !isNaN(delta) ? delta : Number.MIN_VALUE; delta = -delta; const fontSize = 16; const rank_icon = this.get_icon(delta, fontSize); const star_icon = ent_data[1].discovered ? this.discovered_icon(fontSize) : null; return ( <Tooltip title={ <React.Fragment> { <span> <div>{ent_data[0]}</div> <div>Count: {ent_data[1].count}</div> <div>Previous Count: {ent_data[1].prev_count}</div> </span> } </React.Fragment> } placement="left"> <div> <ListItem style={{padding: 0}}> <div key={`div_${ent_data[0]}_${ent_data[1].count}`} style={{ background: `-webkit-linear-gradient(left, ${blueGrey[200]} ${get_percentage(ent_data[1].count, max_count)}%, white 0%)`, display: 'inline-block', flexGrow: 1, padding: 0, }}> <ListItemText primary={ <React.Fragment> <Typography component="span" style={{fontSize}} color="textPrimary"> {`${ent_data[0]}`} {star_icon} </Typography> </React.Fragment> } /> </div> {rank_icon} </ListItem> <Divider /> </div> </Tooltip> );})} </List> } </div> ); } } SurprsingLabels.propTypes = { data: PropTypes.object, predictions: PropTypes.array, height: PropTypes.number, updateTopEntities: PropTypes.func, }; export default withRoot(withStyles(styles)(SurprsingLabels));
lukekras/zig
lib/libc/include/any-linux-any/linux/netfilter/xt_SECMARK.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _XT_SECMARK_H_target #define _XT_SECMARK_H_target #include <linux/types.h> /* * This is intended for use by various security subsystems (but not * at the same time). * * 'mode' refers to the specific security subsystem which the * packets are being marked for. */ #define SECMARK_MODE_SEL 0x01 /* SELinux */ #define SECMARK_SECCTX_MAX 256 struct xt_secmark_target_info { __u8 mode; __u32 secid; char secctx[SECMARK_SECCTX_MAX]; }; struct xt_secmark_target_info_v1 { __u8 mode; char secctx[SECMARK_SECCTX_MAX]; __u32 secid; }; #endif /*_XT_SECMARK_H_target */
silphire/GodingBat
recursion2/splitArray.go
package recursion2 func _search(nums []int, target int) bool { if len(nums) == 0 || target < 0 { return false } if target == 0 { return true } return _search(nums[1:len(nums)], target-nums[0]) } func _sum(nums []int) int { if len(nums) == 0 { return 0 } return nums[0] + _sum(nums[1:len(nums)]) } func splitArray(nums []int) bool { x := _sum(nums) if x%2 == 1 { return false } x /= 2 return _search(nums, x) }
Almazmsi/Kamado-Tanjiro
handlers/erela_events/node_events.js
let started = false; module.exports = (client) => { client.manager .on("nodeConnect", (node) => { if (!started) { started = true; client.logger(`Node подключена :: ${String(node.options.identifier).brightBlue}`) } setTimeout(() => { started = false; }, 2000) }) .on("nodeCreate", (node) => { client.logger(`Node создана :: ${String(node.options.identifier).brightBlue}`) }) .on("nodeReconnect", (node) => { client.logger(`Node переподключена... :: ${String(node.options.identifier).brightBlue}`) }) .on("nodeDisconnect", (node) => { client.logger(`Node отключена :: ${String(node.options.identifier).brightBlue}`) setTimeout(() => { node.connect(); }, 1000); }) .on("nodeError", (node, error) => { client.logger(`Node ошибка :: ${String(node.options.identifier).brightBlue}`) setTimeout(() => { node.connect(); }, 1000); }) };
danmainah/vacations-booking-front-end
src/components/DeleteDestinations.js
import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import Button from 'react-bootstrap/Button'; import { deleteThunkDestination } from '../redux/Destinations/destinations'; import styles from '../styles/Delete.module.css'; const DeleteDestinations = () => { const destinations = useSelector((state) => state.destinations.destinations); const dispatch = useDispatch(); const handleDelete = (destinationId) => { dispatch(deleteThunkDestination(destinationId)); }; return ( <div className={styles.delete}> <div className="listed"> <h3 className="text-center mb-4"> My Destinations </h3> </div> <ul className="list-group"> {destinations && destinations.map((destination) => ( <li className="list-group-item d-flex justify-content-between" key={destination.id}> {destination.name} <Button className="ms-5 btn-danger" onClick={() => handleDelete(destination.id)}> Remove </Button> </li> ))} </ul> </div> ); }; export default DeleteDestinations;
NeuroArchitect/lm
src/lm/datasets/constants.py
<gh_stars>1-10 """ vocab conventions """ PAD = "[PAD]" # End Of Sentence EOS = "[EOS]" PAD_ = 0 EOS_ = 1 TEXT_FEATURE_NAME = "target"
icbat/RFTools
src/main/java/mcjty/rftools/blocks/storagemonitor/StorageScannerBlock.java
<filename>src/main/java/mcjty/rftools/blocks/storagemonitor/StorageScannerBlock.java<gh_stars>0 package mcjty.rftools.blocks.storagemonitor; import mcjty.lib.api.Infusable; import mcjty.lib.gui.GenericGuiContainer; import mcjty.rftools.RFTools; import mcjty.rftools.blocks.GenericRFToolsBlock; import net.minecraft.block.material.Material; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import org.lwjgl.input.Keyboard; import java.util.List; import java.util.function.BiFunction; public class StorageScannerBlock extends GenericRFToolsBlock<StorageScannerTileEntity, StorageScannerContainer> implements Infusable { public StorageScannerBlock() { super(Material.IRON, StorageScannerTileEntity.class, StorageScannerContainer::new, "storage_scanner", true); } @SideOnly(Side.CLIENT) @Override public BiFunction<StorageScannerTileEntity, StorageScannerContainer, GenericGuiContainer<? super StorageScannerTileEntity>> getGuiFactory() { return GuiStorageScanner::new; } @SideOnly(Side.CLIENT) @Override public void addInformation(ItemStack itemStack, World player, List<String> list, ITooltipFlag advancedToolTip) { super.addInformation(itemStack, player, list, advancedToolTip); if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) { list.add(TextFormatting.WHITE + "This machine will scan all nearby inventories"); list.add(TextFormatting.WHITE + "and show them in a list. You can then search"); list.add(TextFormatting.WHITE + "for items in all those inventories."); list.add(TextFormatting.YELLOW + "Infusing bonus: reduced power consumption."); } else { list.add(TextFormatting.WHITE + RFTools.SHIFT_MESSAGE); } } @Override public int getGuiID() { return RFTools.GUI_STORAGE_SCANNER; } }
leafchild0/chart-desk
charts/src/main/java/chart/desk/configuration/JsonConfiguration.java
package chart.desk.configuration; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.joda.JodaModule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @Configuration public class JsonConfiguration { @Primary @Bean(name = "json_mapper") public ObjectMapper getHelmObjectMapper() { return new ObjectMapper() .registerModule(new JodaModule()) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); } }
supudo/Kuplung
Kuplung/kuplung/settings/FontsList.cpp
<reponame>supudo/Kuplung // // FontsList.cpp // Kuplung // // Created by <NAME> on 2/4/16. // Copyright © 2016 supudo.net. All rights reserved. // #include "FontsList.hpp" #include <algorithm> #include <stdio.h> #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include "kuplung/settings/Settings.h" #ifdef WIN32 #include <shlobj.h> #endif namespace fs = boost::filesystem; void FontsList::init() { this->fonts.clear(); } const bool FontsList::fontFileExists(std::string const& font)const { return boost::filesystem::exists(font); } const int FontsList::getSelectedFontSize() const { for (size_t i=0; i<sizeof(this->fontSizes[0]); i++) { if (atof(this->fontSizes[i]) < Settings::Instance()->UIFontSize) return static_cast<int>(i); } return 0; } void FontsList::getFonts() { #ifdef WIN32 return this->loadFontsWindows(); #elif __APPLE__ return this->loadFontsOSX(); #elif linux || __linux return this->loadFontsNix(); #endif } void FontsList::loadFontsOSX() { //| /System/Library/Fonts - Fonts necessary for the system. Do not touch these. //| /Library/Fonts - Additional fonts that can be used by all users. This is generally where fonts go if they are to be used by other applications. //| ~/Library/Fonts - Fonts specific to each user. //| /Network/Library/Fonts - Fonts shared for users on a network. std::string fontsAdditionalPath = "/Library/Fonts/"; fs::path currentPath(fontsAdditionalPath); if (fs::is_directory(currentPath)) { fs::directory_iterator iteratorEnd; int i = 1; for (fs::directory_iterator iteratorFolder(currentPath); iteratorFolder != iteratorEnd; ++iteratorFolder) { try { std::string fileExtension = iteratorFolder->path().extension().string(); fs::file_status fileStatus = iteratorFolder->status(); if (fileExtension == ".ttf" && (fs::is_directory(fileStatus) || fs::is_regular_file(fileStatus))) { FBEntity fontFile; fontFile.isFile = true; fontFile.extension = "ttf"; fontFile.path = fontsAdditionalPath + iteratorFolder->path().filename().string(); fontFile.title = iteratorFolder->path().filename().string(); boost::replace_all(fontFile.title, ".ttf", ""); this->fonts.push_back(fontFile); if (fontFile.path == Settings::Instance()->UIFontFile) Settings::Instance()->UIFontFileIndex = i; i += 1; } } catch (const std::exception & ex) { Settings::Instance()->funcDoLog(iteratorFolder->path().filename().string() + " " + ex.what()); } } } } void FontsList::loadFontsWindows() { //| %WINDIR%\fonts #ifdef WIN32 std::string fontsFolder = "%WINDIR%\fonts"; TCHAR szPath[MAX_PATH]; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_WINDOWS, NULL, 0, szPath))) { # ifndef UNICODE fontsFolder = szPath; # else std::wstring folderLocalAppDataW = szPath; fontsFolder = std::string(folderLocalAppDataW.begin(), folderLocalAppDataW.end()); # endif fontsFolder += "\\fonts"; fs::path currentPath(fontsFolder); if (fs::is_directory(currentPath)) { fs::directory_iterator iteratorEnd; int i = 1; for (fs::directory_iterator iteratorFolder(currentPath); iteratorFolder != iteratorEnd; ++iteratorFolder) { try { std::string fileExtension = iteratorFolder->path().extension().string(); fs::file_status fileStatus = iteratorFolder->status(); if (fileExtension == ".ttf" && (fs::is_directory(fileStatus) || fs::is_regular_file(fileStatus))) { FBEntity fontFile; fontFile.isFile = true; fontFile.extension = "ttf"; fontFile.path = fontsFolder + iteratorFolder->path().filename().string(); fontFile.title = iteratorFolder->path().filename().string(); boost::replace_all(fontFile.title, ".ttf", ""); this->fonts.push_back(fontFile); if (fontFile.path == Settings::Instance()->UIFontFile) Settings::Instance()->UIFontFileIndex = i; i += 1; } } catch (const std::exception& ex) { Settings::Instance()->funcDoLog(iteratorFolder->path().filename().string() + " " + ex.what()); } } } } #endif } void FontsList::loadFontsNix() { //| /usr/share/fonts //| /usr/local/share/fonts //| ~/.fonts }
anubhab-code/Competitive-Programming
Codeforces/A_Snow_Footprints.py
<reponame>anubhab-code/Competitive-Programming n=int(input()) s=input() l,r=s.rfind('L')+1,s.find('R')+1 if r>0: print(r,r+s.count('R')) else: print(l,l-s.count('L'))
kovetskiy/aurora
cmd/aurorad/cloud.go
package main import ( "context" "fmt" "io" "os" "path/filepath" "runtime" "strconv" "sync" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/docker/docker/pkg/stdcopy" "github.com/kovetskiy/lorg" "github.com/reconquest/karma-go" ) const ( ImageLabelKey = "io.reconquest/aurora" ) type Cloud struct { client *client.Client BaseImage string mutex sync.Mutex resources ConfigResources threads int cpuNext int } func NewCloud(baseImage string, resources ConfigResources, threads int) (*Cloud, error) { var err error cloud := &Cloud{} cloud.client, err = client.NewEnvClient() cloud.BaseImage = baseImage cloud.resources = resources if threads == 0 { threads = runtime.NumCPU() } cloud.threads = threads return cloud, err } func (cloud *Cloud) getNextCPU() string { if cloud.resources.CPU == 0 { return "" } cloud.mutex.Lock() defer cloud.mutex.Unlock() start := cloud.cpuNext end := start + cloud.resources.CPU - 1 cloud.cpuNext = (cloud.cpuNext + cloud.resources.CPU) % cloud.threads if start == end { return strconv.Itoa(start) } else { return fmt.Sprintf("%d-%d", start, end) } } func (cloud *Cloud) CreateContainer( bufferDir string, containerName string, packageName string, cloneURL string, subdir string, ) (string, error) { config := &container.Config{ Image: cloud.BaseImage, Labels: map[string]string{ ImageLabelKey: version, }, Tty: true, Env: []string{ fmt.Sprintf("AURORA_PACKAGE=%s", packageName), fmt.Sprintf("AURORA_CLONE_URL=%s", cloneURL), fmt.Sprintf("AURORA_SUBDIR=%s", subdir), }, AttachStdout: true, AttachStderr: true, } hostConfig := &container.HostConfig{ Binds: []string{ fmt.Sprintf("%s:/buffer", bufferDir), }, } if cloud.resources.CPU > 0 { hostConfig.Resources.CpusetCpus = cloud.getNextCPU() } created, err := cloud.client.ContainerCreate( context.Background(), config, hostConfig, nil, containerName, ) if err != nil { return "", err } return created.ID, nil } func (cloud *Cloud) FollowLogs(ctx context.Context, container string, send func(string)) error { reader, err := cloud.client.ContainerLogs( ctx, container, types.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, Follow: true, Tail: "all", }, ) if err != nil { return err } defer reader.Close() buffer := make([]byte, 1024) for { size, err := reader.Read(buffer) if err != nil { if err == io.EOF { break } return err } send(string(buffer[:size])) } return nil } func (cloud *Cloud) StartContainer(container string) error { err := cloud.client.ContainerStart( context.Background(), container, types.ContainerStartOptions{}, ) if err != nil { return err } return nil } func (cloud *Cloud) DestroyContainer(container string) error { err := cloud.client.ContainerRemove( context.Background(), container, types.ContainerRemoveOptions{ Force: true, }, ) if err != nil { return err } return nil } func (cloud *Cloud) Exec( ctx context.Context, logger lorg.Logger, publish func(string), container string, command, env []string, ) error { exec, err := cloud.client.ContainerExecCreate( ctx, container, types.ExecConfig{ Cmd: command, Env: env, AttachStdout: true, AttachStderr: true, }, ) if err != nil { return err } response, err := cloud.client.ContainerExecAttach( ctx, exec.ID, types.ExecConfig{ AttachStdout: true, AttachStderr: true, }, ) if err != nil { return err } writer := &execWriter{logger: logger, publish: publish} _, err = stdcopy.StdCopy(writer, writer, response.Reader) if err != nil { return karma.Format(err, "unable to read stdout of exec/attach") } return nil } func (cloud *Cloud) WriteLogs( logsDir, container, packageName string, ) error { logfile, err := os.OpenFile( filepath.Join(logsDir, packageName), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644, ) if err != nil { return err } reader, err := cloud.client.ContainerLogs( context.Background(), container, types.ContainerLogsOptions{ ShowStdout: true, ShowStderr: true, }, ) if err != nil { return err } defer reader.Close() _, err = io.Copy(logfile, reader) if err != nil && err != io.EOF { return err } return nil } func (cloud *Cloud) Cleanup() error { options := types.ContainerListOptions{} containers, err := cloud.client.ContainerList( context.Background(), options, ) if err != nil { return karma.Format( err, "unable to list containers", ) } destroyed := 0 for _, container := range containers { if _, ours := container.Labels[ImageLabelKey]; ours { infof( "cleanup: destroying container %q %q in status: %s", container.ID, container.Names, container.Status, ) err := cloud.DestroyContainer(container.ID) if err != nil { return karma.Describe("id", container.ID).Format( err, "unable to destroy container", ) } destroyed++ } } infof("cleanup: destroyed %d containers", destroyed) return nil }
frekele/focusnfe-api-client
src/test/java/org/frekele/fiscal/focus/nfe/client/filter/RequestLoggingFilterTest.java
<gh_stars>1-10 package org.frekele.fiscal.focus.nfe.client.filter; import org.frekele.fiscal.focus.nfe.client.testng.InvokedMethodListener; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import javax.ws.rs.client.ClientRequestContext; import javax.ws.rs.core.MediaType; import static org.mockito.Mockito.*; /** * @author frekele - <NAME> */ @Listeners(InvokedMethodListener.class) public class RequestLoggingFilterTest { @Test public void testNewInstance() throws Exception { ClientRequestContext requestContext = mock(ClientRequestContext.class); new RequestLoggingFilter().filter(requestContext); String content = "{\"codigo\":\"123\",\"mensagem\":\"teste\"}"; when(requestContext.hasEntity()).thenReturn(true); when(requestContext.getEntity()).thenReturn(content); new RequestLoggingFilter().filter(requestContext); when(requestContext.hasEntity()).thenReturn(true); when(requestContext.getEntity()).thenReturn(content); when(requestContext.getMediaType()).thenReturn(MediaType.APPLICATION_JSON_TYPE.withCharset("UTF-8")); new RequestLoggingFilter().filter(requestContext); } }
johnjohndoe/pgem
db/migrate/20181120224626_create_ticket_group_benefits.rb
<gh_stars>1-10 class CreateTicketGroupBenefits < ActiveRecord::Migration def self.up create_table :ticket_group_benefits do |t| t.references :ticket_group, null: false t.string :name, null: false t.text :description, null: false t.integer :position t.timestamps end add_foreign_key :ticket_group_benefits, :ticket_groups end def self.down drop_table :ticket_group_benefits end end
TJC-Team/Twitch2Minecraft-WhitelistTool
node_modules/ircv3/lib/Message/MessageTypes/Numerics/Error482ChanOpPrivsNeeded.js
<reponame>TJC-Team/Twitch2Minecraft-WhitelistTool "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Error482ChanOpPrivsNeeded = void 0; var tslib_1 = require("tslib"); var Message_1 = require("../../Message"); var MessageDefinition_1 = require("../../MessageDefinition"); var Error482ChanOpPrivsNeeded = /** @class */ (function (_super) { tslib_1.__extends(Error482ChanOpPrivsNeeded, _super); function Error482ChanOpPrivsNeeded() { return _super !== null && _super.apply(this, arguments) || this; } tslib_1.__decorate([ MessageDefinition_1.MessageParamDefinition({}) ], Error482ChanOpPrivsNeeded.prototype, "me", void 0); tslib_1.__decorate([ MessageDefinition_1.MessageParamDefinition({}) ], Error482ChanOpPrivsNeeded.prototype, "channel", void 0); tslib_1.__decorate([ MessageDefinition_1.MessageParamDefinition({ trailing: true }) ], Error482ChanOpPrivsNeeded.prototype, "suffix", void 0); Error482ChanOpPrivsNeeded = tslib_1.__decorate([ MessageDefinition_1.MessageType('482') ], Error482ChanOpPrivsNeeded); return Error482ChanOpPrivsNeeded; }(Message_1.Message)); exports.Error482ChanOpPrivsNeeded = Error482ChanOpPrivsNeeded;
npocmaka/Windows-Server-2003
sdktools/ztools/src/pname.c
/*** pname.c - form a "pretty" version of a user file name * * OS/2 v1.2 and later will allow filenames to retain the case * when created while still being case insensitive for all operations. * This allows the user to create more visually appealing file names. * * All runtime routines should, therefore, preserve the case that was * input. Since the user may not have input in the case that the entries * were created, we provide a service whereby a pathname is adjusted * to be more visually appealing. The rules are: * * if (real mode) * lowercase it * else * if (version is <= 1.1) * lowercase it * else * if (filesystem is FAT) * lowercase it * else * for each component starting at the root, use DosFindFirst * to retrieve the original case of the name. * * Modifications: * 10-Oct-1989 mz First implementation * * 03-Aug-1990 davegi Removed dynamic linking to DosQueryPathInfo * on the assumption that it will always be * there on a 32-bit OS/2 (OS/2 2.0) * 18-Oct-1990 w-barry Removed 'dead' code. * 24-Oct-1990 w-barry Changed PFILEFINDBUF3 to FILEFINDBUF3 *. * */ #define INCL_ERRORS #define INCL_DOSFILEMGR #define INCL_DOSMODULEMGR #include <stdio.h> #include <string.h> #include <stdlib.h> #include <malloc.h> #include <windows.h> #include <tools.h> // // Form pretty name in place. There must be sufficient room to handle // short-name expansion // char * pname ( char *pszName ) { HANDLE handle; WIN32_FIND_DATA findbuf; char PrettyName[MAX_PATH]; char *Name = pszName; char *Pretty = PrettyName; char *ComponentEnd; char SeparatorChar; char *Component; if (!IsMixedCaseSupported (pszName)) return _strlwr (pszName); // // Walk forward through the name, copying components. As // we process a component, we let the underlying filesystem // tell us the correct case and expand short to long name // // // If there's a drive letter copy it // if (Name[0] != '\0' && Name[1] == ':') { *Pretty++ = *Name++; *Pretty++ = *Name++; } while (TRUE) { // // If we're at a separator // Copy it // if (*Name == '/' || *Name == '\\' || *Name == '\0') { if (Pretty >= PrettyName + MAX_PATH) { break; } *Pretty++ = *Name++; if (Name[-1] == '\0') { strcpy( pszName, PrettyName ); break; } continue; } // // We're pointing to the first character of a component. // Find the terminator, save it and terminate the component. // ComponentEnd = strbscan( Name, "/\\" ); SeparatorChar = *ComponentEnd; *ComponentEnd = '\0'; // // If there's no meta chars and it's not . and not .. and if we can find it // if ( *strbscan( Name, "*?" ) == 0 && strcmp( Name, "." ) && strcmp( Name, ".." ) && (handle = FindFirstFile( pszName, &findbuf )) != INVALID_HANDLE_VALUE) { Component = findbuf.cFileName; FindClose( handle ); } else { Component = Name; } // // Pretty points to where the next component name should be placed // Component points to the appropriate text. If there's not enough // room, we're done // if (Pretty + strlen( Component ) + 1 > Pretty + MAX_PATH) { break; } // // Copy the component in, advance destination and source // strcpy( Pretty, Component ); Pretty += strlen( Pretty ); Name = ComponentEnd; *Name = SeparatorChar; } return pszName; } /* IsMixedCaseSupported - determine if a file system supports mixed case * * We presume that all OS's prior to OS/2 1.2 or FAT filesystems * do not support mixed case. It is up to the client to figure * out what to do. * * We presume that non FAT filesystems on 1.2 and later DO support mixed * case * * We do some caching to prevent redundant calls to the file systems. * * returns TRUE (MCA_SUPPORT) if it is supported * FALSE (MCA_NOTSUPP) if unsupported * */ #define MCA_UNINIT 123 #define MCA_SUPPORT TRUE #define MCA_NOTSUPP FALSE static WORD mca[27] = { MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT, MCA_UNINIT}; WORD QueryMixedCaseSupport ( char *psz ) { UNREFERENCED_PARAMETER( psz ); return MCA_SUPPORT; //BYTE* pUpdPath; // //UNREFERENCED_PARAMETER( psz ); // ///* If OS/2 before 1.2, presume no mixed case support // */ //if (_osmajor < 10 || (_osmajor == 10 && _osminor < 2)) //return MCA_NOTSUPP; // //pUpdPath = (*tools_alloc) (MAX_PATH); //if (pUpdPath == NULL) //return MCA_NOTSUPP; // //return MCA_NOTSUPP; } WORD IsMixedCaseSupported ( char *psz ) { WORD mcaSupp; DWORD ulDrvOrd; BOOL fUNC; fUNC = (BOOL)( ( fPathChr( psz[0] ) && fPathChr( psz[1] ) ) || ( psz[0] != 0 && psz[1] == ':' && fPathChr( psz[2] ) && fPathChr( psz[3] ) ) ); /* Obtain drive ordinal and return cached value if valid */ if (!fUNC) { if (psz[0] != 0 && psz[1] == ':') { ulDrvOrd = (tolower(psz[0]) | 0x20) - 'a' + 1; } else { char buf[MAX_PATH]; GetCurrentDirectory( MAX_PATH, buf ); ulDrvOrd = (tolower(buf[0]) | 0x20 ) - 'a' + 1; } if (mca[ulDrvOrd] != MCA_UNINIT) { return mca[ulDrvOrd]; } } /* Get support value */ mcaSupp = QueryMixedCaseSupport (psz); if (!fUNC) mca[ulDrvOrd] = mcaSupp; return mcaSupp; }
gchicoye/amphtml
ads/playstream.js
<reponame>gchicoye/amphtml /** * Copyright 2020 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {loadScript, validateData} from '../3p/3p'; const mandatoryParams = ['id']; const optionalParams = ['fluid']; /** * @param {!Window} global * @param {!Object} data */ export function playstream(global, data) { /*eslint "google-camelcase/google-camelcase": 0*/ global.playstream = { unitData: data['id'], fluid: data['fluid'], }; validateData(data, mandatoryParams, optionalParams); const searchParams = new URLSearchParams(data); loadScript( global, 'https://app.playstream.media/js/amp.js?' + searchParams.toString() ); }
bompi88/grand-view
client/lib/helpers/general.js
<gh_stars>1-10 //-------------------------------------------------------------------------------------------------- // General helpers //-------------------------------------------------------------------------------------------------- import { $ } from 'jquery'; import { moment } from 'meteor/momentjs:moment'; import bootbox from 'bootbox'; export default { /** * Formats the date like "i går kl. 15.28" */ formatDateRelative(date) { return moment && moment(date).calendar(); }, formatDateRegular(date) { return moment && moment(date).format('L'); }, showConfirmationPrompt(options, callbackYes, callbackNo) { const { title, message } = options; $('div.tooltip').hide(); // A confirmation prompt before removing the document const confirmationPrompt = { title, message, buttons: { cancel: { label: 'Nei', callback: callbackNo, }, confirm: { label: 'Ja', callback: callbackYes, }, }, }; bootbox.dialog(confirmationPrompt); }, goto({ FlowRouter }, id, template = false) { const route = template ? 'Template' : 'Document'; FlowRouter.go(FlowRouter.path(route, { _id: id })); }, goToDocument(_, id) { this.goto(id); }, goToTemplate(_, id) { this.goto(id, true); }, };
shreejitverma/GeeksforGeeks
Competitive Programming/System Design/Tweet Counts Per Frequency.cpp
/* https://leetcode.com/problems/tweet-counts-per-frequency/ 1348. Tweet Counts Per Frequency Medium 78 150 Add to List Share A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day). For example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies: Every minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000] Every hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000] Every day (86400-second chunks): [10,10000] Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example). Design and implement an API to help the company with their analysis. Implement the TweetCounts class: TweetCounts() Initializes the TweetCounts object. void recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds). List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq. freq is one of "minute", "hour", or "day" representing a frequency of every minute, hour, or day respectively. Example: Input ["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"] [[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]] Output [null,null,null,null,[2],[2,1],null,[4]] Explanation TweetCounts tweetCounts = new TweetCounts(); tweetCounts.recordTweet("tweet3", 0); // New tweet "tweet3" at time 0 tweetCounts.recordTweet("tweet3", 60); // New tweet "tweet3" at time 60 tweetCounts.recordTweet("tweet3", 10); // New tweet "tweet3" at time 10 tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]; chunk [0,59] had 2 tweets tweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet tweetCounts.recordTweet("tweet3", 120); // New tweet "tweet3" at time 120 tweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]; chunk [0,210] had 4 tweets Constraints: 0 <= time, startTime, endTime <= 109 0 <= endTime - startTime <= 104 There will be at most 104 calls in total to recordTweet and getTweetCountsPerFrequency. */ // Time: add: O(logn), // query: O(c), c is the total count of matching records // Space: O(n) class TweetCounts { public: TweetCounts() { } void recordTweet(string tweetName, int time) { records_[tweetName].emplace(time); } vector<int> getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) { static const unordered_map<string, int> lookup = {{"minute", 60}, {"hour", 3600}, {"day", 86400}}; const auto &delta = lookup.at(freq); vector<int> result((endTime - startTime) / delta + 1); for (auto it = records_[tweetName].lower_bound(startTime); it != records_[tweetName].end() && *it <= endTime; ++it) { ++result[(*it - startTime) / delta]; } return result; } private: unordered_map<string, multiset<int> > records_; }; // Time: add: O(n), // query: O(rlogn), r is the size of result // Space: O(n) class TweetCounts2 { public: TweetCounts2() { } void recordTweet(string tweetName, int time) { auto it = lower_bound(records_[tweetName].begin(), records_[tweetName].end(), time); records_[tweetName].insert(it, time); } vector<int> getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) { static const unordered_map<string, int> lookup = {{"minute", 60}, {"hour", 3600}, {"day", 86400}}; const auto &delta = lookup.at(freq); vector<int> result; for (int i = startTime; i <= endTime; i += delta) { int j = min(i + delta, endTime + 1); result.emplace_back(distance(lower_bound(records_[tweetName].cbegin(), records_[tweetName].cend(), i), lower_bound(records_[tweetName].cbegin(), records_[tweetName].cend(), j))); } return result; } private: unordered_map<string, vector<int> > records_; }; // Time: add: O(1), // query: O(n) // Space: O(n) class TweetCounts3 { public: TweetCounts3() { } void recordTweet(string tweetName, int time) { records_[tweetName].emplace_back(time); } vector<int> getTweetCountsPerFrequency(string freq, string tweetName, int startTime, int endTime) { static const unordered_map<string, int> lookup = {{"minute", 60}, {"hour", 3600}, {"day", 86400}}; const auto &delta = lookup.at(freq); vector<int> result((endTime - startTime) / delta + 1); for (const auto &t : records_[tweetName]) { if (startTime <= t && t <= endTime) { ++result[(t - startTime) / delta]; } } return result; } private: unordered_map<string, vector<int> > records_; };
GoodyIT/social-app-iOS
Q-municate/Scenes/Auth/Calendar window/CalendarViewController.h
// // CalendarViewController.h // Pile // // Created by Admin on 2016-11-14. // Copyright © 2016 Admin. All rights reserved. // #import <UIKit/UIKit.h> @interface CalendarViewController : UIViewController @end
cburgess421/PokeGame
Master/GameControllers/GameMenuViewController.h
<gh_stars>1-10 // // GameMenuViewController.h // iPokeMon // // Created by <NAME> on 2/26/12. // Copyright (c) 2012 Kjuly. All rights reserved. // #import <UIKit/UIKit.h> @protocol GameMenuViewControllerDelegate; @interface GameMenuViewController : UIViewController <UIAlertViewDelegate> { id <GameMenuViewControllerDelegate> delegate_; } @property (nonatomic, assign) id <GameMenuViewControllerDelegate> delegate; - (void)prepareForNewScene; - (void)reset; @end // Delegate @protocol GameMenuViewControllerDelegate - (void)unloadBattleScene; @end
chrisharrington/twitter-followers-server
lib/controllers/sign-in/request-token.js
<gh_stars>1-10 "use strict"; var twitter = include("twitter-oauth"), cache = require("./cache"); module.exports = function(app) { app.get("/auth/request-token", function(req, res, next) { twitter.getRequestToken(function(err, token, secret) { if (err) res.status(500).send(err); else { cache[token] = secret; res.redirect("https://api.twitter.com/oauth/authenticate?oauth_token=" + token); } }); }); };
harry-hao/easemob-im-server-sdk
im-sdk-core/src/main/java/com/easemob/im/server/api/group/member/add/GroupMemberAdd.java
package com.easemob.im.server.api.group.member.add; import com.easemob.im.server.api.Context; import reactor.core.publisher.Mono; public class GroupMemberAdd { public static Mono<Void> single(Context context, String groupId, String username) { return context.getHttpClient() .post() .uri(String.format("/chatgroups/%s/users/%s", groupId, username)) .responseSingle((rsp, buf) -> context.getErrorMapper().apply(rsp).then()); } }
nosix/dragome-sdk
dragome-w3c-standards/src/main/java/org/w3c/dom/css/CSSStringComponentValue.java
<reponame>nosix/dragome-sdk // Generated by esidl 0.4.0. package org.w3c.dom.css; public interface CSSStringComponentValue { // CSSStringComponentValue public String getString(); public void setString(String string); }
zhangce/elementary
doc/html/search/classes_74.js
<reponame>zhangce/elementary var searchData= [ ['tests',['tests',['../structtests.html',1,'']]], ['timer',['Timer',['../classmia_1_1elly_1_1utils_1_1_timer.html',1,'mia::elly::utils']]] ];
jovanidash21/express-react-redux-chat-app
src/_main/containers/Partial/MembersList/Index.js
<reponame>jovanidash21/express-react-redux-chat-app export { default as MembersList } from './MembersList';
amazing-2020/pdf
C/code case/code case 179.c
<reponame>amazing-2020/pdf #include <stdio.h> #include <math.h> int issushu(int k); int main(void) { int n, count=0; scanf("%d", &n); for (int i=n; i>3; i--) { if (issushu(i)) { if (issushu(i-2)) { count++; } } } printf("%d ", count); return 0; } int issushu(int k) { for (int i=2; i<sqrt(k)+1; i++) { if (k%i==0) { return 0; } } return 1; }//质数的个数,但是存在bug