repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
kristianmandrup/cantango
lib/cantango/permission_engine/parser/category.rb
module CanTango class PermissionEngine < Engine module Parser class Category < Rule # remove the '@' prefix to get the category name # look up the category and get models referenced by said category attr_reader :categories def initialize method, action, target super load_categories end def parse cat_name = target.gsub(/^\^/, '').to_sym targets = category_models_for(cat_name).map{|model| parse_class(model)} targets.inject([]) do |statements, target| statements << "#{method}(:#{action}, #{target})" end end def category_models_for name categories.registered[name.to_s] end def load_categories @categories = CanTango::PermissionEngine::Loader::Categories.new.categories end end end end end
TitanInfrastructure/virtualbox
lib/virtualbox/medium_attachment.rb
<filename>lib/virtualbox/medium_attachment.rb module VirtualBox # Represents the attachment of a medium (DVD, Hard Drive, etc) to a # virtual machine, and specifically to a {StorageController}. class MediumAttachment < AbstractModel attribute :parent, :readonly => true, :property => false attribute :controller_name, :readonly => :true, :property => :controller attribute :port, :readonly => true attribute :device, :readonly => true attribute :passthrough, :readonly => true attribute :type, :readonly => true relationship :medium, :Medium relationship :storage_controller, :StorageController class << self # Populates a relationship with another model. # # **This method typically won't be used except internally.** # # @return [Array<MediumAttachment>] def populate_relationship(caller, imachine) relation = Proxies::Collection.new(caller) imachine.medium_attachments.each do |ima| relation << new(caller, ima) end relation end end def initialize(parent, imedium_attachment) populate_attributes({:parent => parent}, :ignore_relationships => true) initialize_attributes(imedium_attachment) end def initialize_attributes(ima) load_interface_attributes(ima) populate_relationship(:medium, ima.medium) populate_relationship(:storage_controller, self) end # Detaches the medium from it's parent virtual machine. Note that this # **does not delete** the `medium` which this attachment references; it # merely removes the assocation of said medium with this attachment's # virtual machine. def detach parent.with_open_session do |session| machine = session.machine machine.detach_device(storage_controller.name, port, device) end end # Destroy this medium attachment. This simply detaches the medium attachment. # This will also delete the medium if that option is specified. def destroy(opts={}) detach medium.destroy(opts[:destroy_medium] == :delete) if opts[:destroy_medium] && medium end end end
npocmaka/Windows-Server-2003
multimedia/directx/dxvb/dx8vb/dmsegmentobj.cpp
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1998 - 1999 // // File: dmsegmentobj.cpp // //-------------------------------------------------------------------------- // dmSegmentObj.cpp #include "stdafx.h" #include "Direct.h" #include "dmusici.h" #include "dmusicc.h" #include "dmusicf.h" #include "dms.h" #include "dmSegmentObj.h" #include "dmStyleObj.h" #include "dmChordMapObj.h" extern void *g_dxj_DirectMusicSegment; extern void *g_dxj_DirectMusicStyle; extern void *g_dxj_DirectMusicChordMap; //CONSTRUCTOR(_dxj_DirectMusicSegment, {}); C_dxj_DirectMusicSegmentObject::C_dxj_DirectMusicSegmentObject() { m__dxj_DirectMusicSegment = NULL; parent = NULL; pinterface = NULL; nextobj = (void*)g_dxj_DirectMusicSegment; creationid = ++g_creationcount; g_dxj_DirectMusicSegment = (void*)this; } DESTRUCTOR(_dxj_DirectMusicSegment, {}); GETSET_OBJECT(_dxj_DirectMusicSegment); HRESULT C_dxj_DirectMusicSegmentObject::clone( /* [in] */ long mtStart, /* [in] */ long mtEnd, /* [retval][out] */ I_dxj_DirectMusicSegment __RPC_FAR *__RPC_FAR *ppSegment) { HRESULT hr; IDirectMusicSegment *pOut=NULL; IDirectMusicSegment8 *pReal=NULL; __try { if (FAILED (hr=m__dxj_DirectMusicSegment->Clone((MUSIC_TIME)mtStart,(MUSIC_TIME)mtEnd,&pOut) ) ) return hr; if (!pOut)return E_OUTOFMEMORY; hr = pOut->QueryInterface(IID_IDirectMusicSegment8, (void**) &pReal); pOut->Release(); if FAILED(hr) return hr; INTERNAL_CREATE_NOADDREF(_dxj_DirectMusicSegment,pReal,ppSegment); if (!*ppSegment)return E_OUTOFMEMORY; } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::setStartPoint( /* [in] */ long mtStart) { HRESULT hr; __try { hr=m__dxj_DirectMusicSegment->SetStartPoint((MUSIC_TIME)mtStart); } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::getStartPoint( /* [in] */ long *mtStart) { HRESULT hr; __try { hr=m__dxj_DirectMusicSegment->GetStartPoint((MUSIC_TIME*)mtStart); } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::setLoopPoints( /* [in] */ long mtStart, /* [in] */ long mtEnd) { HRESULT hr; __try { hr=m__dxj_DirectMusicSegment->SetLoopPoints((MUSIC_TIME)mtStart,(MUSIC_TIME)mtEnd); } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::getLoopPointStart( long *mtOut) { HRESULT hr; MUSIC_TIME mtStart =0; MUSIC_TIME mtEnd =0; __try { hr=m__dxj_DirectMusicSegment->GetLoopPoints((MUSIC_TIME*)&mtStart,(MUSIC_TIME*)&mtEnd); *mtOut=(long)mtStart; } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::getLoopPointEnd( long *mtOut) { HRESULT hr; MUSIC_TIME mtStart =0; MUSIC_TIME mtEnd =0; __try { hr=m__dxj_DirectMusicSegment->GetLoopPoints((MUSIC_TIME*)&mtStart,(MUSIC_TIME*)&mtEnd); *mtOut=(long)mtEnd; } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::setLength( /* [in] */ long mtLength) { HRESULT hr; __try { hr=m__dxj_DirectMusicSegment->SetLength((MUSIC_TIME)mtLength); } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::getLength( /* [in] */ long *mtLength) { HRESULT hr; __try { hr=m__dxj_DirectMusicSegment->GetLength((MUSIC_TIME*)mtLength); } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::setRepeats( /* [in] */ long lrep) { HRESULT hr; __try { hr=m__dxj_DirectMusicSegment->SetRepeats((DWORD)lrep); } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::getRepeats( /* [in] */ long *lrep) { HRESULT hr; __try { hr=m__dxj_DirectMusicSegment->GetRepeats((DWORD*)lrep); } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::download( /* [in] */ IUnknown __RPC_FAR *downloadpath) { if (!downloadpath) return E_INVALIDARG; HRESULT hr; __try { I_dxj_DirectMusicSegment *lpSeg = NULL; I_dxj_DirectMusicAudioPath *lpPath = NULL; hr = downloadpath->QueryInterface(IID_I_dxj_DirectMusicPerformance, (void**)&lpSeg); if (SUCCEEDED(hr) ) { DO_GETOBJECT_NOTNULL(IDirectMusicPerformance8*,pPer,lpSeg); hr=m__dxj_DirectMusicSegment->Download(pPer); return hr; } else { hr = downloadpath->QueryInterface(IID_I_dxj_DirectMusicAudioPath, (void**)&lpPath); if (SUCCEEDED(hr) ) { DO_GETOBJECT_NOTNULL(IDirectMusicAudioPath*,pPer,lpPath); hr=m__dxj_DirectMusicSegment->Download(pPer); return hr; } else return E_INVALIDARG; } } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return S_OK; } HRESULT C_dxj_DirectMusicSegmentObject::unload( /* [in] */ IUnknown __RPC_FAR *downloadpath) { if (!downloadpath) return E_INVALIDARG; HRESULT hr; I_dxj_DirectMusicSegment *lpSeg = NULL; I_dxj_DirectMusicAudioPath *lpPath = NULL; __try { hr = downloadpath->QueryInterface(IID_I_dxj_DirectMusicPerformance, (void**)&lpSeg); if (SUCCEEDED(hr) ) { DO_GETOBJECT_NOTNULL(IDirectMusicPerformance8*,pPer,lpSeg); hr=m__dxj_DirectMusicSegment->Unload(pPer); return hr; } else { hr = downloadpath->QueryInterface(IID_I_dxj_DirectMusicAudioPath, (void**)&lpPath); if (SUCCEEDED(hr) ) { DO_GETOBJECT_NOTNULL(IDirectMusicAudioPath*,pPer,lpPath); hr=m__dxj_DirectMusicSegment->Unload(pPer); return hr; } else return E_INVALIDARG; } } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return S_OK; } HRESULT C_dxj_DirectMusicSegmentObject::setAutoDownloadEnable( /* [retval][out] */ VARIANT_BOOL b) { HRESULT hr; __try { if (b==VARIANT_FALSE){ hr=m__dxj_DirectMusicSegment->SetParam(GUID_Disable_Auto_Download,0xFFFFFFFF,(DWORD)0,(MUSIC_TIME)0,NULL); } else { hr=m__dxj_DirectMusicSegment->SetParam(GUID_Enable_Auto_Download,0xFFFFFFFF,(DWORD)0,(MUSIC_TIME)0,NULL); } } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::setTempoEnable( /* [retval][out] */ VARIANT_BOOL b) { HRESULT hr; DWORD trackIndex=0; __try { if (b==VARIANT_FALSE){ hr=m__dxj_DirectMusicSegment->SetParam(GUID_DisableTempo,0xFFFFFFFF,(DWORD)trackIndex,(MUSIC_TIME)0,NULL); } else { hr=m__dxj_DirectMusicSegment->SetParam(GUID_EnableTempo,0xFFFFFFFF,(DWORD)trackIndex,(MUSIC_TIME)0,NULL); } } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::setTimeSigEnable( /* [retval][out] */ VARIANT_BOOL b) { HRESULT hr; DWORD trackIndex=0; __try { if (b==VARIANT_FALSE){ hr=m__dxj_DirectMusicSegment->SetParam(GUID_DisableTimeSig,0xFFFFFFFF,(DWORD)trackIndex,(MUSIC_TIME)0,NULL); } else { hr=m__dxj_DirectMusicSegment->SetParam(GUID_EnableTimeSig,0xFFFFFFFF,(DWORD)trackIndex,(MUSIC_TIME)0,NULL); } } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::setStandardMidiFile() { HRESULT hr; __try { hr=m__dxj_DirectMusicSegment->SetParam(GUID_StandardMIDIFile,0xFFFFFFFF,(DWORD)0,(MUSIC_TIME)0,NULL); } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject:: connectToCollection( /* [in] */ I_dxj_DirectMusicCollection __RPC_FAR *c) { HRESULT hr; __try { DO_GETOBJECT_NOTNULL(IDirectMusicCollection8*,pCol,c); hr=m__dxj_DirectMusicSegment->SetParam(GUID_ConnectToDLSCollection,0xFFFFFFFF,(DWORD)0,(MUSIC_TIME)0,(void*)pCol); } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject:: GetAudioPathConfig(IUnknown **ret) { HRESULT hr; __try { if (FAILED(hr = m__dxj_DirectMusicSegment->GetAudioPathConfig(ret) )) return hr; } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return S_OK; } HRESULT C_dxj_DirectMusicSegmentObject::getStyle( /* [in] */ long lTrack, /* [retval][out] */ I_dxj_DirectMusicStyle __RPC_FAR *__RPC_FAR *ret) { HRESULT hr; IDirectMusicStyle *pStyle=NULL; __try { if (!ret) return E_INVALIDARG; *ret=NULL; hr=m__dxj_DirectMusicSegment->GetParam( GUID_IDirectMusicStyle, 0xffffffff, (DWORD)lTrack, 0, NULL, (VOID*)&pStyle ); if FAILED(hr) return hr; INTERNAL_CREATE_NOADDREF(_dxj_DirectMusicStyle,pStyle,ret); if (*ret==NULL) return E_OUTOFMEMORY; } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::getChordMap( /* [in] */ long lTrack, /* [in] */ long mtTime, /* [in] */ long *mtUntil, /* [retval][out] */ I_dxj_DirectMusicChordMap __RPC_FAR *__RPC_FAR *ret) { HRESULT hr; IDirectMusicChordMap *pMap=NULL; __try { if (!ret) return E_INVALIDARG; *ret=NULL; hr=m__dxj_DirectMusicSegment->GetParam(GUID_IDirectMusicChordMap,0xFFFFFFFF,(DWORD)lTrack,(MUSIC_TIME)mtTime,(MUSIC_TIME*)mtUntil,&pMap ); if FAILED(hr) return hr; INTERNAL_CREATE_NOADDREF(_dxj_DirectMusicChordMap,pMap,ret); if (*ret==NULL) return E_OUTOFMEMORY; } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return hr; } HRESULT C_dxj_DirectMusicSegmentObject::GetName(BSTR *ret) { HRESULT hr; IDirectMusicObject8 *pObj = NULL; DMUS_OBJECTDESC objDesc; __try { *ret=NULL; hr=m__dxj_DirectMusicSegment->QueryInterface(IID_IDirectMusicObject8, (void**) &pObj); if FAILED(hr) return hr; ZeroMemory(&objDesc, sizeof(DMUS_OBJECTDESC)); objDesc.dwSize = sizeof(DMUS_OBJECTDESC); pObj->GetDescriptor(&objDesc); if ((objDesc.dwValidData & DMUS_OBJ_NAME) == DMUS_OBJ_NAME) { //Return this name *ret = SysAllocString(objDesc.wszName); } else if ((objDesc.dwValidData & DMUS_OBJ_FILENAME) == DMUS_OBJ_FILENAME) { //Return this filename *ret = SysAllocString(objDesc.wszFileName); } } __except(EXCEPTION_EXECUTE_HANDLER) { return E_FAIL; } return S_OK; }
xformation/xformation-compliancemanager-service
compliancemanager-server/src/main/java/com/synectiks/process/server/inputs/converters/AbstractDateConverter.java
<filename>compliancemanager-server/src/main/java/com/synectiks/process/server/inputs/converters/AbstractDateConverter.java /* * */ package com.synectiks.process.server.inputs.converters; import org.joda.time.DateTimeZone; import com.synectiks.process.server.plugin.inputs.Converter; import java.util.Map; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Strings.emptyToNull; public abstract class AbstractDateConverter extends Converter { private static final DateTimeZone DEFAULT_TIME_ZONE = DateTimeZone.forID("Etc/UTC"); protected final DateTimeZone timeZone; public AbstractDateConverter(Type type, Map<String, Object> config) { super(type, config); this.timeZone = buildTimeZone(config.get("time_zone")); } private static DateTimeZone buildTimeZone(Object timeZoneId) { if (timeZoneId instanceof String) { try { final String timeZoneString = (String) timeZoneId; final String zoneId = firstNonNull(emptyToNull(timeZoneString.trim()), "Etc/UTC"); return DateTimeZone.forID(zoneId); } catch (IllegalArgumentException e) { return DEFAULT_TIME_ZONE; } } else { return DEFAULT_TIME_ZONE; } } @Override public boolean buildsMultipleFields() { return false; } }
UbuntuEvangelist/OG-Platform
projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/timeseries/util/TimeSeriesDifferenceOperator.java
<reponame>UbuntuEvangelist/OG-Platform /** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.timeseries.util; import org.apache.commons.lang.Validate; import com.opengamma.analytics.math.function.Function1D; import com.opengamma.timeseries.date.DateDoubleTimeSeries; import com.opengamma.timeseries.date.localdate.ImmutableLocalDateDoubleTimeSeries; /** * Operator to obtain the difference or absolute return of a time series: difference = V(end) - V(start) * The difference is taken between elements in the time series with a certain lag. * The default lag is 1 element, which means that the difference is between consecutive entries in the series. * The series returned has less element than the input series by the lag. * The dates of the returned time series are the dates of the end of the period on which the difference is computed. */ public class TimeSeriesDifferenceOperator extends Function1D<DateDoubleTimeSeries<?>, DateDoubleTimeSeries<?>> { /** The default lag: 1 time series element. */ private static final int DEFAULT_LAG = 1; /** The lag between the element of the times series on which the difference is taken. */ private final int _lag; /** * Constructor with the default lag of 1 element. */ public TimeSeriesDifferenceOperator() { this._lag = DEFAULT_LAG; } /** * Constructor with a specified lag. * @param lag The lag between element to compute the difference. */ public TimeSeriesDifferenceOperator(int lag) { this._lag = lag; } @Override public DateDoubleTimeSeries<?> evaluate(final DateDoubleTimeSeries<?> ts) { Validate.notNull(ts, "time series"); Validate.isTrue(ts.size() > _lag, "time series length must be > _lag"); final int[] times = ts.timesArrayFast(); final double[] values = ts.valuesArrayFast(); final int n = times.length; final int[] differenceTimes = new int[n - _lag]; final double[] differenceValues = new double[n - _lag]; for (int i = _lag; i < n; i++) { differenceTimes[i - _lag] = times[i]; differenceValues[i - _lag] = values[i] - values[i - _lag]; } return ImmutableLocalDateDoubleTimeSeries.of(differenceTimes, differenceValues); } }
kitman0000/D-Task
ServiceCenter/backEnd/src/main/java/com/dtask/center/bindingModule/service/IBinding.java
<reponame>kitman0000/D-Task package com.dtask.center.bindingModule.service; import com.dtask.center.bindingModule.bo.BindingRequestBo; import com.dtask.center.bindingModule.bo.NodeBo; import com.dtask.center.bindingModule.entity.AskBindingEntity; import com.dtask.center.bindingModule.entity.HandleBindingEntity; import com.dtask.center.bindingModule.entity.NodeEntity; import java.util.List; /** * Created by zhong on 2020-5-16. */ public interface IBinding { String askBanding(AskBindingEntity askBindingEntity); void addNode(NodeEntity nodeEntity); String handleBinding(HandleBindingEntity handleBindingEntity); int getNodeID(String nodeName); List<NodeBo> getAllNodes(); String unbind(NodeEntity nodeEntity); List<BindingRequestBo> getBindRequest(NodeEntity nodeEntity); String setRoot(NodeEntity nodeEntity); void receiveKeepAlive(int nodeID); }
mkawserm/flamed
pkg/app/graphql/mutation/jsontpmutator/batchprocess.go
package jsontpmutator import ( "github.com/graphql-go/graphql" "github.com/graphql-go/graphql/gqlerrors" "github.com/mkawserm/flamed/pkg/app/graphql/kind" "github.com/mkawserm/flamed/pkg/tp/json" "github.com/mkawserm/flamed/pkg/utility" "github.com/mkawserm/flamed/pkg/x" ) var GQLBatchProcess = &graphql.Field{ Name: "BatchProcess", Type: kind.GQLProposalResponseType, Description: "", Args: graphql.FieldConfigArgument{ "input": &graphql.ArgumentConfig{ Description: "Input JSON as list. " + "supported action: INSERT, UPSERT, UPDATE, MERGE, DELETE " + "example `[{action:\"INSERT\",data:{id:1,value:100}}," + "{action:\"UPSERT\",data:{id:2,value:5}}]`", Type: graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(kind.GQLJSONType))), }, }, Resolve: func(p graphql.ResolveParams) (interface{}, error) { input := p.Args["input"].([]interface{}) jsonContext, ok := p.Source.(*json.Context) if !ok { return nil, nil } if !utility.HasReadPermission(jsonContext.AccessControl) { return nil, gqlerrors.NewFormattedError(x.ErrReadPermissionRequired.Error()) } if !utility.HasWritePermission(jsonContext.AccessControl) { return nil, gqlerrors.NewFormattedError(x.ErrWritePermissionRequired.Error()) } if !utility.HasUpdatePermission(jsonContext.AccessControl) { return nil, gqlerrors.NewFormattedError(x.ErrUpdatePermissionRequired.Error()) } if !utility.HasDeletePermission(jsonContext.AccessControl) { return nil, gqlerrors.NewFormattedError(x.ErrDeletePermissionRequired.Error()) } batch := jsonContext.Client.NewBatch() for _, si := range input { sim := si.(map[string]interface{}) action := sim["action"].(string) data := sim["data"].(map[string]interface{}) switch action { case "INSERT": err := batch.InsertJSONMap(data) if err != nil { return nil, gqlerrors.NewFormattedError(err.Error()) } case "MERGE": err := batch.MergeJSONMap(data) if err != nil { return nil, gqlerrors.NewFormattedError(err.Error()) } case "UPDATE": err := batch.UpdateJSONMap(data) if err != nil { return nil, gqlerrors.NewFormattedError(err.Error()) } case "UPSERT": err := batch.UpsertJSONMap(data) if err != nil { return nil, gqlerrors.NewFormattedError(err.Error()) } case "DELETE": err := batch.DeleteJSONMap(data) if err != nil { return nil, gqlerrors.NewFormattedError(err.Error()) } } } pr, err := jsonContext.Client.ApplyBatch(batch) if err != nil { return nil, gqlerrors.NewFormattedError(err.Error()) } return pr, nil }, }
antonioeloy/livraria-api
src/main/java/br/com/alura/livraria/dto/LivroFormDto.java
<filename>src/main/java/br/com/alura/livraria/dto/LivroFormDto.java package br.com.alura.livraria.dto; import java.time.LocalDate; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.PastOrPresent; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Getter @Setter @AllArgsConstructor public class LivroFormDto { @NotBlank @Size(min = 10, max = 200) private String titulo; @NotNull @PastOrPresent private LocalDate dataLancamento; @NotNull @Min(value = 100) private Integer numeroPaginas; @NotNull private Long autorId; }
rydockman/YouPick
node_modules/@iconify-icons/clarity/firewall-outline-alerted.js
<filename>node_modules/@iconify-icons/clarity/firewall-outline-alerted.js<gh_stars>1-10 var data = { "body": "<path d=\"M33.68 15.4H32v5.68h-3.08v-4.81H27v4.81h-8.08v-4.81H17v4.81H8.9v-4.81H7v4.81H4V15h16.58a3.58 3.58 0 0 1-1.76-1.92H14v-4h-2v4H4V8h16.14l1.15-2H4a2 2 0 0 0-2 2v20a2 2 0 0 0 2 2h28a2 2 0 0 0 2-2V15.38zM23.8 28v-3.73h-1.6V28H14v-3.73h-1.6V28H4v-5h28v5z\" class=\"clr-i-outline--alerted clr-i-outline-path-1--alerted\" fill=\"currentColor\"/><path d=\"M26.85 1.14L21.13 11a1.28 1.28 0 0 0 1.1 2h11.45a1.28 1.28 0 0 0 1.1-2l-5.72-9.86a1.28 1.28 0 0 0-2.21 0z\" class=\"clr-i-outline--alerted clr-i-outline-path-2--alerted clr-i-alert\" fill=\"currentColor\"/>", "width": 36, "height": 36 }; export default data;
jacobvv/android-samples
utils/src/main/java/org/jacobvv/utils/BarUtils.java
<gh_stars>1-10 package org.jacobvv.utils; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.os.Build; import androidx.annotation.ColorInt; import androidx.annotation.IntRange; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; /** * @author yinhui * @date 18-6-11 */ @SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue", "ObsoleteSdkInt"}) public final class BarUtils { private static final String TAG = BarUtils.class.getSimpleName(); // Status bar part private static final int TAG_HAS_OFFSET = -123; /** * Return the status bar's height. * * @return the status bar's height */ public static int getStatusBarHeight() { Resources resources = Resources.getSystem(); int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android"); return resources.getDimensionPixelSize(resourceId); } /** * Return whether the status bar is visible. * * @param activity The activity. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isStatusBarVisible(@NonNull final Activity activity) { int flags = activity.getWindow().getAttributes().flags; return (flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0; } /** * Set the status bar's visibility. * * @param activity The activity. * @param isVisible True to set status bar visible, false otherwise. */ public static void setStatusBarVisibility(@NonNull final Activity activity, final boolean isVisible) { setStatusBarVisibility(activity.getWindow(), isVisible); } /** * Set the status bar's visibility. * * @param window The window. * @param isVisible True to set status bar visible, false otherwise. */ public static void setStatusBarVisibility(@NonNull final Window window, final boolean isVisible) { if (isVisible) { window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } } /** * Set the status bar's light mode. * * @param activity The activity. * @param isLightMode True to set status bar light mode, false otherwise. */ public static void setStatusBarLightMode(@NonNull final Activity activity, final boolean isLightMode) { setStatusBarLightMode(activity.getWindow(), isLightMode); } /** * Set the status bar's light mode. * * @param window The window. * @param isLightMode True to set status bar light mode, false otherwise. */ public static void setStatusBarLightMode(@NonNull final Window window, final boolean isLightMode) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return; } View decorView = window.getDecorView(); if (decorView == null) { return; } int vis = decorView.getSystemUiVisibility(); if (isLightMode) { window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } else { vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } decorView.setSystemUiVisibility(vis); } /** * Add the top margin size equals status bar's height for view. * * @param view The view. */ public static void addMarginTopEqualStatusBarHeight(@NonNull View view) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } Object haveSetOffset = view.getTag(TAG_HAS_OFFSET); if (haveSetOffset != null && (Boolean) haveSetOffset) { return; } ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin + getStatusBarHeight(), layoutParams.rightMargin, layoutParams.bottomMargin); view.setTag(TAG_HAS_OFFSET, true); } /** * Subtract the top margin size equals status bar's height for view. * * @param view The view. */ public static void subtractMarginTopEqualStatusBarHeight(@NonNull View view) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return; } Object haveSetOffset = view.getTag(TAG_HAS_OFFSET); if (haveSetOffset == null || !(Boolean) haveSetOffset) { return; } ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); layoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin - getStatusBarHeight(), layoutParams.rightMargin, layoutParams.bottomMargin); view.setTag(TAG_HAS_OFFSET, false); } /** * Set the status bar's color. * * @param activity The activity. * @param color The status bar's color. */ public static void setStatusBarColor(@NonNull final Activity activity, @ColorInt final int color) { setStatusBarColor(activity, color, 255); } /** * Set the status bar's color. * * @param activity The activity. * @param color The status bar's color. * @param alpha The status bar's alpha which isn't the same as alpha in the color. */ public static void setStatusBarColor(@NonNull final Activity activity, @ColorInt final int color, @IntRange(from = 0, to = 255) final int alpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { return; } Window window = activity.getWindow(); int colorWithAlpha = (alpha << 24) | (color & 0x00FFFFFF); window.setStatusBarColor(colorWithAlpha); activity.setImmersive(true); } /** * Set the status bar's alpha. * * @param activity The activity. * @param alpha The status bar's alpha. */ public static void setStatusBarAlpha(@NonNull final Activity activity, @IntRange(from = 0, to = 255) final int alpha) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { return; } Window window = activity.getWindow(); int color = window.getStatusBarColor(); int colorWithAlpha = (alpha << 24) | (color & 0x00FFFFFF); window.setStatusBarColor(colorWithAlpha); activity.setImmersive(true); } // // private static void setStatusBarTransparent(final Activity activity) { // Window window = activity.getWindow(); // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); // int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; // window.getDecorView().setSystemUiVisibility(option); // window.setStatusBarColor(Color.TRANSPARENT); // } else { // window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // } // } // // // Title bar part // // public static void setTitleBarImmersive(Activity activity, PhiTitleBar titleBar) { // setTitleBarImmersive(activity, titleBar, null); // } // // public static void setTitleBarImmersive(Activity activity, PhiTitleBar titleBar, @ColorInt Integer color) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // View decorView = activity.getWindow().getDecorView(); // int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; // decorView.setSystemUiVisibility(option); // int colorOrTrans = color == null ? Color.TRANSPARENT : color; // activity.getWindow().setStatusBarColor(colorOrTrans); // titleBar.setImmersive(true); // } else { // titleBar.setImmersive(false); // } // titleBar.setAllCaps(true); // ActionBar actionBar = activity.getActionBar(); // if (actionBar != null) { // actionBar.hide(); // } // } /** * Return the action bar's height. * * @return the action bar's height */ public static int getActionBarHeight(Context context) { TypedValue tv = new TypedValue(); if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { return TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics()); } return 0; } // Navigation bar /** * Return the navigation bar's height. * * @return the navigation bar's height */ public static int getNavBarHeight() { Resources res = Resources.getSystem(); int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId != 0) { return res.getDimensionPixelSize(resourceId); } else { return 0; } } /** * Set the navigation bar's visibility. * * @param activity The activity. * @param isVisible True to set notification bar visible, false otherwise. */ public static void setNavBarVisibility(@NonNull final Activity activity, boolean isVisible) { setNavBarVisibility(activity.getWindow(), isVisible); } /** * Set the navigation bar's visibility. * * @param window The window. * @param isVisible True to set notification bar visible, false otherwise. */ public static void setNavBarVisibility(@NonNull final Window window, boolean isVisible) { if (isVisible) { window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } else { window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); View decorView = window.getDecorView(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { int visibility = decorView.getSystemUiVisibility(); decorView.setSystemUiVisibility(visibility & ~View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } } /** * Set the navigation bar immersive. * * @param activity The activity. */ @RequiresApi(Build.VERSION_CODES.KITKAT) public static void setNavBarImmersive(@NonNull final Activity activity) { setNavBarImmersive(activity.getWindow()); } /** * Set the navigation bar immersive. * * @param window The window. */ @RequiresApi(Build.VERSION_CODES.KITKAT) public static void setNavBarImmersive(@NonNull final Window window) { View decorView = window.getDecorView(); window.clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; decorView.setSystemUiVisibility(uiOptions); } /** * Set the navigation bar's color. * * @param activity The activity. * @param color The navigation bar's color. */ @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public static void setNavBarColor(@NonNull final Activity activity, @ColorInt final int color) { setNavBarColor(activity.getWindow(), color); } /** * Set the navigation bar's color. * * @param window The window. * @param color The navigation bar's color. */ @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public static void setNavBarColor(@NonNull final Window window, @ColorInt final int color) { window.setNavigationBarColor(color); } /** * Return the color of navigation bar. * * @param activity The activity. * @return the color of navigation bar */ @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public static int getNavBarColor(@NonNull final Activity activity) { return getNavBarColor(activity.getWindow()); } /** * Return the color of navigation bar. * * @param window The window. * @return the color of navigation bar */ @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public static int getNavBarColor(@NonNull final Window window) { return window.getNavigationBarColor(); } /** * Return whether the navigation bar visible. * * @param activity The activity. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isNavBarVisible(@NonNull final Activity activity) { return isNavBarVisible(activity.getWindow()); } /** * Return whether the navigation bar visible. * * @param window The window. * @return {@code true}: yes<br>{@code false}: no */ public static boolean isNavBarVisible(@NonNull final Window window) { boolean isNoLimits = (window.getAttributes().flags & WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS) != 0; if (isNoLimits) { return false; } View decorView = window.getDecorView(); int visibility = decorView.getSystemUiVisibility(); return (visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0; } }
polyurfms/nucore-open
db/migrate/20201127093634_create_account_user_expenses.rb
<filename>db/migrate/20201127093634_create_account_user_expenses.rb class CreateAccountUserExpenses < ActiveRecord::Migration[5.2] def change create_view :account_user_expenses end end
epinter/Partner-Center-Java
src/main/java/com/microsoft/store/partnercenter/models/entitlements/ReferenceOrder.java
// ----------------------------------------------------------------------- // <copyright file="ReferenceOrder.java" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- package com.microsoft.store.partnercenter.models.entitlements; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.store.partnercenter.models.ResourceBaseWithLinks; import com.microsoft.store.partnercenter.models.StandardResourceLinks; /** * Class that represents an order linked to the entitlement. */ public class ReferenceOrder extends ResourceBaseWithLinks<StandardResourceLinks> { /** * Gets or sets order id. */ @JsonProperty( "id" ) private String __Id; public String getId() { return __Id; } public void setId( String value ) { __Id = value; } /** * Gets or sets order line item id. */ @JsonProperty( "lineItemId" ) private String __LineItemId; public String getLineItemId() { return __LineItemId; } public void setLineItemId( String value ) { __LineItemId = value; } }
xsthunder/a
individually_weekly/w10/B.cc
<reponame>xsthunder/a #include<iostream> #include<cmath> #include<iomanip> #include<utility> #include<vector> #include<queue> #include<algorithm> #include<cstring> #include<map> #define mk(a,b) make_pair(a,b) using namespace std; void inp(); void fld(); const int N =100+100; typedef int E[N][N]; E e; int n,ec; typedef pair<int,int> pqe; const int test=0; #define IF if(test) void pM(int width=4){ cout<<0; for(int j =1;j<=n;j++){ cout<<setw(width)<<j; } cout<<endl; for(int i =1;i<=n;i++){ cout<<i<<' '; for(int j =1;j<=n;j++){ cout<<setw(width)<<e[i][j]; } cout<<endl; } cout<<endl; } void fld(){ for(int k=1;k<=n;k++){ for(int i =1;i<=n;i++){ for(int j=1;j<=n;j++){ e[i][j]=max(e[i][j],min(e[i][k],e[k][j])); } //IF pM(); } } } int main(){ cin.tie(0); ios_base::sync_with_stdio(0); int cnt=0; while(cin>>n>>ec){ if(n==0&&ec==0)return 0; inp(); int s,t,p; cin>>s>>t>>p; fld(); p++; int div; div = e[s][t]-1; IF cout<<s<<' '<<t<<endl;; IF cout<<p<<' '<<div<<endl; IF if(div==0){ pM(); return 0; } cout<<"Scenario #"<<++cnt<<endl; if(cnt==7)cout<<div<<endl; cout<<"Minimum Number of Trips = "<<ceil((p*1.0f)/div)<<endl;; cout<<endl; } return 0; } const int inf = 1e9; void inp(){ for(int i =1;i<=n;i++){ for(int j=1;j<=n;j++){ e[i][j]=0; } } for(int i =0;i<ec;i++){ int a,b,c; cin>>a>>b>>c; e[a][b]=c; e[b][a]=c; } }
HaoyeTianCoder/coming
src/main/resources/repairability_test_files/ground_truth/Cardumen/patch1-Math-101-Cardumen/Cardumen/0032/Cardumen_0032_t.java
<reponame>HaoyeTianCoder/coming<gh_stars>10-100 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.complex; import java.io.Serializable; import java.text.FieldPosition; import java.text.Format; import java.text.NumberFormat; import java.text.ParseException; import java.text.ParsePosition; import java.util.Locale; /** * Formats a Complex number in cartesian format "Re(c) + Im(c)i". 'i' can * be replaced with 'j', and the number format for both real and imaginary parts * can be configured. * * @author Apache Software Foundation * @version $Revision$ $Date$ */ public class ComplexFormat extends Format implements Serializable { /** Serializable version identifier */ private static final long serialVersionUID = -6337346779577272306L; /** The default imaginary character. */ private static final String DEFAULT_IMAGINARY_CHARACTER = "i"; /** The notation used to signify the imaginary part of the complex number. */ private String imaginaryCharacter; /** The format used for the imaginary part. */ private NumberFormat imaginaryFormat; /** The format used for the real part. */ private NumberFormat realFormat; /** * Create an instance with the default imaginary character, 'i', and the * default number format for both real and imaginary parts. */ public ComplexFormat() { this(DEFAULT_IMAGINARY_CHARACTER, getDefaultNumberFormat()); } /** * Create an instance with a custom number format for both real and * imaginary parts. * @param format the custom format for both real and imaginary parts. */ public ComplexFormat(NumberFormat format) { this(DEFAULT_IMAGINARY_CHARACTER, format); } /** * Create an instance with a custom number format for the real part and a * custom number format for the imaginary part. * @param realFormat the custom format for the real part. * @param imaginaryFormat the custom format for the imaginary part. */ public ComplexFormat(NumberFormat realFormat, NumberFormat imaginaryFormat) { this(DEFAULT_IMAGINARY_CHARACTER, realFormat, imaginaryFormat); } /** * Create an instance with a custom imaginary character, and the default * number format for both real and imaginary parts. * @param imaginaryCharacter The custom imaginary character. */ public ComplexFormat(String imaginaryCharacter) { this(imaginaryCharacter, getDefaultNumberFormat()); } /** * Create an instance with a custom imaginary character, and a custom number * format for both real and imaginary parts. * @param imaginaryCharacter The custom imaginary character. * @param format the custom format for both real and imaginary parts. */ public ComplexFormat(String imaginaryCharacter, NumberFormat format) { this(imaginaryCharacter, format, (NumberFormat)format.clone()); } /** * Create an instance with a custom imaginary character, a custom number * format for the real part, and a custom number format for the imaginary * part. * @param imaginaryCharacter The custom imaginary character. * @param realFormat the custom format for the real part. * @param imaginaryFormat the custom format for the imaginary part. */ public ComplexFormat(String imaginaryCharacter, NumberFormat realFormat, NumberFormat imaginaryFormat) { super(); setImaginaryCharacter(imaginaryCharacter); setImaginaryFormat(imaginaryFormat); setRealFormat(realFormat); } /** * This static method calls formatComplex() on a default instance of * ComplexFormat. * * @param c Complex object to format * @return A formatted number in the form "Re(c) + Im(c)i" */ public static String formatComplex( Complex c ) { return getInstance().format( c ); } /** * Formats a {@link Complex} object to produce a string. * * @param complex the object to format. * @param toAppendTo where the text is to be appended * @param pos On input: an alignment field, if desired. On output: the * offsets of the alignment field * @return the value passed in as toAppendTo. */ public StringBuffer format(Complex complex, StringBuffer toAppendTo, FieldPosition pos) { pos.setBeginIndex(0); pos.setEndIndex(0); // format real double re = complex.getReal(); formatDouble(re, getRealFormat(), toAppendTo, pos); // format sign and imaginary double im = complex.getImaginary(); if (im < 0.0) { toAppendTo.append(" - "); formatDouble(-im, getImaginaryFormat(), toAppendTo, pos); toAppendTo.append(getImaginaryCharacter()); } else if (im > 0.0 || Double.isNaN(im)) { toAppendTo.append(" + "); formatDouble(im, getImaginaryFormat(), toAppendTo, pos); toAppendTo.append(getImaginaryCharacter()); } return toAppendTo; } /** * Formats a object to produce a string. <code>obj</code> must be either a * {@link Complex} object or a {@link Number} object. Any other type of * object will result in an {@link IllegalArgumentException} being thrown. * * @param obj the object to format. * @param toAppendTo where the text is to be appended * @param pos On input: an alignment field, if desired. On output: the * offsets of the alignment field * @return the value passed in as toAppendTo. * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition) * @throws IllegalArgumentException is <code>obj</code> is not a valid type. */ public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { StringBuffer ret = null; if (obj instanceof Complex) { ret = format( (Complex)obj, toAppendTo, pos); } else if (obj instanceof Number) { ret = format( new Complex(((Number)obj).doubleValue(), 0.0), toAppendTo, pos); } else { throw new IllegalArgumentException( "Cannot format given Object as a Date"); } return ret; } /** * Formats a double value to produce a string. In general, the value is * formatted using the formatting rules of <code>format</code>. There are * three exceptions to this: * <ol> * <li>NaN is formatted as '(NaN)'</li> * <li>Positive infinity is formatted as '(Infinity)'</li> * <li>Negative infinity is formatted as '(-Infinity)'</li> * </ol> * * @param value the double to format. * @param format the format used. * @param toAppendTo where the text is to be appended * @param pos On input: an alignment field, if desired. On output: the * offsets of the alignment field * @return the value passed in as toAppendTo. */ private StringBuffer formatDouble(double value, NumberFormat format, StringBuffer toAppendTo, FieldPosition pos) { if( Double.isNaN(value) || Double.isInfinite(value) ) { toAppendTo.append('('); toAppendTo.append(value); toAppendTo.append(')'); } else { format.format(value, toAppendTo, pos); } return toAppendTo; } /** * Get the set of locales for which complex formats are available. This * is the same set as the {@link NumberFormat} set. * @return available complex format locales. */ public static Locale[] getAvailableLocales() { return NumberFormat.getAvailableLocales(); } /** * Create a default number format. The default number format is based on * {@link NumberFormat#getInstance()} with the only customizing is the * maximum number of fraction digits, which is set to 2. * @return the default number format. */ private static NumberFormat getDefaultNumberFormat() { return getDefaultNumberFormat(Locale.getDefault()); } /** * Create a default number format. The default number format is based on * {@link NumberFormat#getInstance(java.util.Locale)} with the only * customizing is the maximum number of fraction digits, which is set to 2. * @param locale the specific locale used by the format. * @return the default number format specific to the given locale. */ private static NumberFormat getDefaultNumberFormat(Locale locale) { NumberFormat nf = NumberFormat.getInstance(locale); nf.setMaximumFractionDigits(2); return nf; } /** * Access the imaginaryCharacter. * @return the imaginaryCharacter. */ public String getImaginaryCharacter() { return imaginaryCharacter; } /** * Access the imaginaryFormat. * @return the imaginaryFormat. */ public NumberFormat getImaginaryFormat() { return imaginaryFormat; } /** * Returns the default complex format for the current locale. * @return the default complex format. */ public static ComplexFormat getInstance() { return getInstance(Locale.getDefault()); } /** * Returns the default complex format for the given locale. * @param locale the specific locale used by the format. * @return the complex format specific to the given locale. */ public static ComplexFormat getInstance(Locale locale) { NumberFormat f = getDefaultNumberFormat(locale); return new ComplexFormat(f); } /** * Access the realFormat. * @return the realFormat. */ public NumberFormat getRealFormat() { return realFormat; } /** * Parses a string to produce a {@link Complex} object. * * @param source the string to parse * @return the parsed {@link Complex} object. * @exception ParseException if the beginning of the specified string * cannot be parsed. */ public Complex parse(String source) throws ParseException { ParsePosition parsePosition = new ParsePosition(0); Complex result = parse(source, parsePosition); if (parsePosition.getIndex() == 0) { throw new ParseException("Unparseable complex number: \"" + source + "\"", parsePosition.getErrorIndex()); } return result; } /** * Parses a string to produce a {@link Complex} object. * * @param source the string to parse * @param pos input/ouput parsing parameter. * @return the parsed {@link Complex} object. */ public Complex parse(String source, ParsePosition pos) { int initialIndex = pos.getIndex(); // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse real Number re = parseNumber(source, getRealFormat(), pos); if (re == null) { // invalid real number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } // parse sign int startIndex = pos.getIndex(); char c = parseNextCharacter(source, pos); int sign = 0; switch (c) { case 0 : // no sign // return real only complex number return new Complex(re.doubleValue(), 0.0); case '-' : sign = -1; break; case '+' : sign = 1; break; default : // invalid sign // set index back to initial, error index should be the last // character examined. pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse imaginary Number im = parseNumber(source, getRealFormat(), pos); if (im == null) { // invalid imaginary number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } // parse imaginary character int n = getImaginaryCharacter().length(); startIndex = pos.getIndex(); int endIndex = source.length(); if ( source.substring(startIndex, endIndex).compareTo( getImaginaryCharacter()) != 0) { // set index back to initial, error index should be the start index // character examined. pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } pos.setIndex(endIndex); return new Complex(re.doubleValue(), im.doubleValue() * sign); } /** * Parses <code>source</code> until a non-whitespace character is found. * * @param source the string to parse * @param pos input/ouput parsing parameter. On output, <code>pos</code> * holds the index of the next non-whitespace character. */ private void parseAndIgnoreWhitespace(String source, ParsePosition pos) { parseNextCharacter(source, pos); pos.setIndex(pos.getIndex() - 1); } /** * Parses <code>source</code> until a non-whitespace character is found. * * @param source the string to parse * @param pos input/ouput parsing parameter. * @return the first non-whitespace character. */ private char parseNextCharacter(String source, ParsePosition pos) { int index = pos.getIndex(); int n = source.length(); char ret = 0; if (index < n) { char c; do { c = source.charAt(index++); } while (Character.isWhitespace(c) && index < n); pos.setIndex(index); if (index < n) { ret = c; } } return ret; } /** * Parses <code>source</code> for a special double values. These values * include Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY. * * @param source the string to parse * @param value the special value to parse. * @param pos input/ouput parsing parameter. * @return the special number. */ private Number parseNumber(String source, double value, ParsePosition pos) { Number ret = null; StringBuffer sb = new StringBuffer(); sb.append('('); sb.append(value); sb.append(')'); int n = sb.length(); int startIndex = pos.getIndex(); int endIndex = startIndex + n; if (endIndex < source.length()) { if (source.substring(startIndex, endIndex).compareTo(sb.toString()) == 0) { ret = new Double(value); pos.setIndex(endIndex); } } return ret; } /** * Parses <code>source</code> for a number. This method can parse normal, * numeric values as well as special values. These special values include * Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY. * * @param source the string to parse * @param format the number format used to parse normal, numeric values. * @param pos input/ouput parsing parameter. * @return the parsed number. */ private Number parseNumber(String source, NumberFormat format, ParsePosition pos) { int startIndex = pos.getIndex(); Number number = format.parse(source, pos); int endIndex = pos.getIndex(); // check for error parsing number if (startIndex == endIndex) { // try parsing special numbers double[] special = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}; for (int i = 0; i < special.length; ++i) { number = parseNumber(source, special[i], pos); if (number != null) { break; } } } return number; } /** * Parses a string to produce a object. * * @param source the string to parse * @param pos input/ouput parsing parameter. * @return the parsed object. * @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition) */ public Object parseObject(String source, ParsePosition pos) { return parse(source, pos); } /** * Modify the imaginaryCharacter. * @param imaginaryCharacter The new imaginaryCharacter value. * @throws IllegalArgumentException if <code>imaginaryCharacter</code> is * <code>null</code> or an empty string. */ public void setImaginaryCharacter(String imaginaryCharacter) { if (imaginaryCharacter == null || imaginaryCharacter.length() == 0) { throw new IllegalArgumentException( "imaginaryCharacter must be a non-empty string."); } this.imaginaryCharacter = imaginaryCharacter; } /** * Modify the imaginaryFormat. * @param imaginaryFormat The new imaginaryFormat value. * @throws IllegalArgumentException if <code>imaginaryFormat</code> is * <code>null</code>. */ public void setImaginaryFormat(NumberFormat imaginaryFormat) { if (imaginaryFormat == null) { throw new IllegalArgumentException( "imaginaryFormat can not be null."); } this.imaginaryFormat = imaginaryFormat; } /** * Modify the realFormat. * @param realFormat The new realFormat value. * @throws IllegalArgumentException if <code>realFormat</code> is * <code>null</code>. */ public void setRealFormat(NumberFormat realFormat) { if (realFormat == null) { throw new IllegalArgumentException( "realFormat can not be null."); } this.realFormat = realFormat; } }
fu7mu4/entonetics
sfml/samples/voip/Client.cpp
//////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Audio.hpp> #include <SFML/Network.hpp> #include <iostream> const sf::Uint8 AudioData = 1; const sf::Uint8 EndOfStream = 2; //////////////////////////////////////////////////////////// /// Specialization of audio recorder for sending recorded audio /// data through the network //////////////////////////////////////////////////////////// class NetworkRecorder : public sf::SoundRecorder { public : //////////////////////////////////////////////////////////// /// Constructor /// /// \param Socket : Socket that holds the connection with the server /// //////////////////////////////////////////////////////////// NetworkRecorder(sf::SocketTCP Socket) : mySocket(Socket) { } private : //////////////////////////////////////////////////////////// /// /see sfSoundRecorder::ProcessSamples /// //////////////////////////////////////////////////////////// virtual bool ProcessSamples(const sf::Int16* Samples, std::size_t SamplesCount) { // Pack the audio samples into a network packet sf::Packet PacketOut; PacketOut << AudioData; PacketOut.Append(Samples, SamplesCount * sizeof(sf::Int16)); // Send the audio packet to the server return mySocket.Send(PacketOut) == sf::Socket::Done; } //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// sf::SocketTCP mySocket; ///< Socket used to communicate with the server }; //////////////////////////////////////////////////////////// /// Create a client, connect it to a running server and /// start sending him audio data /// //////////////////////////////////////////////////////////// void DoClient(unsigned short Port) { // Check that the device can capture audio if (sf::SoundRecorder::CanCapture() == false) { std::cout << "Sorry, audio capture is not supported by your system" << std::endl; return; } // Ask for server address sf::IPAddress ServerAddress; do { std::cout << "Type address or name of the server to connect to : "; std::cin >> ServerAddress; } while (!ServerAddress.IsValid()); // Create a TCP socket for communicating with server sf::SocketTCP Socket; // Connect to the specified server if (!Socket.Connect(Port, ServerAddress)) return; std::cout << "Connected to server " << ServerAddress << std::endl; // Wait for user input... std::cin.ignore(10000, '\n'); std::cout << "Press enter to start recording audio"; std::cin.ignore(10000, '\n'); // Create a instance of our custom recorder NetworkRecorder Recorder(Socket); // Start capturing audio data Recorder.Start(44100); std::cout << "Recording... press enter to stop"; std::cin.ignore(10000, '\n'); Recorder.Stop(); // Send a "end-of-stream" packet sf::Packet PacketOut; PacketOut << EndOfStream; Socket.Send(PacketOut); // Close the socket when we're done Socket.Close(); }
Sumit2792/logisticsApplication
src/main/java/com/fw/enums/LengthUnits.java
package com.fw.enums; public enum LengthUnits { FEET("FEET"), METER("METER"), CENTIMETER("CENTIMETER"); private final String dbString; private LengthUnits(String dbString) { this.dbString = dbString; } public String toDbString() { return (this.dbString); } public static LengthUnits fromString(String str) { if ("FEET".equalsIgnoreCase(str)) { return (FEET); } else if ("METER".equalsIgnoreCase(str)) { return (METER); } else if ("CENTIMETER".equalsIgnoreCase(str)) { return (CENTIMETER); } else { throw new RuntimeException("No such unit type:" + str); } } }
CjHare/systematic-trading
systematic-trading-simulation/src/main/java/com/systematic/trading/simulation/Simulation.java
<gh_stars>1-10 /** * Copyright (c) 2015-2018, <NAME> 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 [project] 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. */ package com.systematic.trading.simulation; import java.time.LocalDate; import java.time.Period; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.systematic.trading.model.TickerSymbolTradingData; import com.systematic.trading.model.price.TradingDayPrices; import com.systematic.trading.simulation.SimulationStateListener.SimulationState; import com.systematic.trading.simulation.analysis.roi.ReturnOnInvestmentListener; import com.systematic.trading.simulation.brokerage.Brokerage; import com.systematic.trading.simulation.brokerage.exception.InsufficientEquitiesException; import com.systematic.trading.simulation.cash.CashAccount; import com.systematic.trading.simulation.cash.exception.InsufficientFundsException; import com.systematic.trading.simulation.order.EquityOrder; import com.systematic.trading.simulation.order.EquityOrderInsufficientFundsAction; import com.systematic.trading.simulation.order.event.EquityOrderDeletedDueToInsufficentFundsEvent; import com.systematic.trading.simulation.order.event.OrderEvent; import com.systematic.trading.simulation.order.event.OrderEventListener; import com.systematic.trading.strategy.Strategy; /** * The application of the chosen trading logic over a given set of data is performed in the * Simulation. * <p/> * Applies the trading logic over a single equity only. * * @author <NAME> */ public class Simulation { /** Classes logger. */ private static final Logger LOG = LogManager.getLogger(Simulation.class); /** Makes the decision on whether entry and exit actions. */ private final Strategy strategy; /** The manager dealing with cash and it's accounting. */ private final CashAccount funds; /** Dealer of equities, manages the equity balance. */ private final Brokerage broker; /** Time between deposit events. */ private final Period interval = Period.ofDays(1); /** Return on investment calculator. */ private final ReturnOnInvestmentListener roi; /** Listeners interested in entry events. */ private final List<OrderEventListener> orderEventListeners = new ArrayList<>(); /** Listeners interested in state transition events. */ private final List<SimulationStateListener> stateListeners = new ArrayList<>(); /** Trading data to use for the simulation. */ private final TickerSymbolTradingData tradingData; public Simulation( final TickerSymbolTradingData tradingData, final Brokerage broker, final CashAccount funds, final ReturnOnInvestmentListener roi, final Strategy strategy ) { this.strategy = strategy; this.funds = funds; this.broker = broker; this.roi = roi; this.tradingData = tradingData; } public void run() { final Map<LocalDate, TradingDayPrices> tradingDayPrices = tradingData.tradingPrices(); final LocalDate endDate = tradingData.latestDate(); List<EquityOrder> orders = new ArrayList<>(); LocalDate currentDate = tradingData.earliestDate(); while (currentDate.isBefore(endDate)) { // Financial activity of deposits, withdrawal and interest funds.update(currentDate); final TradingDayPrices currentTradingData = tradingDayPrices.get(currentDate); // Only when there is trading data for today if (currentTradingData != null) { // Process orders and add those from the day's trading data orders = processTradingData(currentTradingData, orders); // Update the return on investment calculator roi.update(broker, funds, currentTradingData); // Broker activity of fees, clearing transactions at the end of the business day broker.update(currentTradingData); } // Move date to tomorrow currentDate = currentDate.plus(interval); } notifyListeners(SimulationState.COMPLETE); } /** * Adds the listener to the set of order event listeners. * * @param listener * will receive notification of order event occurrences. */ public void addListener( final OrderEventListener listener ) { if (!orderEventListeners.contains(listener)) { orderEventListeners.add(listener); } } /** * Adds the listener to the set of state transition listeners. * * @param listener * will receive notification of simulation state change occurrences. */ public void addListener( final SimulationStateListener listener ) { if (!stateListeners.contains(listener)) { stateListeners.add(listener); } } /** * Processes any outstanding orders when their execution criteria and add any additional orders * based on the day's trading data. * * @param tradingDataToday * trading data for today. * @param orders * orders carried over from yesterday. * @return the outstanding orders to carry over to tomorrow. */ private List<EquityOrder> processTradingData( final TradingDayPrices tradingDataToday, final List<EquityOrder> orders ) { // Attempt to execute the queued orders final List<EquityOrder> withoutAnyOutstandingOrders = processOutstandingOrders(orders, tradingDataToday); // Apply analysis to generate more orders final List< EquityOrder> exitOrdersIncluded = addExitOrderForToday(tradingDataToday, withoutAnyOutstandingOrders); return addEntryOrderForToday(tradingDataToday, exitOrdersIncluded); } /** * Update the exit logic analysis, adding any orders triggered by the day's trading data. * * @param data * todays trading data. * @param openOrders * the existing trading orders unfulfilled. * @return the given list of open orders, plus any order added by the exit logic. */ private List<EquityOrder> addExitOrderForToday( final TradingDayPrices data, final List<EquityOrder> openOrders ) { final Optional<EquityOrder> order = strategy.exitTick(broker, data); if (order.isPresent()) { notifyListeners(order.get().orderEvent()); openOrders.add(order.get()); } return openOrders; } /** * Update the entry logic analysis, adding any orders triggered by the day's trading data. * * @param data * todays trading data. * @param openOrders * the existing trading orders unfulfilled. * @return the given list of open orders, plus any order added by the entry logic. */ private List<EquityOrder> addEntryOrderForToday( final TradingDayPrices data, final List<EquityOrder> openOrders ) { final Optional<EquityOrder> order = strategy.entryTick(broker, funds, data); if (order.isPresent()) { notifyListeners(order.get().orderEvent()); openOrders.add(order.get()); } return openOrders; } /** * Attempts to process the outstanding orders against today's price action. * * @return orders that were not executed as their conditions were not met. */ private List<EquityOrder> processOutstandingOrders( final List<EquityOrder> orders, final TradingDayPrices data ) { final List<EquityOrder> remainingOrders = new ArrayList<>(orders.size()); for (final EquityOrder order : orders) { if (order.isValid(data)) { final EquityOrder processedOrder = processOutstandingValidOrder(order, data); // Add the original / altered order back to try again if (processedOrder != null) { remainingOrders.add(processedOrder); } } } return remainingOrders; } /** * Processes the order based on whether the execution criteria are met. * * @return the order that may or may not have been executed. */ private EquityOrder processOutstandingValidOrder( final EquityOrder order, final TradingDayPrices data ) { if (order.areExecutionConditionsMet(data)) { return executeOrder(order, data); } return order; } /** * Attempt to execute the order. * * @param order * trade to execute. * @return <code>null</code> on success, or an order to re-attempt next cycle. * @throws OrderException */ private EquityOrder executeOrder( final EquityOrder order, final TradingDayPrices data ) { try { order.execute(broker, broker, funds, data); // Discard the order, as it's processed return null; } catch (final InsufficientFundsException e) { final EquityOrderInsufficientFundsAction action = strategy.actionOnInsufficentFunds(order); switch (action) { case DELETE: // Discard the order notifyListeners(new EquityOrderDeletedDueToInsufficentFundsEvent(order.orderEvent())); return null; case RESUMIT: default: throw new IllegalArgumentException( String.format( "Unsupported insufficient funds action: %s for order: %s using strategy: %s", action, order, strategy), e); } } catch (final InsufficientEquitiesException e) { logExecutionException(e); throw new IllegalArgumentException("Unhandled Order exception", e); } } private void notifyListeners( final OrderEvent event ) { for (final OrderEventListener listener : orderEventListeners) { listener.event(event); } } private void notifyListeners( final SimulationState event ) { for (final SimulationStateListener listener : stateListeners) { listener.stateChanged(event); } } private void logExecutionException( final InsufficientEquitiesException e ) { LOG.error(e); } }
shaojiankui/iOS10-Runtime-Headers
PrivateFrameworks/EmbeddedAcousticRecognition.framework/_EARSpeechExperiment.h
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/EmbeddedAcousticRecognition.framework/EmbeddedAcousticRecognition */ @interface _EARSpeechExperiment : NSObject { _EARSpeechRecognizer * _recognizer; _EARUserProfile * _userProfile; } - (void).cxx_destruct; - (void)evaluateScript:(id)arg1 archiveData:(id)arg2 completion:(id /* block */)arg3; - (void)evaluateScript:(id)arg1 completion:(id /* block */)arg2; - (id)initWithRecognizer:(id)arg1 userProfile:(id)arg2; @end
thl-mot/mbed-os
connectivity/nanostack/sal-stack-nanostack/source/Security/protocols/msg_sec_prot/msg_sec_prot.c
<filename>connectivity/nanostack/sal-stack-nanostack/source/Security/protocols/msg_sec_prot/msg_sec_prot.c<gh_stars>1000+ /* * Copyright (c) 2021, Pelion and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "nsconfig.h" #include <string.h> #include "ns_types.h" #include "ns_list.h" #include "ns_trace.h" #include "nsdynmemLIB.h" #include "fhss_config.h" #include "NWK_INTERFACE/Include/protocol.h" #include "6LoWPAN/ws/ws_config.h" #include "Security/protocols/sec_prot_cfg.h" #include "Security/kmp/kmp_addr.h" #include "Security/kmp/kmp_api.h" #include "Security/PANA/pana_eap_header.h" #include "Security/eapol/eapol_helper.h" #include "Security/eapol/kde_helper.h" #include "Security/protocols/sec_prot_certs.h" #include "Security/protocols/sec_prot_keys.h" #include "Security/protocols/sec_prot.h" #include "Security/protocols/sec_prot_lib.h" #include "Security/protocols/msg_sec_prot/msg_sec_prot.h" #ifdef HAVE_WS #define TRACE_GROUP "msep" typedef enum { MSG_STATE_INIT = SEC_STATE_INIT, MSG_STATE_CREATE_REQ = SEC_STATE_CREATE_REQ, MSG_STATE_FINISH = SEC_STATE_FINISH, MSG_STATE_FINISHED = SEC_STATE_FINISHED } msg_sec_prot_state_e; typedef struct { sec_prot_common_t common; /**< Common data */ } msg_sec_prot_int_t; static uint16_t msg_sec_prot_size(void); static int8_t msg_sec_prot_init(sec_prot_t *prot); static void msg_sec_prot_delete(sec_prot_t *prot); static void msg_sec_prot_create_request(sec_prot_t *prot, sec_prot_keys_t *sec_keys); static void msg_sec_prot_state_machine(sec_prot_t *prot); static int8_t msg_sec_prot_auth_rejected_send(sec_prot_t *prot, sec_prot_keys_t *sec_keys); #define msg_sec_prot_get(prot) (msg_sec_prot_int_t *) &prot->data int8_t msg_sec_prot_register(kmp_service_t *service) { if (!service) { return -1; } if (kmp_service_sec_protocol_register(service, MSG_PROT, msg_sec_prot_size, msg_sec_prot_init) < 0) { return -1; } return 0; } static uint16_t msg_sec_prot_size(void) { return sizeof(msg_sec_prot_int_t); } static int8_t msg_sec_prot_init(sec_prot_t *prot) { prot->create_req = msg_sec_prot_create_request; prot->delete = msg_sec_prot_delete; prot->state_machine = msg_sec_prot_state_machine; msg_sec_prot_int_t *data = msg_sec_prot_get(prot); sec_prot_init(&data->common); sec_prot_state_set(prot, &data->common, MSG_STATE_INIT); return 0; } static void msg_sec_prot_delete(sec_prot_t *prot) { (void) prot; } static void msg_sec_prot_create_request(sec_prot_t *prot, sec_prot_keys_t *sec_keys) { (void) sec_keys; prot->state_machine(prot); } static int8_t msg_sec_prot_auth_rejected_send(sec_prot_t *prot, sec_prot_keys_t *sec_keys) { (void) sec_keys; uint8_t *eapol_pdu_frame = ns_dyn_mem_temporary_alloc(prot->header_size); // Send zero length message to relay which requests LLC to remove EAPOL temporary entry based on EUI-64 if (prot->send(prot, eapol_pdu_frame, prot->header_size) < 0) { return -1; } return 0; } static void msg_sec_prot_state_machine(sec_prot_t *prot) { msg_sec_prot_int_t *data = msg_sec_prot_get(prot); switch (sec_prot_state_get(&data->common)) { case MSG_STATE_INIT: sec_prot_state_set(prot, &data->common, MSG_STATE_CREATE_REQ); break; case MSG_STATE_CREATE_REQ: // KMP-CREATE.confirm prot->create_conf(prot, sec_prot_result_get(&data->common)); // Authentication rejected (will continue only after new EAPOL Initial-Key) (void) msg_sec_prot_auth_rejected_send(prot, prot->sec_keys); sec_prot_state_set(prot, &data->common, MSG_STATE_FINISH); break; case MSG_STATE_FINISH: sec_prot_state_set(prot, &data->common, MSG_STATE_FINISHED); /* fall through */ case MSG_STATE_FINISHED: prot->finished(prot); break; default: break; } } #endif /* HAVE_WS */
skripalschikov/connect-sdk-go
domain/payment/OrderTypeInformation.go
<filename>domain/payment/OrderTypeInformation.go // This class was auto-generated from the API references found at // https://epayments-api.developer-ingenico.com/s2sapi/v1/ package payment // OrderTypeInformation represents class OrderTypeInformation type OrderTypeInformation struct { PurchaseType *string `json:"purchaseType,omitempty"` UsageType *string `json:"usageType,omitempty"` } // NewOrderTypeInformation constructs a new OrderTypeInformation func NewOrderTypeInformation() *OrderTypeInformation { return &OrderTypeInformation{} }
Hakerh400/javascript-projects
arr-compress/index.js
<filename>arr-compress/index.js 'use strict'; const fs = require('fs'); const path = require('path'); const assert = require('assert'); const O = require('../omikron'); const debug = require('../debug'); const NumberSet = require('./number-set'); const {min, max} = Math; const compress = arr => { arr = [0, ...arr]; const arrs = new O.MultidimensionalMap(); while(1){ if(arrs.has(arr)) return arr; arrs.set(arr, 1); const len = arr.length; const pats = new O.MultidimensionalMap(); const best = [0, null]; let numMax = 0; for(let i = 1; i !== len; i++){ const num = arr[i]; if(num > numMax) numMax = num; for(let j = 0; j !== i; j++){ const slen = j + 2; const start = i - slen + 1; const pat = arr.slice(start, i + 1); if(!pats.has(pat)){ pats.set(pat, new NumberSet([start])); }else{ const indices = pats.get(pat); if(start - indices.last < slen) continue; indices.add(start); } const c = pats.get(pat).size; const dif = c * (slen - 1) - slen - 1; if(dif > best[0]){ best[0] = dif; best[1] = pat; } } } { const pat = best[1]; if(pat === null) return arr; const plen = pat.length; const indices = pats.get(pat); const arrNew = [plen - 1, ...pat]; const numNew = max(numMax, plen - 1) + 1; for(let i = 0; i !== len;){ assert(i < len); const num = arr[i]; if(!indices.has(i)){ arrNew.push(num); i++; continue; } arrNew.push(numNew); i += plen; } arr = arrNew; } } }; const decompress = arr => { while(1){ if(arr[0] === 0) return arr.slice(1); const len = arr.length; const numMax = arr.reduce((a, b) => max(a, b), 0); const plen = arr[0] + 1; const pat = arr.slice(1, plen + 1); const arrNew = []; for(let i = plen + 1; i !== len; i++){ assert(i < len); const num = arr[i]; if(num !== numMax){ arrNew.push(num); continue; } for(const num of pat) arrNew.push(num); } arr = arrNew; } }; module.exports = { compress, decompress, };
poeschko/polished
src/shorthands/border.js
<gh_stars>1000+ // @flow import capitalizeString from '../internalHelpers/_capitalizeString' import type { SideKeyword } from '../types/sideKeyword' import type { Styles } from '../types/style' const sideMap = ['top', 'right', 'bottom', 'left'] /** * Shorthand for the border property that splits out individual properties for use with tools like Fela and Styletron. A side keyword can optionally be passed to target only one side's border properties. * * @example * // Styles as object usage * const styles = { * ...border('1px', 'solid', 'red') * } * * // styled-components usage * const div = styled.div` * ${border('1px', 'solid', 'red')} * ` * * // CSS as JS Output * * div { * 'borderColor': 'red', * 'borderStyle': 'solid', * 'borderWidth': `1px`, * } * * // Styles as object usage * const styles = { * ...border('top', '1px', 'solid', 'red') * } * * // styled-components usage * const div = styled.div` * ${border('top', '1px', 'solid', 'red')} * ` * * // CSS as JS Output * * div { * 'borderTopColor': 'red', * 'borderTopStyle': 'solid', * 'borderTopWidth': `1px`, * } */ export default function border( sideKeyword: SideKeyword | string | number, ...values: Array<string | number> ): Styles { if (typeof sideKeyword === 'string' && sideMap.indexOf(sideKeyword) >= 0) { return { [`border${capitalizeString(sideKeyword)}Width`]: values[0], [`border${capitalizeString(sideKeyword)}Style`]: values[1], [`border${capitalizeString(sideKeyword)}Color`]: values[2], } } else { values.unshift(sideKeyword) return { borderWidth: values[0], borderStyle: values[1], borderColor: values[2], } } }
artemjackson/resolve
packages/adapters/storage-adapters/resolve-storage-dynamo/test/create-timestamp-expression.test.js
<reponame>artemjackson/resolve import createTimestampExpression from '../src/create-timestamp-expression' describe('method "createTimestampExpression"', () => { test('should return empty expression', () => { const { conditionExpression, attributeNames, attributeValues } = createTimestampExpression({ startTime: undefined, finishTime: undefined }) expect({ conditionExpression, attributeNames, attributeValues }).toMatchSnapshot() }) test('should return correctly expression for startTime', () => { const { conditionExpression, attributeNames, attributeValues } = createTimestampExpression({ startTime: 5, finishTime: undefined }) expect({ conditionExpression, attributeNames, attributeValues }).toMatchSnapshot() }) test('should return correctly expression for finishTime', () => { const { conditionExpression, attributeNames, attributeValues } = createTimestampExpression({ startTime: undefined, finishTime: 10 }) expect({ conditionExpression, attributeNames, attributeValues }).toMatchSnapshot() }) test('should return correctly expression for startTime and finishTime', () => { const { conditionExpression, attributeNames, attributeValues } = createTimestampExpression({ startTime: 5, finishTime: 10 }) expect({ conditionExpression, attributeNames, attributeValues }).toMatchSnapshot() }) })
JamesTheZ/BladeDISC
tao_compiler/mlir/xla/ral/context/custom_library/bitonic_sort.cu.h
// Copyright 2021 The BladeDISC 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. #ifndef DYN_SORT_BITONIC_SORT_H_ #define DYN_SORT_BITONIC_SORT_H_ template <typename Dtype> __device__ __forceinline__ void bitonicExchange( Dtype& key, const unsigned mask, const unsigned active_mask = full_mask) { const Dtype key1 = key; const unsigned tgx = threadIdx.x & 31; const unsigned otgx = tgx ^ mask; const Dtype key2 = __shfl_sync(active_mask, key, otgx); const bool flag = ((key1 > key2) ^ (tgx > otgx)) && (key1 != key2); key = flag ? key1 : key2; } template <typename Itype, typename Dtype> __device__ __forceinline__ void bitonicExchangePair( Dtype& key, Itype& val, const unsigned mask, const unsigned active_mask = full_mask) { const Dtype key1 = key; const Itype val1 = val; const unsigned tgx = threadIdx.x & 31; const unsigned otgx = tgx ^ mask; const Dtype key2 = __shfl_sync(active_mask, key, otgx); const Dtype val2 = __shfl_sync(active_mask, val, otgx); const bool flag = ((key1 > key2) ^ (tgx > otgx)) && (key1 != key2); key = flag ? key1 : key2; val = flag ? val1 : val2; } // warp bitonic sort template <typename Dtype> __device__ __inline__ void bitonicSort32( Dtype& key, const unsigned active_mask = full_mask) { bitonicExchange(key, 1, active_mask); bitonicExchange(key, 3, active_mask); bitonicExchange(key, 1, active_mask); bitonicExchange(key, 7, active_mask); bitonicExchange(key, 2, active_mask); bitonicExchange(key, 1, active_mask); bitonicExchange(key, 15, active_mask); bitonicExchange(key, 4, active_mask); bitonicExchange(key, 2, active_mask); bitonicExchange(key, 1, active_mask); bitonicExchange(key, 31, active_mask); bitonicExchange(key, 8, active_mask); bitonicExchange(key, 4, active_mask); bitonicExchange(key, 2, active_mask); bitonicExchange(key, 1, active_mask); } // warp bitonic sort template <typename Itype, typename Dtype> __device__ __inline__ void bitonicSort32( Dtype& key, Itype& val, const unsigned active_mask = full_mask) { bitonicExchangePair(key, val, 1, active_mask); bitonicExchangePair(key, val, 3, active_mask); bitonicExchangePair(key, val, 1, active_mask); bitonicExchangePair(key, val, 7, active_mask); bitonicExchangePair(key, val, 2, active_mask); bitonicExchangePair(key, val, 1, active_mask); bitonicExchangePair(key, val, 15, active_mask); bitonicExchangePair(key, val, 4, active_mask); bitonicExchangePair(key, val, 2, active_mask); bitonicExchangePair(key, val, 1, active_mask); bitonicExchangePair(key, val, 31, active_mask); bitonicExchangePair(key, val, 8, active_mask); bitonicExchangePair(key, val, 4, active_mask); bitonicExchangePair(key, val, 2, active_mask); bitonicExchangePair(key, val, 1, active_mask); } template <typename Itype, typename Dtype> __device__ __inline__ void bitonicExchange256Pair( Dtype keys[8], Itype vals[8], const unsigned mask, const unsigned active_mask = full_mask) { bitonicExchangePair(keys[0], vals[0], mask, active_mask); bitonicExchangePair(keys[1], vals[1], mask, active_mask); bitonicExchangePair(keys[2], vals[2], mask, active_mask); bitonicExchangePair(keys[3], vals[3], mask, active_mask); bitonicExchangePair(keys[4], vals[4], mask, active_mask); bitonicExchangePair(keys[5], vals[5], mask, active_mask); bitonicExchangePair(keys[6], vals[6], mask, active_mask); bitonicExchangePair(keys[7], vals[7], mask, active_mask); } template <typename Dtype> __device__ __inline__ void bitonicExchange256( Dtype keys[8], const unsigned mask, const unsigned active_mask = full_mask) { bitonicExchange(keys[0], mask, active_mask); bitonicExchange(keys[1], mask, active_mask); bitonicExchange(keys[2], mask, active_mask); bitonicExchange(keys[3], mask, active_mask); bitonicExchange(keys[4], mask, active_mask); bitonicExchange(keys[5], mask, active_mask); bitonicExchange(keys[6], mask, active_mask); bitonicExchange(keys[7], mask, active_mask); } template <typename Itype, typename Dtype> __device__ __inline__ void bitonicSort32_256_pair( Dtype keys[8], Itype vals[8], const unsigned active_mask = full_mask) { bitonicExchange256Pair(keys, vals, 1, active_mask); bitonicExchange256Pair(keys, vals, 3, active_mask); bitonicExchange256Pair(keys, vals, 1, active_mask); bitonicExchange256Pair(keys, vals, 7, active_mask); bitonicExchange256Pair(keys, vals, 2, active_mask); bitonicExchange256Pair(keys, vals, 1, active_mask); bitonicExchange256Pair(keys, vals, 15, active_mask); bitonicExchange256Pair(keys, vals, 4, active_mask); bitonicExchange256Pair(keys, vals, 2, active_mask); bitonicExchange256Pair(keys, vals, 1, active_mask); bitonicExchange256Pair(keys, vals, 31, active_mask); bitonicExchange256Pair(keys, vals, 8, active_mask); bitonicExchange256Pair(keys, vals, 4, active_mask); bitonicExchange256Pair(keys, vals, 2, active_mask); bitonicExchange256Pair(keys, vals, 1, active_mask); } template <typename Dtype> __device__ __inline__ void bitonicSort32_256( Dtype keys[8], const unsigned active_mask = full_mask) { bitonicExchange256(keys, 1, active_mask); bitonicExchange256(keys, 3, active_mask); bitonicExchange256(keys, 1, active_mask); bitonicExchange256(keys, 7, active_mask); bitonicExchange256(keys, 2, active_mask); bitonicExchange256(keys, 1, active_mask); bitonicExchange256(keys, 15, active_mask); bitonicExchange256(keys, 4, active_mask); bitonicExchange256(keys, 2, active_mask); bitonicExchange256(keys, 1, active_mask); bitonicExchange256(keys, 31, active_mask); bitonicExchange256(keys, 8, active_mask); bitonicExchange256(keys, 4, active_mask); bitonicExchange256(keys, 2, active_mask); bitonicExchange256(keys, 1, active_mask); } template <typename Itype, typename Dtype> __device__ __forceinline__ void bitonicMergePair( Dtype& k0, Itype& v0, Dtype& k1, Itype& v1, const unsigned active_mask = full_mask) { const unsigned tgx = threadIdx.x & 31; const unsigned otgx = 31 - tgx; Dtype key1 = k0; Dtype val1 = v0; const Dtype key2 = __shfl_sync(active_mask, k1, otgx); const Dtype val2 = __shfl_sync(active_mask, v1, otgx); const bool flag = key1 > key2; k0 = flag ? key1 : key2; v0 = flag ? val1 : val2; key1 = flag ? key2 : key1; val1 = flag ? val2 : val1; k1 = __shfl_sync(active_mask, key1, otgx); v1 = __shfl_sync(active_mask, val1, otgx); } template <typename Dtype> __device__ __forceinline__ void bitonicMerge( Dtype& k0, Dtype& k1, const unsigned active_mask = full_mask) { const unsigned tgx = threadIdx.x & 31; const unsigned otgx = 31 - tgx; Dtype key1 = k0; const Dtype key2 = __shfl_sync(active_mask, k1, otgx); const bool flag = key1 > key2; k0 = flag ? key1 : key2; key1 = flag ? key2 : key1; k1 = __shfl_sync(active_mask, key1, otgx); } template <typename Itype, typename Dtype> __device__ __inline__ void bitonicMerge64_256_pair( Dtype keys[8], Itype vals[8], const unsigned active_mask = full_mask) { bitonicMergePair(keys[0], vals[0], keys[1], vals[1], active_mask); bitonicMergePair(keys[2], vals[2], keys[3], vals[3], active_mask); bitonicMergePair(keys[4], vals[4], keys[5], vals[5], active_mask); bitonicMergePair(keys[6], vals[6], keys[7], vals[7], active_mask); } template <typename Dtype> __device__ __inline__ void bitonicMerge64_256( Dtype keys[8], const unsigned active_mask = full_mask) { bitonicMerge(keys[0], keys[1], active_mask); bitonicMerge(keys[2], keys[3], active_mask); bitonicMerge(keys[4], keys[5], active_mask); bitonicMerge(keys[6], keys[7], active_mask); } template <typename Itype, typename Dtype> __device__ __inline__ void bitonicSort64_256_pair( Dtype keys[8], Itype vals[8], const unsigned active_mask = full_mask) { bitonicSort32_256_pair(keys, vals, active_mask); bitonicMerge64_256_pair(keys, vals, active_mask); bitonicExchange256Pair(keys, vals, 16, active_mask); bitonicExchange256Pair(keys, vals, 8, active_mask); bitonicExchange256Pair(keys, vals, 4, active_mask); bitonicExchange256Pair(keys, vals, 2, active_mask); bitonicExchange256Pair(keys, vals, 1, active_mask); } template <typename Dtype> __device__ __inline__ void bitonicSort64_256( Dtype keys[8], const unsigned active_mask = full_mask) { bitonicSort32_256(keys, active_mask); bitonicMerge64_256(keys, active_mask); bitonicExchange256(keys, 16, active_mask); bitonicExchange256(keys, 8, active_mask); bitonicExchange256(keys, 4, active_mask); bitonicExchange256(keys, 2, active_mask); bitonicExchange256(keys, 1, active_mask); } template <typename Itype, typename Dtype> __device__ __inline__ void bitonicMerge128_256_pair( Dtype keys[8], Itype vals[8], const unsigned active_mask = full_mask) { bitonicMergePair(keys[0], vals[0], keys[3], vals[3], active_mask); bitonicMergePair(keys[1], vals[1], keys[2], vals[2], active_mask); bitonicMergePair(keys[4], vals[4], keys[7], vals[7], active_mask); bitonicMergePair(keys[5], vals[5], keys[6], vals[6], active_mask); } template <typename Dtype> __device__ __inline__ void bitonicMerge128_256( Dtype keys[8], const unsigned active_mask = full_mask) { bitonicMerge(keys[0], keys[3], active_mask); bitonicMerge(keys[1], keys[2], active_mask); bitonicMerge(keys[4], keys[7], active_mask); bitonicMerge(keys[5], keys[6], active_mask); } template <typename Itype, typename Dtype> __device__ __inline__ void bitonicMerge256_256_pair( Dtype keys[8], Itype vals[8], const unsigned active_mask = full_mask) { bitonicMergePair(keys[0], vals[0], keys[7], vals[7], active_mask); bitonicMergePair(keys[1], vals[1], keys[6], vals[6], active_mask); bitonicMergePair(keys[2], vals[2], keys[5], vals[5], active_mask); bitonicMergePair(keys[3], vals[3], keys[4], vals[4], active_mask); } template <typename Dtype> __device__ __inline__ void bitonicMerge256_256( Dtype keys[8], const unsigned active_mask = full_mask) { bitonicMerge(keys[0], keys[7], active_mask); bitonicMerge(keys[1], keys[6], active_mask); bitonicMerge(keys[2], keys[5], active_mask); bitonicMerge(keys[3], keys[4], active_mask); } template <typename T> __device__ __inline__ static void swap(T& a, T& b) { T c(a); a = b; b = c; } template <typename Itype, typename Dtype> __device__ __forceinline__ void condExchange(Dtype& k0, Itype& v0, Dtype& k1, Itype& v1) { if (k0 < k1) { swap(k0, k1); swap(v0, v1); } } template <typename Dtype> __device__ __forceinline__ void condExchange(Dtype& k0, Dtype& k1) { if (k0 < k1) { swap(k0, k1); } } template <typename Itype, typename Dtype> __device__ __inline__ void bitonicExchange32_256_pair(Dtype keys[8], Itype vals[8]) { condExchange(keys[0], vals[0], keys[1], vals[1]); condExchange(keys[2], vals[2], keys[3], vals[3]); condExchange(keys[4], vals[4], keys[5], vals[5]); condExchange(keys[6], vals[6], keys[7], vals[7]); } template <typename Dtype> __device__ __inline__ void bitonicExchange32_256(Dtype keys[8]) { condExchange(keys[0], keys[1]); condExchange(keys[2], keys[3]); condExchange(keys[4], keys[5]); condExchange(keys[6], keys[7]); } template <typename Itype, typename Dtype> __device__ __inline__ void bitonicExchange64_256_pair(Dtype keys[8], Itype vals[8]) { condExchange(keys[0], vals[0], keys[2], vals[2]); condExchange(keys[1], vals[1], keys[3], vals[3]); condExchange(keys[4], vals[4], keys[6], vals[6]); condExchange(keys[5], vals[5], keys[7], vals[7]); } template <typename Dtype> __device__ __inline__ void bitonicExchange64_256(Dtype keys[8]) { condExchange(keys[0], keys[2]); condExchange(keys[1], keys[3]); condExchange(keys[4], keys[6]); condExchange(keys[5], keys[7]); } template <typename Itype, typename Dtype> __device__ __inline__ void bitonicSort128_256_pair( Dtype keys[8], Itype vals[8], const unsigned active_mask = full_mask) { bitonicSort64_256_pair(keys, vals, active_mask); bitonicMerge128_256_pair(keys, vals, active_mask); bitonicExchange32_256_pair(keys, vals); bitonicExchange256Pair(keys, vals, 16, active_mask); bitonicExchange256Pair(keys, vals, 8, active_mask); bitonicExchange256Pair(keys, vals, 4, active_mask); bitonicExchange256Pair(keys, vals, 2, active_mask); bitonicExchange256Pair(keys, vals, 1, active_mask); } template <typename Dtype> __device__ __inline__ void bitonicSort128_256( Dtype keys[8], const unsigned active_mask = full_mask) { bitonicSort64_256(keys, active_mask); bitonicMerge128_256(keys, active_mask); bitonicExchange32_256(keys); bitonicExchange256(keys, 16, active_mask); bitonicExchange256(keys, 8, active_mask); bitonicExchange256(keys, 4, active_mask); bitonicExchange256(keys, 2, active_mask); bitonicExchange256(keys, 1, active_mask); } template <typename Itype, typename Dtype> __device__ __inline__ void bitonicSort256_256( Dtype keys[8], Itype vals[8], const unsigned active_mask = full_mask) { bitonicSort128_256_pair(keys, vals, active_mask); bitonicMerge256_256_pair(keys, vals, active_mask); bitonicExchange64_256_pair(keys, vals); bitonicExchange32_256_pair(keys, vals); bitonicExchange256Pair(keys, vals, 16, active_mask); bitonicExchange256Pair(keys, vals, 8, active_mask); bitonicExchange256Pair(keys, vals, 4, active_mask); bitonicExchange256Pair(keys, vals, 2, active_mask); bitonicExchange256Pair(keys, vals, 1, active_mask); } template <typename Dtype> __device__ __inline__ void bitonicSort256_256( Dtype keys[8], const unsigned active_mask = full_mask) { bitonicSort128_256(keys, active_mask); bitonicMerge256_256(keys, active_mask); bitonicExchange64_256(keys); bitonicExchange32_256(keys); bitonicExchange256(keys, 16, active_mask); bitonicExchange256(keys, 8, active_mask); bitonicExchange256(keys, 4, active_mask); bitonicExchange256(keys, 2, active_mask); bitonicExchange256(keys, 1, active_mask); } #endif // DYN_SORT_BITONIC_SORT_H_
Abq-Tool-Shed/Capstone-Abq-Tool-Shed
frontend/src/store/categories.js
import {createSlice} from "@reduxjs/toolkit"; import {httpConfig} from "../utils/http-config"; const slice = createSlice({ name: "categories", initialState: [], reducers: { setAllCategories: (categories, action) => { return action.payload } } }) export const {setAllCategories} = slice.actions export const fetchAllCategories = () => async dispatch => { const {data} = await httpConfig("/apis/category/"); dispatch(setAllCategories(data)) } export default slice.reducer
jbrekelmans/k8s-docker-compose
internal/app/config/config.go
package config import ( "fmt" log "github.com/Sirupsen/logrus" "github.com/kube-compose/kube-compose/internal/pkg/util" dockerComposeConfig "github.com/kube-compose/kube-compose/pkg/docker/compose/config" "github.com/pkg/errors" "github.com/uber-go/mapdecode" "k8s.io/apimachinery/pkg/util/validation" "k8s.io/client-go/rest" ) type DockerRegistryClusterImageStorage struct { Host string } type Service struct { DockerComposeService *dockerComposeConfig.Service matchesFilter bool matchesFilterDirectly bool NameEscaped string Ports []Port } func (s *Service) Name() string { return s.DockerComposeService.Name } type ClusterImageStorage struct { Docker *struct{} DockerRegistry *DockerRegistryClusterImageStorage } type Config struct { // All Kubernetes resources are named with "-"+EnvironmentID as a suffix, // and have an additional label "env="+EnvironmentID so that namespaces can be shared. EnvironmentID string EnvironmentLabel string KubeConfig *rest.Config Namespace string ClusterImageStorage ClusterImageStorage VolumeInitBaseImage *string Services map[string]*Service } type Port struct { Port int32 // one of "udp", "tcp" and "sctp" Protocol string } func New(files []string) (*Config, error) { cfg := &Config{ EnvironmentLabel: "env", } dcCfg, err := dockerComposeConfig.New(files) if err != nil { return nil, err } cfg.Services = map[string]*Service{} for name, dcService := range dcCfg.Services { if e := validation.IsDNS1123Subdomain(name); len(e) > 0 { return nil, fmt.Errorf("sorry, we do not support the potentially valid docker compose service named %s: %s", name, e[0]) } service := &Service{ DockerComposeService: dcService, NameEscaped: util.EscapeName(name), } for _, portBinding := range dcService.Ports { service.Ports = append(service.Ports, Port{ Protocol: portBinding.Protocol, Port: portBinding.Internal, }) } cfg.Services[name] = service } err = loadXKubeCompose(cfg, dcCfg.XProperties) if err != nil { return nil, err } return cfg, nil } type clusterImageStorage struct { Type string `mapdecode:"type"` Host *string `mapdecode:"host"` } type xKubeCompose struct { XKubeCompose struct { ClusterImageStorage *clusterImageStorage `mapdecode:"cluster_image_storage"` PushImages *struct { DockerRegistry string `mapdecode:"docker_registry"` } `mapdecode:"push_images"` VolumeInitBaseImage *string `mapdecode:"volume_init_base_image"` } `mapdecode:"x-kube-compose"` } func loadXKubeCompose(cfg *Config, xPropertiesSlice []dockerComposeConfig.XProperties) error { for i := len(xPropertiesSlice) - 1; i >= 0; i-- { var x xKubeCompose err := mapdecode.Decode(&x, xPropertiesSlice[i], mapdecode.IgnoreUnused(true)) if err != nil { return errors.Wrap(err, "error while parsing \"x-kube-compose\" of a docker compose file") } if x.XKubeCompose.ClusterImageStorage != nil { if x.XKubeCompose.PushImages != nil { return fmt.Errorf("a docker compose file cannot set both \"x-kube-compose\".\"push_images\" and \"x-kube-compose\"." + "\"cluster_image_storage\"") } err = loadClusterImageStorage(cfg, x.XKubeCompose.ClusterImageStorage) if err != nil { return err } } else if x.XKubeCompose.PushImages != nil { log.Warn("a docker compose file has set \"x-kube-compose\".\"push_images\", but this functionality is deprecated. " + "See https://github.com/kube-compose/kube-compose.") cfg.ClusterImageStorage.Docker = nil cfg.ClusterImageStorage.DockerRegistry = &DockerRegistryClusterImageStorage{ Host: x.XKubeCompose.PushImages.DockerRegistry, } } cfg.VolumeInitBaseImage = x.XKubeCompose.VolumeInitBaseImage } return nil } func loadClusterImageStorage(cfg *Config, v *clusterImageStorage) error { cfg.ClusterImageStorage.Docker = nil cfg.ClusterImageStorage.DockerRegistry = nil switch v.Type { case "docker": cfg.ClusterImageStorage.Docker = &struct{}{} case "docker_registry": if v.Host == nil { return fmt.Errorf("a docker compose file is missing a required value at \"x-kube-compose\".\"cluster_image_storage\"." + "\"host\"") } cfg.ClusterImageStorage.DockerRegistry = &DockerRegistryClusterImageStorage{ Host: *v.Host, } default: return fmt.Errorf("a docker compose file has an invalid value at \"x-kube-compose\".\"cluster_image_storage\".\"type\": " + "value must be one of \"docker\" and \"docker_registry\"") } return nil } // AddService adds a service to this configuration. func (cfg *Config) AddService(dockerComposeService *dockerComposeConfig.Service) *Service { service := cfg.Services[dockerComposeService.Name] if service != nil { panic("a docker compose service with that name is already registered") } else { if dockerComposeService.DependsOn != nil { panic("cannot add dockerComposeService that has dependencies") } service = &Service{ DockerComposeService: dockerComposeService, NameEscaped: util.EscapeName(dockerComposeService.Name), } if cfg.Services == nil { cfg.Services = map[string]*Service{} } cfg.Services[dockerComposeService.Name] = service } return service } // MatchesFilter determines whether a service matches the current filter (indirectly or directly). func (cfg *Config) MatchesFilter(service *Service) bool { return service.matchesFilter } // MatchesFilterDirectly determines whether a service matches the current filter directly (e.g. service was passed to AddToFilter). func (cfg *Config) MatchesFilterDirectly(service *Service) bool { return service.matchesFilterDirectly } // ClearFilter sets the current filter to match no service. func (cfg *Config) ClearFilter() { for _, service := range cfg.Services { service.matchesFilter = false service.matchesFilterDirectly = false } } // AddToFilter adds service and its (in)direct dependencies (based on depends_on) to the set of services matched by // the current filter. After a AddToFilter(service), MatchesFilterDirectly(service) will return true unless ClearFilter was called. func (cfg *Config) AddToFilter(service *Service) { queue := []*Service{ service, } service.matchesFilterDirectly = true n := 1 for n > 0 { n-- service1 := queue[n] if !service1.matchesFilter { service1.matchesFilter = true for d := range service1.DockerComposeService.DependsOn { service2 := cfg.Services[d] if n < len(queue) { queue[n] = service2 } else { queue = append(queue, service2) } n++ } } } }
silvrwolfboy/octofacts
spec/octofacts_updater/service/puppetdb_spec.rb
require "spec_helper" require "octocatalog-diff" describe OctofactsUpdater::Service::PuppetDB do before(:each) do ENV.delete("PUPPETDB_URL") end after(:each) do ENV.delete("PUPPETDB_URL") end describe "#facts" do it "should return facts from octocatalog-diff" do facts_double = instance_double(OctocatalogDiff::Facts) facts_answer = { "foo" => "bar" } expected_args = {node: "foo.bar.node", backend: :puppetdb, puppetdb_url: "https://puppetdb.fake:8443"} expect(described_class).to receive(:puppetdb_url).and_return("https://puppetdb.fake:8443") expect(OctocatalogDiff::Facts).to receive(:new).with(expected_args).and_return(facts_double) expect(facts_double).to receive(:facts).and_return(facts_answer) expect(described_class.facts("foo.bar.node", {})).to eq(facts_answer) end it "should raise an error if facts cannot be determined" do facts_double = instance_double(OctocatalogDiff::Facts) expected_args = {node: "foo.bar.node", backend: :puppetdb, puppetdb_url: "https://puppetdb.fake:8443"} expect(described_class).to receive(:puppetdb_url).and_return("https://puppetdb.fake:8443") expect(OctocatalogDiff::Facts).to receive(:new).with(expected_args).and_return(facts_double) expect(facts_double).to receive(:facts).and_return(nil) expect { described_class.facts("foo.bar.node", {}) }.to raise_error(OctocatalogDiff::Errors::FactSourceError) end end describe "#puppetdb_url" do let(:fake_url) { "https://puppetdb.fake:8443" } it "should return puppetdb_url from configuration" do expect(described_class.puppetdb_url("puppetdb" => { "url" => fake_url })).to eq(fake_url) end it "should return PUPPETDB_URL from environment" do ENV["PUPPETDB_URL"] = fake_url expect(described_class.puppetdb_url).to eq(fake_url) end it "should raise an error if puppetdb URL cannot be determined" do expect { described_class.puppetdb_url }.to raise_error(/PuppetDB URL not configured or set in environment/) end end end
VAIBHAV7500/lets_binge
src/routes/index.js
const routes = [ { path: ["/", "/home"], exact: true, component: "Home", },{ path: ["/room"], exact: false, component: "Room", },{ path: ["/terms-and-conditions"], exact: true, component: "TnC", },{ path: ["/privacy-policy"], exact: true, component: "PrivacyPolicy", },{ path: ["/your-rooms"], exact: true, component: "YourRooms", } ] export default routes;
bjaanes/starport
ignite/pkg/cosmosanalysis/module/testdata/planet/x/planet/types/types.go
package types type QueryMyQueryRequest struct{} type QueryMyQueryResponse struct{}
Rajpratik71/pouch
registry/config.go
<reponame>Rajpratik71/pouch package registry var ( defaultV2Registry = "registry-1.docker.io" )
xiaohaijin/RHIC-STAR
StRoot/Stl3Util/gl3/gl3Algorithm.h
//:>------------------------------------------------------------------ //: FILE: gl3Algorithm.h //: HISTORY: //: 1feb2000 version 1.00 //: 31jul2000 add methods initRun, endRun, end //:<------------------------------------------------------------------ // // tom: This class implements the "housekeeping"-issues common to // all Algorithms: counters, pre-/postscaling, parameter handling, // generation of L3 summary data. // // Any implementation of an L3 algorithm must inherit from this class. // //------------------------------------------------------------------ #ifndef GL3ALGORITHM #define GL3ALGORITHM #include "Stl3Util/gl3/gl3Event.h" #include "Stl3Util/gl3/gl3Histo.h" //#include "foreign/daqFormats.h" #include "Stl3Util/foreign/L3/L3Algorithms.h" #include <stdio.h> #include <math.h> class gl3Algorithm { public: gl3Algorithm(); virtual ~gl3Algorithm(); virtual int init(); virtual int end(); int process (gl3Event* event_in); void incrementCounters(); virtual int setParameters(int, int, int, int, int, float, float, float, float, float); void setScaling(int preScale, int postScale); void fillSummary(struct algorithm_data *dest); virtual const int getAlgorithmID() = 0; virtual const char *getAlgorithmName() = 0; protected: virtual int decide () = 0; int priority; // 1 = soft trigger (EVB can drop the event to save bandwidth) // 2 = hard trigger (EVB will write in any case) // Pointer to L3_P containing the event data gl3Event * event; // Parameters from run control int GI1, GI2, GI3, GI4, GI5; float GF1, GF2, GF3, GF4, GF5; // Algorithm summary data to be stored in algorithm_data // Filled by decide() float SummaryData[10]; public: void showConfiguration(); private: void resetCounters(); typedef int counter_type; counter_type preScale_cnt; counter_type call_cnt; counter_type accept_cnt; counter_type build_cnt; int preScale; int postScale; char on, accept, build; }; gl3Algorithm *gl3InstantiateAlgorithm(int algID); #endif
nishio/atcoder
abc197/e.py
# included from snippets/main.py def debug(*x, msg=""): import sys print(msg, *x, file=sys.stderr) def solve(SOLVE_PARAMS): pass def main(): N = int(input()) INF = 9223372036854775807 MAX = [-INF] * (N + 1) MIN = [INF] * (N + 1) for i in range(N): X, C = map(int, input().split()) MAX[C] = max(MAX[C], X) MIN[C] = min(MIN[C], X) lx = 0 rx = 0 lt = 0 rt = 0 for c in range(N + 1): if MIN[c] == INF: continue l = MIN[c] r = MAX[c] lt2 = min(lt + abs(r - lx), rt + abs(r - rx)) + (r - l) rt2 = min(lt + abs(l - lx), rt + abs(l - rx)) + (r - l) lx, rx, lt, rt = l, r, lt2, rt2 # debug(lx, rx, lt, rt, msg=":") print(min(lt + abs(lx), rt + abs(rx))) # tests T1 = """ 5 2 2 3 1 1 3 4 2 5 3 """ TEST_T1 = """ >>> as_input(T1) >>> main() 12 """ T2 = """ 9 5 5 -4 4 4 3 6 3 -5 5 -3 2 2 2 3 3 1 4 """ TEST_T2 = """ >>> as_input(T2) >>> main() 38 """ def _test(): import doctest doctest.testmod() g = globals() for k in sorted(g): if k.startswith("TEST_"): print(k) doctest.run_docstring_examples(g[k], g, name=k) def as_input(s): "use in test, use given string as input file" import io f = io.StringIO(s.strip()) g = globals() g["input"] = lambda: bytes(f.readline(), "ascii") g["read"] = lambda: bytes(f.read(), "ascii") if __name__ == "__main__": import sys input = sys.stdin.buffer.readline read = sys.stdin.buffer.read sys.setrecursionlimit(10 ** 6) if sys.argv[-1] == "-t": print("testing") _test() sys.exit() main() sys.exit() # end of snippets/main.py
highfestiva/life
tools/util/update_codestd.py
#!/usr/bin/env python3 import codecs from collections import defaultdict from io import BytesIO import re import os import sys from tokenize import tokenize, NAME, NUMBER, OP, COMMENT, STRING, TokenError _lookup = {} _fnames = {'ThirdParty': 'thirdparty'} _flookup = defaultdict(set) def _tok(i, tokens): if i >= 0 and i < len(tokens): return tokens[i][:2] return '','' def read(filename): try: return open(filename).read() except UnicodeDecodeError: return codecs.open(filename, encoding='latin-1').read() except: return None def is_cpp_file(filename): return os.path.isfile(filename) and any(filename.endswith(e) for e in ['.cpp', '.cxx', '.mm', '.c', '.m', '.h', '.hpp', '.inl']) def is_proj_file(filename): return os.path.isfile(filename) and any(filename.endswith(e) for e in ['.project', '.vcxproj', '.vcxproj.filters', '.pbxproj', '.sln', '.workspace', '.plist', '.rc']) def parse_token(fname, i, tokens): global _flookup typ,name = _tok(i, tokens) if name: _flookup[fname].add(name) if len(name) <= 1: return if i==1 and typ == STRING and tokens[0][1] == '#include': _lookup[name] = 'loc_inc' return if typ not in (NAME,): return typ0,name0 = _tok(i-1, tokens) isclass = name0 in ('class','struct') if typ == NAME and name in _lookup: if isclass: _lookup[name] = 'class' return typ1,name1 = _tok(i+1, tokens) if name0 == '#define' and name == name.upper(): if name1.isdigit() or name1.startswith('"'): _lookup[name] = 'const' elif '(' not in name: _lookup[name] = 'macro' return istype = (tokens[0][1] == 'typedef') iscamel = (name != name.lower() and name != name.upper()) isvar = (name1 and name1 in ';=[' and not isclass and not istype) if name1 in ';,.-><::?()[+=-=*=/=%=&=|=~=^=': if name0 == 'namespace' and iscamel: _lookup[name] = 'namespace' elif (isclass or istype) and iscamel: _lookup[name] = 'class' elif isvar and name[0] == 'g' and iscamel and 'const' in [t[1] for t in tokens[max(0,i-4):i]]: _lookup[name] = 'const' elif isvar and name[0] in 'ms' and iscamel: _lookup[name] = 'm_var' elif isvar and name[0] == 'g' and (name[1] == '_' or name[1].isupper()): _lookup[name] = 'g_var' elif i == 0 and name == name.upper() and name1 == '=': _lookup[name] = 'const' elif (i==0 or 'enum' in [t[1] for t in tokens]) and name == name.upper() and name.split('_',1)[0] not in ('PNG','GL','GLX') and name1 in ('',',','}'): _lookup[name] = 'const' # enum elif isvar and name[0] in 'lps' and iscamel: _lookup[name] = 's_var' elif name1 and name1 in '),' and name[0] in 'lp' and iscamel: _lookup[name] = 's_var' elif name1 == '(': # Constructor call or function call. Hard to distinguish. if name[0] in 'mlp' and iscamel: if name[0] in 'lp': _lookup[name] = 's_var' else: # This is probably a constructor initializer. Type will be found in definition. return elif typ0 == NAME or '=' in name0 or ':' in name0: if name[0].isupper(): _lookup[name] = 'func' elif _tok(len(tokens)-1, tokens)[1] == ';': # This is either a prototype or a stack object calling it's constructor. # We can't tell without knowing if we're inside a function or not. pass def get_token(i, tokens): typ,name = _tok(i, tokens) if name in _lookup: return _lookup[name],name return typ,name def filename_convert(line): words = [word for word in re.split(r'[^a-zA-Z0-9\._]', line) if word] for word in sorted(words, key=lambda w:-len(w)): if word in _fnames: line = line.replace(word, _fnames[word]) return line def namespacename(name): return name.lower() def classname(name): return name def funcname(name): return name def varname(filename, name): # Remove hungarian notation. n = name.lstrip('abcdefghijklmnopqrstuvwxyz_') if len(n)+5 < len(name): return name # Uh-oh. Not even I could stand this many hungarian letters. if not n or n[:1].isdigit(): return name # Convert CPUThread to CpuThread. n = re.sub('([A-Z])([A-Z]+)([A-Z]|$)', lambda m: m.group(1)+m.group(2).lower()+m.group(3), n) # Convert CamelCase to cpp_case. n = ''.join('_'+c.lower() if c.isupper() else c for c in n).lstrip('_') xlat = {'string':'s', 'double':'d', 'int':'i', 'float':'f', 'char':'c', 'str':'s', 'wstr':'ws', 'true':'if_true', 'false':'if_false', 'this':'value', 'class':'clazz', 'default':'_default', 'continue':'do_continue', 'const':'constant'} n = xlat[n] if n in xlat else n hasplain = n in _flookup[filename] if name[0] == 'l' and (('p'+name[1:]) in _flookup[filename] or hasplain): n = '__'+n if hasplain else '_'+n elif name[0] == 'p' and hasplain: n = '_'+n elif name[:2] in ('ms','sm') and ('m'+name[2:]) in _flookup[filename]: n = n+'_' return n def constname(name): if '_' in name: name = name.replace('_', ' ').title().replace(' ', '') if name == name.upper(): name = name.title() return 'k' + name.lstrip('abcdefghijklmnopqrstuvwxyz_') def incname(name): return filename_convert(name) def balance(s, a, b): t = s if '"' in s: splits = re.split(r'(?<!\\)"', s)[::2] if len(splits)%2 == 0: t = ' '.join(splits) ca,cb = t.count(a),t.count(b) while ca < cb: s = a+s ca += 1 while ca > cb: s += b cb += 1 return s def treplace(s, src, dst): src = r'([^A-Za-z0-9_]+|^)%s([^A-Za-z0-9_]+|$)' % src dst = r'\1%s\2' % dst return re.sub(src, dst, s) def update_cpp(fname, src, output): newlines = [] inblock = False for line in src.split('\n'): line = line.rstrip() l = line.lstrip() if l == '{': prevline,eolcomment = newlines[-1].lstrip(), '' if '//' in prevline: code = prevline.split('//')[0].rstrip() prevline,eolcomment = code,prevline[len(code):] if prevline and not prevline.startswith('#') and (prevline[-1] in '):' or prevline[-1].isalnum()): s = newlines[-1] newlines[-1] = s[:s.index(prevline)+len(prevline)] + ' {' + eolcomment continue preproc = '#' if l[:1] == '#' else '' l = l.replace('#', ' ').lstrip() try: tokens = list(tokenize(BytesIO(l.encode()).readline))[1:] except TokenError as e: l = l.split('//')[0] l = balance(l, '(', ')') l = balance(l, '{', '}') l = balance(l, '[', ']') l = balance(l, "'", "'") try: tokens = list(tokenize(BytesIO(l.encode()).readline))[1:] except TokenError as e: print(e, l) continue tokens[0] = (tokens[0][0], preproc+tokens[0][1], 0, 0, 0) token_len_idx = [i for i,t in sorted(enumerate(tokens), key=lambda it:-len(it[1][1]))] for i in range(len(tokens)): if not output: if _tok(i, tokens) == (OP,'//'): break if not inblock and _tok(i, tokens) == (OP,'/') and _tok(i+1, tokens) == (OP,'*'): inblock = True if inblock: if _tok(i, tokens) == (OP,'*') and _tok(i+1, tokens) == (OP,'/'): inblock = False continue parse_token(fname, i, tokens) else: tli = token_len_idx[i] typ,name = get_token(tli, tokens) #print(' ---', typ, name) if typ == 'namespace': line = treplace(line, name, namespacename(name)) elif typ == 'class': line = treplace(line, name, classname(name)) elif typ == 'func': line = treplace(line, name, funcname(name)) elif typ == 'm_var': line = treplace(line, name, varname(fname, name)+'_') elif typ == 's_var': line = treplace(line, name, varname(fname, name)) elif typ == 'const': line = treplace(line, name, constname(name)) elif typ == 'g_var': line = treplace(line, name, 'g_'+varname(fname, name)) elif typ == 'loc_inc': line = treplace(line, name, incname(name)) elif tli == 0 and (name in ('else','catch', 'break') or (name == 'while' and line.endswith(';'))): # Continue else, catch, do...while statements on line with end brace. if newlines[-1].endswith('}'): line = newlines.pop() + ' ' + line.lstrip() newlines.append(line) return '\n'.join(newlines) def update_proj(src): newlines = [] for line in src.split('\n'): line = filename_convert(line) newlines.append(line) return '\n'.join(newlines) def cpp_convert(filenames): # Traverse all files to pick up all unique symbols. print('Parsing C++ source...') for filename in filenames: if not is_cpp_file(filename): continue print('%s... ' % filename, flush=True, end='') src = read(filename) if not src: print('ignored.') continue update_cpp(filename, src, False) print('parsed.') # Update source code. print('Updating C++ source and projects...') for filename in filenames: print('%s... ' % filename, flush=True, end='') src = read(filename) if not src: print('ignored (unable to read).') continue if is_proj_file(filename): newsrc = update_proj(src) else: newsrc = update_cpp(filename, src, True) if newsrc != src: open(filename, 'w').write(newsrc) print('updated.') #print(newsrc) else: print('unchanged.') def cpp_convert_dir_entries(root, entries, level=0): global _fnames es = [] for e in entries: exempt = any(a==e for a in ['.xcodeproj','Contents','Resources','Debug','Release','Profile']) n = e if exempt else e.lower() n = n if n != 'source' else 'src' e,n = [os.path.join(root,x) for x in (e,n)] es += [n] if n != e: os.rename(e, n) ebase, nbase = e.rstrip('/').rsplit('/',1)[-1], n.rstrip('/').rsplit('/',1)[-1] assert ebase not in _fnames or _fnames[ebase] == nbase _fnames[ebase] = nbase print('%s -> %s' % (e, n)) files = [f for f in es if is_cpp_file(f) or is_proj_file(f)] dirs = [d for d in es if os.path.isdir(d)] for d in dirs: files += cpp_convert_dir_entries(d, os.listdir(d), level+1) if level == 0: cpp_convert(files) return files assert varname('?', 'lCPUThreadFTW') == 'cpu_thread_ftw' _flookup['?'].add('pCPUThreadFTW') assert varname('?', 'lCPUThreadFTW') == '_cpu_thread_ftw' _flookup['?'].add('cpu_thread_ftw') assert varname('?', 'lCPUThreadFTW') == '__cpu_thread_ftw' assert namespacename('UiLepra') == 'uilepra' s = 'namespace Apa;\nApa::Bepa::Cepa(Thing pThing);' update_cpp('?', s, False) assert update_cpp('?', s, True) == 'namespace apa;\napa::Bepa::Cepa(Thing thing);' cpp_convert_dir_entries('', sys.argv[1:]) for name,typ in sorted(_lookup.items(), key=lambda nt:nt[1]+nt[0]): print(typ, name)
npwebste/UPS_Controller
lib/scipoptsuite-5.0.1/soplex/src/spxratiotester.h
<filename>lib/scipoptsuite-5.0.1/soplex/src/spxratiotester.h /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the class library */ /* SoPlex --- the Sequential object-oriented simPlex. */ /* */ /* Copyright (C) 1996-2018 Konrad-Zuse-Zentrum */ /* fuer Informationstechnik Berlin */ /* */ /* SoPlex is distributed under the terms of the ZIB Academic Licence. */ /* */ /* You should have received a copy of the ZIB Academic License */ /* along with SoPlex; see the file COPYING. If not email to <EMAIL>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file spxratiotester.h * @brief Abstract ratio test base class. */ #ifndef _SPXRATIOTESTER_H_ #define _SPXRATIOTESTER_H_ #include <assert.h> #include "spxdefines.h" #include "spxsolver.h" namespace soplex { /**@brief Abstract ratio test base class. @ingroup Algo Class SPxRatioTester is the virtual base class for computing the ratio test within the Simplex algorithm driven by SoPlex. After a SoPlex solver has been #load()%ed to an SPxRatioTester, the solver calls #selectLeave() for computing the ratio test for the entering simplex and #selectEnter() for computing the ratio test in leaving simplex. */ class SPxRatioTester { protected: //------------------------------------- /**@name Data */ //@{ /// the solver SPxSolver* thesolver; /// name of the ratio tester const char* m_name; /// internal storage of type SPxSolver::Type m_type; /// allowed bound violation Real delta; //@} public: //------------------------------------- /**@name Access / modification */ //@{ /// get name of ratio tester. virtual const char* getName() const { return m_name; } /// loads LP. /** Load the solver and LP for which pricing steps are to be performed. */ virtual void load(SPxSolver* p_solver) { thesolver = p_solver; } /// unloads LP. virtual void clear() { thesolver = 0; } /// returns loaded LP solver. virtual SPxSolver* solver() const { return thesolver; } /// set allowed bound violation virtual void setDelta( Real newDelta ) { if( newDelta <= DEFAULT_EPS_ZERO ) delta = DEFAULT_EPS_ZERO; else delta = newDelta; } /// get allowed bound violation virtual Real getDelta() { return delta; } //@} //------------------------------------- /**@name Entering / leaving */ //@{ /// selects index to leave the basis. /** Method #selectLeave() is called by the loaded SoPlex solver when computing the entering simplex algorithm. Its task is to select and return the index of the basis variable that is to leave the basis. When being called, \ref SPxSolver::fVec() "fVec()" fullfills the basic bounds \ref SPxSolver::lbBound() "lbBound()" and \ref SPxSolver::ubBound() "ubBound()" within \ref SPxSolver::entertol() "entertol()". fVec().delta() is the vector by which fVec() will be updated in this simplex step. Its nonzero indices are stored in sorted order in fVec().idx(). If \p val > 0, \p val is the maximum allowed update value for fVec(), otherwise the minimum. Method #selectLeave() must chose \p val of the same sign as passed, such that updating fVec() by \p val yields a new vector that satisfies all basic bounds (within entertol). The returned index, must be the index of an element of fVec(), that reaches one of its bounds with this update. */ virtual int selectLeave(Real& val, Real enterTest, bool polish = false) = 0; /// selects variable Id to enter the basis. /** Method #selectEnter() is called by the loaded SoPlex solver, when computing the leaving simplex algorithm. It's task is to select and return the Id of the basis variable that is to enter the basis. When being called, \ref SPxSolver::pVec() "pVec()" fullfills the bounds \ref SPxSolver::lbBound() "lbBound()" and \ref SPxSolver::ubBound() "ubBound()" within \ref SPxSolver::leavetol() "leavetol()". Similarly, \ref SPxSolver::coPvec() "coPvec()" fulfills the bounds \ref SPxSolver::lbBound() "lbBound()" and \ref SPxSolver::ubBound() "ubBound()" within \ref SPxSolver::leavetol() "leavetol()". pVec().delta() and coPvec().delta() are the vectors by which pVec() and coPvec() will be updated in this simplex step. Their nonzero indices are stored in sorted order in pVec().idx() and coPvec().idx(). If \p val > 0, \p val is the maximum allowed update value for pVec() and coPvec(), otherwise the minimum. Method #selectEnter() must chose \p val of the same sign as passed, such that updating pVec() and coPvec() by \p val yields a new vector that satisfies all basic bounds (within leavetol). The returned Id must be the Id of an element of pVec() or coPvec(), that reaches one of its bounds with this update. */ virtual SPxId selectEnter(Real& val, int leaveIdx, bool polish = false) = 0; /// sets Simplex type. /** Informs pricer about (a change of) the loaded SoPlex's Type. In the sequel, only the corresponding select methods may be called. */ virtual void setType(SPxSolver::Type) {} //@} //------------------------------------- /**@name Construction / destruction */ //@{ /// default constructor explicit SPxRatioTester(const char* name) : thesolver(0) , m_name(name) , m_type(SPxSolver::LEAVE) , delta(1e-6) {} /// copy constructor SPxRatioTester( const SPxRatioTester& old) : thesolver(old.thesolver) , m_name(old.m_name) , m_type(old.m_type) , delta(old.delta) {} /// assignment operator SPxRatioTester& operator=( const SPxRatioTester& rhs) { if(this != &rhs) { m_name = rhs.m_name; thesolver = rhs.thesolver; m_type = rhs.m_type; delta = rhs.delta; } return *this; } /// destructor. virtual ~SPxRatioTester() { thesolver = 0; m_name = 0; } /// clone function for polymorphism virtual SPxRatioTester* clone() const = 0; //@} }; } // namespace soplex #endif // _SPXRATIOTESTER_H_
ArtemJDev/design-architectural-patterns
patterns/src/main/java/com/other/solid/LiskovSubstitution/Main.java
<filename>patterns/src/main/java/com/other/solid/LiskovSubstitution/Main.java package com.other.solid.LiskovSubstitution; public class Main { static Rectangle getRect() { return new Rectangle(); } public static void main(String[] args) { Rectangle rectangle = getRect(); rectangle.setHeight(10); rectangle.setWodth(5); System.out.println(rectangle.getArea()); } }
bublesy/qiqi
dream/qiqi-security/src/main/java/com/qiqi/security/entity/AuthenticationBean.java
package com.qiqi.security.entity; import lombok.Getter; import lombok.Setter; /** * @author QiQiDream * @date 2020-06-18 10:42 */ @Getter @Setter public class AuthenticationBean { private String username; private String password; }
kiranmai-sfdev/aura
aura/src/main/java/org/auraframework/def/TestCaseDef.java
<reponame>kiranmai-sfdev/aura<gh_stars>100-1000 /* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.def; import java.util.Collection; import java.util.Map; import java.util.Set; import org.auraframework.def.DefDescriptor.DefType; /** * An individual test case for a component. TestCaseDef is a sub-definition of TestSuiteDef. */ public interface TestCaseDef extends Definition { /** * The attributes which should be used to instantiate the component under test. * * @return the Map of attribute names to values used to instantiate the component under test */ Map<String, Object> getAttributeValues(); /** * The type of component under test, typically an Application or Component. * * @return the DefType of the component under test */ DefType getDefType(); /** * Labels intended to categorize test cases, although no explicit grouping is applied. * * @return the Set of labels this test is tagged with */ Set<String> getTestLabels(); /** * Specialized labels intended to describe target client platforms for this test case. * * @return the Set of "browsers" this test should apply to */ Set<String> getBrowsers(); /** * Definitions that are expected to be present for this test case to run, typically stubbed implementations of * actual Definitions. These should take precedence over any existing Definitions with the same DefDescriptor. * * @return the Set of Definitions expected by this test case */ Collection<Definition> getLocalDefs(); /** * The set of Aura errors (displayed via $A.error) that are allowed during initialization. These exceptions will not * cause the test to fail. * * @return The Set of Aura errors that are allowed during initialization */ Set<String> getAuraErrorsExpectedDuringInit(); /** * Return the qualified name of the test case. if current browser info is available, it will contain the browser * type too. for example: * js://auraStorageTest.initTest/TESTCASE$testRefreshErrorResponseNotStored:BROWSERTYPEgooglechrome * * @return the qualified name the the test case */ String getQualifiedName(); /** * set currentBrowser of this test case * * @param b name of the browser, like googlechrome */ public void setCurrentBrowser(String b); /** * scrumTeam intended for a particular test cases, * * @return the scrumTeam for this test is tagged with */ String getScrumTeam(); /** * Owner intended for a particular test cases, * * @return the owner for this test is tagged with */ String getOwner(); }
turbaszek/dbnd
plugins/dbnd-gcp/src/dbnd_gcp/apache_beam/apache_beam_task.py
from __future__ import absolute_import import logging import subprocess import typing from typing import Dict, List from dbnd import parameter from dbnd._core.configuration.config_path import from_task_env from dbnd._core.decorator.decorated_task import _DecoratedTask from dbnd._core.decorator.func_task_decorator import _task_decorator from dbnd._core.errors import DatabandConfigError, friendly_error from dbnd._core.settings.engine import EngineConfig from dbnd._core.task_ctrl.task_repr import _parameter_value_to_argparse_str from dbnd.tasks import Config, Task from dbnd_gcp.apache_beam import ApacheBeamJobCtrl if typing.TYPE_CHECKING: from dbnd_gcp.dataflow.dataflow_config import DataflowConfig logger = logging.getLogger(__name__) class ApacheBeamConfig(Config): """Apache Beam (-s [TASK].spark.[PARAM]=[VAL] for specific tasks)""" # we don't want spark class to inherit from this one, as it should has Config behaviour _conf__task_family = "beam" jar = parameter.value(None, description="Main application jar")[str] verbose = parameter.value( False, description="Whether to pass the verbose flag to spark-submit process for debugging", ) options = parameter(empty_default=True)[Dict[str, str]] class LocalBeamEngineConfig(EngineConfig): def get_beam_ctrl(self, task_run): from dbnd_gcp.apache_beam.local_apache_beam import LocalApacheBeamJobCtrl return LocalApacheBeamJobCtrl(task_run) class _BeamTask(Task): beam_config = parameter(config_path=from_task_env("beam_config"))[ApacheBeamConfig] beam_engine = parameter(config_path=from_task_env("beam_engine"))[ EngineConfig ] # type: DataflowConfig def get_beam_task_options(self): """ 'Arguments for the application being submitted' :return: list """ return {} def _get_job_ctrl(self): # type:(...)->ApacheBeamJobCtrl return self.beam_engine.get_beam_ctrl(self.current_task_run) class ApacheBeamJavaTask(_BeamTask): main_class = parameter.none( description="The entry point for your application", system=True )[str] def _task_submit(self): if not self.beam.main_jar: raise DatabandConfigError("main_jar is not configured for %s" % self) return self._get_job_ctrl().run_cmd_java( jar=self.beam.jar, main_class=self.main_class ) class ApacheBeamPythonTask(_BeamTask): py_file = parameter.help("The application that submitted as *.py file").none[str] py_options = parameter(empty_default=True)[List[str]] def _task_submit(self): return self._get_job_ctrl().run_cmd_python( py_file=self.py_file, py_options=self.py_options ) class _ApacheBeamInlineTask(_BeamTask, _DecoratedTask): _conf__require_run_dump_file = True dataflow_build_pipeline = parameter( system=True, description="Build Pipeline object if not set" ).value(True) dataflow_wait_until_finish = parameter( system=True, description="Automatically wait for pipeline run finish" ).value(True) dataflow_submit_dbnd_info = parameter( system=True, description="Add databand data to PipelineOptions" ).value(True) dataflow_pipeline = parameter(system=True, description="Dataflow Pipeline").value( None )[object] def _task_run(self): super(_ApacheBeamInlineTask, self)._task_run() def _task_options(self, python_pipeline_options): # We use the save_main_session option because one or more DoFn's in this # workflow rely on global context (e.g., a module imported at module level). from apache_beam.options.pipeline_options import PipelineOptions user_params = self._params.get_param_values(user_only=True) class TaskOptions(PipelineOptions): @classmethod def _add_argparse_args(cls, parser): for dbnd_key in [ "databand_url", "task_id", "task_function", "task_vcs", ]: parser.add_argument( "--dbnd-%s" % (dbnd_key.replace("_", "-")), help="Databand %s" % dbnd_key, default=None, dest="dbnd_%s" % dbnd_key, ) for param_obj, param_name in user_params: action = ( "store_true" if param_obj.value_type.type is bool else "store" ) parser.add_argument( ["--" + param_name.lower().replace("_", "-")], help=param_obj.description, default=None, action=action, dest=param_name, ) for p, p_value in user_params: argparse_str = _parameter_value_to_argparse_str(p, p_value) python_pipeline_options.extend(argparse_str) python_pipeline_options.extend( [ "--dbnd-tracker-url", self.ctrl.task_run.task_tracker_url, "--dbnd-task-id", self.task_id, "--dbnd-task-function", self.task_definition.full_task_family, "--dbnd-task-vcs", self.ctrl.task_run.run.source_version, ] ) logger.info( "Creating beam pipeline options: %s", subprocess.list2cmdline(python_pipeline_options), ) pipeline_options = TaskOptions(python_pipeline_options) return pipeline_options def run(self): # We use the save_main_session option because one or more DoFn's in this # workflow rely on global context (e.g., a module imported at module level). if self.dataflow_pipeline is None and self.dataflow_build_pipeline: self.dataflow_pipeline = self.build_pipeline() self._invoke_func() if self.dataflow_wait_until_finish: if self.dataflow_pipeline is None: raise friendly_error.tools.dataflow_pipeline_not_set(self) result = self.dataflow_pipeline.run() result.wait_until_finish() def build_pipeline(self, extra_pipeline_options=None): python_pipeline_options = self._get_job_ctrl().get_python_options() if extra_pipeline_options: python_pipeline_options.extend(extra_pipeline_options) if self.dataflow_submit_dbnd_info: pipeline_options = self._task_options(python_pipeline_options) else: logger.info( "Creating beam pipeline options: %s", subprocess.list2cmdline(python_pipeline_options), ) from apache_beam.options.pipeline_options import PipelineOptions pipeline_options = PipelineOptions(python_pipeline_options) import apache_beam return apache_beam.Pipeline(options=pipeline_options) def beam_task(*args, **kwargs): kwargs.setdefault("_task_type", _ApacheBeamInlineTask) kwargs.setdefault("_task_default_result", parameter.output.pickle[object]) return _task_decorator(*args, **kwargs)
ethansaxenian/RosettaDecode
lang/Go/ordered-words.go
package main import ( "bytes" "fmt" "io/ioutil" ) func main() { // read into memory in one chunk b, err := ioutil.ReadFile("unixdict.txt") if err != nil { fmt.Println(err) return } // split at line ends bss := bytes.Split(b, []byte{'\n'}) // accumulate result var longest int var list [][]byte for _, bs := range bss { // don't bother with words shorter than // our current longest ordered word if len(bs) < longest { continue } // check for ordered property var lastLetter byte for i := 0; ; i++ { if i == len(bs) { // end of word. it's an ordered word. // save it and break from loop if len(bs) > longest { longest = len(bs) list = list[:0] } list = append(list, bs) break } // check next letter b := bs[i] if b < 'a' || b > 'z' { continue // not a letter. ignore. } if b < lastLetter { break // word not ordered. } // letter passes test lastLetter = b } } // print result for _, bs := range list { fmt.Println(string(bs)) } }
brettdavidson3/eclipselink.runtime
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/xmltype/builtin/MyDate.java
package org.eclipse.persistence.testing.jaxb.xmltype.builtin; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; @XmlType(namespace="http://www.w3.org/2001/XMLSchema", name="date") public class MyDate { @XmlValue public String value; }
sanj0/salty-engine
src/main/java/de/edgelord/saltyengine/components/Components.java
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.edgelord.saltyengine.components; /** * A list of String constants of tags for Components */ public abstract class Components { public static final String PRIMITIVES_RENDER_COMPONENT = "de.edgelord.saltyengine.components.simpleRenderComponent"; public static final String ACCELERATOR_COMPONENT = "de.edgelord.saltyengine.components.accelerator"; public static final String TECHNICAL_DRAW_COMPONENT = "de.edgelord.saltyengine.components.technicalDrawComponent"; public static final String CORE_COMPONENT = "de.edgelord.saltyengine.components.core"; public static final String PHYSICS_COMPONENT = "de.edgelord.saltyengine.components.physics"; public static final String RENDER_COMPONENT = "de.edgelord.saltyengine.components.renderComponent"; public static final String GFX_COMPONENT = "de.edgelord.saltyengine.components.gfx"; public static final String ANIMATION_COMPONENT = "de.edgelord.saltyengine.components.animation"; public static final String TIMING_COMPONENT = "de.edgelord.saltyengine.components.timing"; public static final String COLLIDER_COMPONENT = "de.edgelord.saltyengine.components.collider"; public static final String CAMERA_COMPONENT = "de.edgelord.saltyengine.components.camera"; public static final String GAME_COMPONENT = "de.edgelord.saltyengine.components.game"; public static final String GAMEOBJECT_BEHAVIOUR = "de.edgelord.saltyengine.components.gameobjectBehaviour"; public static final String GIF_RENDER = "de.edgelord.saltyengine.components.gifRender"; public static final String EMITTER_COMPONENT = "de.edgelord.saltyengine.components.emitter"; public static final String UTILITY_COMPONENT = "de.edgelord.saltyengine.components.utility"; }
ViniVelasco/Books-App
app/src/main/java/cmp1144/pucgoias/com/booksapp/Fragment/CadastroUsuarios.java
<filename>app/src/main/java/cmp1144/pucgoias/com/booksapp/Fragment/CadastroUsuarios.java package cmp1144.pucgoias.com.booksapp.Fragment; import android.app.DatePickerDialog; import android.app.Fragment; import android.icu.text.SimpleDateFormat; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.util.Base64; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.RadioButton; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException; import com.google.firebase.auth.FirebaseAuthUserCollisionException; import com.google.firebase.auth.FirebaseAuthWeakPasswordException; import com.google.firebase.auth.FirebaseUser; import java.util.Calendar; import java.util.Date; import cmp1144.pucgoias.com.booksapp.DAO.ConfiguracaoFireBase; import cmp1144.pucgoias.com.booksapp.Entidades.Usuario; import cmp1144.pucgoias.com.booksapp.Helper.Base64Custom; import cmp1144.pucgoias.com.booksapp.Helper.Mensagem; import cmp1144.pucgoias.com.booksapp.Helper.Preferencias; import cmp1144.pucgoias.com.booksapp.R; public class CadastroUsuarios extends Fragment { View myView; EditText textNome, textSobrenome, textEmail, textSenha, textDataNascimento, textTelefone; RadioButton radioMasc, radioFem; Button btnSelecionarData, btnCadastrar; private Usuario usuario; private FirebaseAuth autenticacao; private int ano, mes, dia; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { myView = inflater.inflate(R.layout.cadastro_usuarios, container, false); return myView; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); bindingComponents(); selecionarData(); btnCadastrar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(textNome.getText().toString().isEmpty() || textEmail.getText().toString().isEmpty() || textSenha.getText().toString().isEmpty() || textSobrenome.getText().toString().isEmpty() || textSobrenome.getText().toString().isEmpty() || textDataNascimento.getText().toString().isEmpty() || textTelefone.getText().toString().isEmpty()){ Mensagem.alerta("Por favor, preencha todos os campos", getContext()); } else { usuario = new Usuario(); usuario.setNome(textNome.getText().toString()); usuario.setEmail(textEmail.getText().toString()); usuario.setSenha(<PASSWORD>ha.getText().toString()); usuario.setSobrenome(textSobrenome.getText().toString()); usuario.setDataNascimento(textDataNascimento.getText().toString()); usuario.setTelefone(textTelefone.getText().toString()); if(radioMasc.isChecked()){ usuario.setSexo("Masculino"); } else { usuario.setSexo("Feminino"); } cadastrarUsuario(); } } }); } /** * Associa os elementos da activity às variáveis */ public void bindingComponents(){ textNome = (EditText) getView().findViewById(R.id.textNome); textSobrenome = (EditText) getView().findViewById(R.id.textSobrenome); textEmail = (EditText) getView().findViewById(R.id.textEmail); textSenha = (EditText) getView().findViewById(R.id.textSenha); textTelefone = (EditText) getView().findViewById(R.id.textTelefone); textDataNascimento = (EditText) getView().findViewById(R.id.textDataNascimento); textDataNascimento.setEnabled(false); radioMasc = (RadioButton) getView().findViewById(R.id.radioMasc); radioFem = (RadioButton) getView().findViewById(R.id.radioFem); btnSelecionarData = (Button) getView().findViewById(R.id.btnSelecionarData); btnCadastrar = (Button) getView().findViewById(R.id.btnCadastrar); } /** * Cadastra o usuário no WebService */ private void cadastrarUsuario(){ autenticacao = ConfiguracaoFireBase.getFirebaseAutenticacao(); autenticacao.createUserWithEmailAndPassword(usuario.getEmail(), usuario.getSenha() ).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ alerta("Usuário cadastrado com sucesso!"); String identificadorUsuario = Base64Custom.codificarBase64(usuario.getEmail()); FirebaseUser usuarioFirebase = task.getResult().getUser(); usuario.setId(identificadorUsuario); usuario.salvar(); Preferencias preferencias = new Preferencias(getContext()); preferencias.salvarUsuarioPreferencias(identificadorUsuario, usuario.getNome()); } else { String erro = ""; try { throw task.getException(); } catch(FirebaseAuthWeakPasswordException e) { erro = "Digite uma senha forte, contendo no mínimo 8 caracteres de letras e números."; } catch(FirebaseAuthInvalidCredentialsException e) { erro = "O e-mail digitado é inválido, digite um novo e-mail."; } catch(FirebaseAuthUserCollisionException e) { erro = "Esse e-mail já está cadastrado."; } catch(Exception e) { erro = "Erro ao efetuar o cadastrado, verifique a conexão com a internet."; e.printStackTrace(); } alerta(erro); } } }); } /** * Método que cria o DatePicker para a seleção de data de nascimento */ private void selecionarData() { btnSelecionarData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Calendar c = Calendar.getInstance(); ano = c.get(Calendar.YEAR); mes = c.get(Calendar.MONTH); dia = c.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() { @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { textDataNascimento.setText(formatDate(year, month , dayOfMonth)); } }, ano, mes, dia); datePickerDialog.show(); } }); } /** * Método que formata a data do DatePicker * @param year * @param month * @param day * @return */ @RequiresApi(api = Build.VERSION_CODES.N) private static String formatDate(int year, int month, int day) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(0); cal.set(year, month, day); Date date = cal.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); return sdf.format(date); } private void alerta(String msg){ Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); } }
simon-m-mudd/LSDMappingTools
ArchiveTestScripts/FJCTestArtist2.py
# -*- coding: utf-8 -*- """ Created on Fri Feb 10 16:57:22 2017 @author: smudd """ # -*- coding: utf-8 -*- """ Created on Fri Feb 10 12:55:23 2017 @author: smudd """ import matplotlib matplotlib.use('Agg') import matplotlib.cm as cm from LSDMapFigure.PlottingRaster import MapFigure from LSDMapFigure.PlottingRaster import BaseRaster import matplotlib.pyplot as plt from LSDPlottingTools import colours as lsdcolours from LSDPlottingTools import init_plotting_DV import sys from LSDPlottingTools import LSDMap_VectorTools as LSDMap_VT # Generate random colormap def rand_cmap(nlabels, type='bright', first_color_black=True, last_color_black=False, verbose=True): """ Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks :param nlabels: Number of labels (size of colormap) :param type: 'bright' for strong colors, 'soft' for pastel colors :param first_color_black: Option to use first color as black, True or False :param last_color_black: Option to use last color as black, True or False :param verbose: Prints the number of labels and shows the colormap. True or False :return: colormap for matplotlib """ from matplotlib.colors import LinearSegmentedColormap import colorsys import numpy as np if type not in ('bright', 'soft'): print ('Please choose "bright" or "soft" for type') return if verbose: print('Number of labels: ' + str(nlabels)) # Generate color map for bright colors, based on hsv if type == 'bright': randHSVcolors = [(np.random.uniform(low=0.0, high=1), np.random.uniform(low=0.2, high=1), np.random.uniform(low=0.9, high=1)) for i in xrange(nlabels)] # Convert HSV list to RGB randRGBcolors = [] for HSVcolor in randHSVcolors: randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0], HSVcolor[1], HSVcolor[2])) if first_color_black: randRGBcolors[0] = [0, 0, 0] if last_color_black: randRGBcolors[-1] = [0, 0, 0] random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels) # Generate soft pastel colors, by limiting the RGB spectrum if type == 'soft': low = 0.6 high = 0.95 randRGBcolors = [(np.random.uniform(low=low, high=high), np.random.uniform(low=low, high=high), np.random.uniform(low=low, high=high)) for i in xrange(nlabels)] if first_color_black: randRGBcolors[0] = [0, 0, 0] if last_color_black: randRGBcolors[-1] = [0, 0, 0] random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels) # Display colorbar if verbose: from matplotlib import colors, colorbar from matplotlib import pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(15, 0.5)) bounds = np.linspace(0, nlabels, nlabels + 1) norm = colors.BoundaryNorm(bounds, nlabels) cb = colorbar.ColorbarBase(ax, cmap=random_colormap, norm=norm, spacing='proportional', ticks=None, boundaries=bounds, format='%1i', orientation=u'horizontal') return random_colormap #sys.path.append("PATH/TO/LSDPlottingTools/") # #init_plotting_DV() Directory = "/media/fionaclubb/terrace_lidar/Mendocino_TJ/mendocino/coastal_california/" #Directory = "T:\\analysis_for_papers\\Meghalaya\\divide_migration\\" Base_file = "California_clip" #BackgroundRasterName = Base_file+".bil" DrapeRasterName = Base_file+"_hs.bil" BasinsName = Base_file+"_basins.bil" #BR = BaseRaster(BackgroundRasterName, Directory) #BR.set_raster_type("Terrain") #print(BR._colourmap) #BR.show_raster() #BR.set_colourmap("RdYlGn") #BR.show_raster() #label_size = 100 #rcParams['font.family'] = 'sans-serif' #rcParams['font.sans-serif'] = ['Liberation Sans'] #rcParams['font.size'] = label_size #rcParams['lines.linewidth'] = 1.5 plt.clf() MF = MapFigure(DrapeRasterName, Directory,coord_type="UTM_km",colourbar_location='None') # add the basins drape cmap = cm.Set1 MF.add_drape_image(BasinsName, Directory, colourmap = cmap, alpha = 0.5, colorbarlabel='Basin ID', show_colourbar = False) # add the basin outlines Basins = LSDMap_VT.GetBasinOutlines(Directory, BasinsName) MF.plot_polygon_outlines(Basins, linewidth=0.8) #MF.add_drape_image(ChiRasterName,Directory,colourmap = "cubehelix",alpha = 0.4, show_colourbar = True) #MF.show_plot() MF.save_fig(fig_width_inches = 12, FigFileName=Directory+Base_file+'.png', FigFormat='png', Fig_dpi=300, transparent=True) # Customise the DrapePlot #dp.make_drape_colourbar(cbar_label=colourbar_label) #dp.set_fig_axis_labels() #dp.show_plot()
synctera/client-libraries-go
synctera/model_bin_and_debit_network.go
/* Synctera API <h2>Let's build something great.</h2><p>Welcome to the official reference documentation for Synctera APIs. Our APIs are the best way to automate your company's banking needs and are designed to be easy to understand and implement.</p><p>We're continuously growing this library and what you see here is just the start, but if you need something specific or have a question, <a class='text-blue-600' href='https://synctera.com/contact' target='_blank' rel='noreferrer'>contact us</a>.</p> API version: 0.5.0 */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package openapi import ( "encoding/json" ) // BinAndDebitNetwork struct for BinAndDebitNetwork type BinAndDebitNetwork struct { // The ID of the bank network BankNetworkId string `json:"bank_network_id"` Bin Bin `json:"bin"` DebitNetwork DebitNetwork `json:"debit_network"` } // NewBinAndDebitNetwork instantiates a new BinAndDebitNetwork object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewBinAndDebitNetwork(bankNetworkId string, bin Bin, debitNetwork DebitNetwork) *BinAndDebitNetwork { this := BinAndDebitNetwork{} this.BankNetworkId = bankNetworkId this.Bin = bin this.DebitNetwork = debitNetwork return &this } // NewBinAndDebitNetworkWithDefaults instantiates a new BinAndDebitNetwork object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewBinAndDebitNetworkWithDefaults() *BinAndDebitNetwork { this := BinAndDebitNetwork{} return &this } // GetBankNetworkId returns the BankNetworkId field value func (o *BinAndDebitNetwork) GetBankNetworkId() string { if o == nil { var ret string return ret } return o.BankNetworkId } // GetBankNetworkIdOk returns a tuple with the BankNetworkId field value // and a boolean to check if the value has been set. func (o *BinAndDebitNetwork) GetBankNetworkIdOk() (*string, bool) { if o == nil { return nil, false } return &o.BankNetworkId, true } // SetBankNetworkId sets field value func (o *BinAndDebitNetwork) SetBankNetworkId(v string) { o.BankNetworkId = v } // GetBin returns the Bin field value func (o *BinAndDebitNetwork) GetBin() Bin { if o == nil { var ret Bin return ret } return o.Bin } // GetBinOk returns a tuple with the Bin field value // and a boolean to check if the value has been set. func (o *BinAndDebitNetwork) GetBinOk() (*Bin, bool) { if o == nil { return nil, false } return &o.Bin, true } // SetBin sets field value func (o *BinAndDebitNetwork) SetBin(v Bin) { o.Bin = v } // GetDebitNetwork returns the DebitNetwork field value func (o *BinAndDebitNetwork) GetDebitNetwork() DebitNetwork { if o == nil { var ret DebitNetwork return ret } return o.DebitNetwork } // GetDebitNetworkOk returns a tuple with the DebitNetwork field value // and a boolean to check if the value has been set. func (o *BinAndDebitNetwork) GetDebitNetworkOk() (*DebitNetwork, bool) { if o == nil { return nil, false } return &o.DebitNetwork, true } // SetDebitNetwork sets field value func (o *BinAndDebitNetwork) SetDebitNetwork(v DebitNetwork) { o.DebitNetwork = v } func (o BinAndDebitNetwork) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["bank_network_id"] = o.BankNetworkId } if true { toSerialize["bin"] = o.Bin } if true { toSerialize["debit_network"] = o.DebitNetwork } return json.Marshal(toSerialize) } type NullableBinAndDebitNetwork struct { value *BinAndDebitNetwork isSet bool } func (v NullableBinAndDebitNetwork) Get() *BinAndDebitNetwork { return v.value } func (v *NullableBinAndDebitNetwork) Set(val *BinAndDebitNetwork) { v.value = val v.isSet = true } func (v NullableBinAndDebitNetwork) IsSet() bool { return v.isSet } func (v *NullableBinAndDebitNetwork) Unset() { v.value = nil v.isSet = false } func NewNullableBinAndDebitNetwork(val *BinAndDebitNetwork) *NullableBinAndDebitNetwork { return &NullableBinAndDebitNetwork{value: val, isSet: true} } func (v NullableBinAndDebitNetwork) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableBinAndDebitNetwork) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
brunodevel/GloboNetworkAPI
networkapi/ip/urls_network.py
<reponame>brunodevel/GloboNetworkAPI<filename>networkapi/ip/urls_network.py # -*- coding: utf-8 -*- from __future__ import absolute_import from django.conf.urls import patterns, url from networkapi.ip.resource.NetworkAddResource import NetworkAddResource from networkapi.ip.resource.NetworkEditResource import NetworkEditResource from networkapi.ip.resource.NetworkIPv4AddResource import NetworkIPv4AddResource from networkapi.ip.resource.NetworkIPv4DeallocateResource import NetworkIPv4DeallocateResource from networkapi.ip.resource.NetworkIPv4GetResource import NetworkIPv4GetResource from networkapi.ip.resource.NetworkIPv6AddResource import NetworkIPv6AddResource from networkapi.ip.resource.NetworkIPv6DeallocateResource import NetworkIPv6DeallocateResource from networkapi.ip.resource.NetworkIPv6GetResource import NetworkIPv6GetResource from networkapi.ip.resource.NetworkRemoveResource import NetworkRemoveResource from networkapi.ip.resource.SearchIPv6EnvironmentResource import SearchIPv6EnvironmentResource networkip4_get_resource = NetworkIPv4GetResource() networkip6_get_resource = NetworkIPv6GetResource() network_edit_resource = NetworkEditResource() network_add_resource = NetworkAddResource() network_remove_resource = NetworkRemoveResource() network_ipv4_add_resource = NetworkIPv4AddResource() network_ipv4_deallocate_resource = NetworkIPv4DeallocateResource() network_ipv6_add_resource = NetworkIPv6AddResource() network_ipv6_deallocate_resource = NetworkIPv6DeallocateResource() search_ipv6_environment = SearchIPv6EnvironmentResource() urlpatterns = patterns('', url(r'^ipv4/id/(?P<id_rede4>[^/]+)/$', networkip4_get_resource.handle_request, name='network.ip4.get.by.id'), url(r'^ipv6/id/(?P<id_rede6>[^/]+)/$', networkip6_get_resource.handle_request, name='network.ip6.get.by.id'), url(r'^add/$', network_add_resource.handle_request, name='network.add'), url(r'^edit/$', network_edit_resource.handle_request, name='network.edit'), url(r'^create/$', network_edit_resource.handle_request, name='network.create'), url(r'^remove/$', network_remove_resource.handle_request, name='network.remove'), url(r'^ipv4/add/$', network_ipv4_add_resource.handle_request, name='network.ipv4.add'), url(r'^ipv4/(?P<id_network_ipv4>[^/]+)/deallocate/$', network_ipv4_deallocate_resource.handle_request, name='network.ipv4.deallocate'), url(r'^ipv6/add/$', network_ipv6_add_resource.handle_request, name='network.ipv6.add'), url(r'^ipv6/(?P<id_network_ipv6>[^/]+)/deallocate/$', network_ipv6_deallocate_resource.handle_request, name='network.ipv6.deallocate') )
stinsonga/geo-prime-workspace
work/exampleAFCR.js
<reponame>stinsonga/geo-prime-workspace function my_function472(){ //49005651230582861133084656003251afvRZAXyFchVOiWZzsvTONjEcDpgnpMS } function my_function464(){ //97758245539863081798075680056194AlAGqkwWyHcvQHxayAphlMySeXWRAjbK } function my_function154(){ //87994934410762777794976212256900hvWutabkvFPyydqSTvXOwQlRiQKqenjA } function my_function026(){ //00682303382601746612495067490773WXecOkThiNOCFueSZCAdsojSgMQHivLo } function my_function122(){ //80235692809155624929076148038705SjFudHfPwNeeGwjeXZbYzvgQMjhrcEha } function my_function532(){ //95932874615244788266919584912272vnWMAkEmVMmxzhOGWZbwTnTXReaYOjTG } function my_function261(){ //72386100879093118622882644325014qnzteID<KEY> } function my_function168(){ //54340820993412987599820064611320TnyFmaXfXkJOGcFyyzDMWznnWhIpbdpJ } function my_function990(){ //78626160972986398577038495759297kxUdISgzgjiNqDLcvqFooSPyDGxmJAZj } function my_function589(){ //33720716714516053735293974887390rZYkVbkALvKFHmlNmivVMTdOuRNaNeqf } function my_function257(){ //65892868956231123111523821050737tvIFdnaWHFClxZOPINmNGvxTDMiIZEMw } function my_function525(){ //52416975708153665350036015166187krICHZsrWgcvjCvqwnukjnTNjWtCOVPT } function my_function677(){ //13506605121158239474702285103567qRYUSKXJPGbjzdPUxfCbzxjJTreUaWAG } function my_function484(){ //41601975606555958503776898962997hiQCorcCAVkAXNgPdPNxNyPGihZssaNR } function my_function455(){ //21354995963042872333063057838412xikuwqESxsDOoFKVhxoRhXybiZBNQOaS } function my_function066(){ //26558078222046547459830201160602nGTokFCTGYrtrOB<KEY> } function my_function166(){ //06757686477673445939222145593713FFemIcCAecTBBRUGmEWWkHjXBWkPOOHk } function my_function990(){ //45646142192502560780991687965822axFVFACthbwsvusacvDtrGclVINomOpg } function my_function141(){ //37038742063314945360488894290159VskUbKgNgngIKonJLQgyeosVxMZpoMcT } function my_function447(){ //56516622713617560262638379853150EDddZUAzaUwTPqPueqSBDwdBZpyhIoVe } function my_function360(){ //62678599924398859069837907344685GjxtDeWHILtnbKdDqtVsyxNDkHXiPxYV } function my_function736(){ //54298321454275078669215461407341hyxdxTAozTpPhbeapQITTBMBxetsZeGa }
phorward/rapidbatch
rb_comp.codegen.c
/* -MODULE---------------------------------------------------------------------- RapidBATCH Copyright (C) 2008, 2009 by Phorward Software Technologies, <NAME> http://www.phorward-software.com ++ <EMAIL> File: rb_comp.codegen.c Author: <NAME> Usage: Virtual machine code generator ----------------------------------------------------------------------------- */ /* * Includes */ #include "rb_global.h" /* * Global variables */ static vm_prog* patch_prog; static vm_code patch_instr; static vm_addr patch_addr; static pboolean patch_required = FALSE; /* * Functions */ /* -FUNCTION-------------------------------------------------------------------- Function: rb_comp_next_addr() Author: <NAME> Usage: Sets up a new code address and returns its pointer. Parameters: vm_prog* prog Program to be extended vm_code instr The command which should be allocated (including a possible parameter) Returns: vm_addr The new (next) address ~~~ CHANGES & NOTES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Date: Author: Note: ----------------------------------------------------------------------------- */ vm_addr rb_comp_next_addr( vm_prog* prog, vm_code instr ) { char allocsize; PROC( "rb_comp_next_addr" ); PARMS( "prog", "%p", prog ); PARMS( "instr", "%d", instr ); allocsize = 1 + VM_GET_PARAM_SIZE( instr ); VARS( "required size for this command is", "%d", allocsize ); prog->cur_addr = prog->code_next; VARS( "start", "%ld", prog->cur_addr ); for( ; allocsize > 0; allocsize-- ) { if( prog->code_cnt == 0 ) { prog->code = (vm_code*)pmalloc( MALLOC_STEP * sizeof( vm_code ) ); prog->code_cnt = MALLOC_STEP; } else if( prog->code_next == prog->code_cnt ) { prog->code = (vm_code*)prealloc( (vm_code*)( prog->code ), ( prog->code_cnt + MALLOC_STEP ) * sizeof( vm_code ) ); prog->code_cnt += MALLOC_STEP; } if( !( prog->code ) ) OUTOFMEM; prog->code[ prog->code_next++ ] = 0; } prog->code[ prog->cur_addr ] = instr; /* Patch a possible Jump! */ if( patch_required && patch_prog == prog ) { rb_comp_patch( VM_GET_CODE( prog, patch_addr ), patch_instr, &( prog->cur_addr ) ); patch_required = FALSE; } RETURN( prog->cur_addr ); } /* -FUNCTION-------------------------------------------------------------------- Function: rb_comp_patch_jmp() Author: <NAME> Usage: Sets the code generator's patch variables to patch a program address with the next code memory request. This causes lesser generation of NOP-instructions. USE CAREFULLY! Parameters: vm_prog Program to be patched vm_addr Address of the instruction, where a program address must be patched. Returns: void ~~~ CHANGES & NOTES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Date: Author: Note: ----------------------------------------------------------------------------- */ void rb_comp_patch_jmp( vm_prog* prog, vm_code instr, vm_addr call ) { patch_required = TRUE; patch_prog = prog; patch_instr = instr; patch_addr = call; } /* -FUNCTION-------------------------------------------------------------------- Function: rb_comp_cur_addr() Author: <NAME> Usage: Sets up a new code address and returns a pointer. Parameters: vm_prog* prog Program to be extended Returns: vm_addr Current address ~~~ CHANGES & NOTES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Date: Author: Note: ----------------------------------------------------------------------------- */ vm_addr rb_comp_cur_addr( vm_prog* prog ) { PROC( "rb_comp_cur_addr" ); PARMS( "prog", "%p", prog ); RETURN( prog->cur_addr ); } /* -FUNCTION-------------------------------------------------------------------- Function: rb_comp_patch() Author: <NAME> Usage: Patches an existing vm_code item with a cmd and a possible operand. Parameters: vm_code* code Code item to be patched int instr Virtual machine command to be set up. If < 0, then the instruction is not set, only the parameter. void* parm Parameter pointer; This must be of a type instr requires. Returns: pboolean TRUE, if all worked fine, FALSE, in case param contained invalid data for the instr. ~~~ CHANGES & NOTES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Date: Author: Note: ----------------------------------------------------------------------------- */ /* pboolean rb_comp_patch_d( char* file, int line, vm_code* code, int instr, void* parm ) */ pboolean rb_comp_patch( vm_code* code, int instr, void* parm ) { char size; PROC( "rb_comp_patch" ); PARMS( "code", "%p", code ); PARMS( "instr", "%d", instr ); PARMS( "parm", "%p", parm ); /* fprintf( stderr, "BACKPATCHING from %s %d: %x as %d\n", file, line, code - ( cur_prog.code ), instr ); rb_vm_dump( stderr, &cur_prog ); fprintf( stderr, "\n" ); */ if( instr >= 0 ) *code = (vm_code)instr; VARS( "instr", "%d", instr ); if( ( size = VM_GET_PARAM_SIZE( instr ) ) ) { MSG( "Instruction has parameter!" ); memcpy( code+1, parm, size ); } /* rb_vm_dump( stderr, &cur_prog ); fprintf( stderr, "---------\n\n" ); */ RETURN( TRUE ); } /* -FUNCTION-------------------------------------------------------------------- Function: rb_comp_gen() Author: <NAME> Usage: Main code generation function, that creates a new code within a virtual machine program. Parameters: vm_prog* prog Program to be extended vm_cmd instr Virtual machine command void* parm Parameter pointer; This must be of a type instr requires. Returns: vm_addr Address of new instruction ~~~ CHANGES & NOTES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Date: Author: Note: ----------------------------------------------------------------------------- */ vm_addr rb_comp_gen( vm_prog* prog, vm_code instr, void* parm ) { vm_addr next; PROC( "rb_comp_gen" ); PARMS( "prog", "%p", prog ); PARMS( "instr", "%d", instr ); PARMS( "parm", "%p", parm ); next = rb_comp_next_addr( prog, instr ); rb_comp_patch( VM_GET_CODE( prog, next ), instr, parm ); RETURN( next ); }
msxiehui/eoLinker-API-Management-for-PHP
frontend_resource/src/app/component/navbar/index.service.js
<reponame>msxiehui/eoLinker-API-Management-for-PHP<gh_stars>1-10 (function() { 'use strict'; /** * @Author 广州银云信息科技有限公司 eolinker * @function [顶部栏(navbar)相关服务js] [Top bar (navbar) related services js] * @version 3.0.2 * @service $state [注入路由服务] [inject state service] * @service CommonResource [注入通用接口服务] [inject common API service] * @constant CODE [注入状态码常量] [inject status code constant service] * @return data [服务相关对象] [Service related object] */ angular.module('eolinker') .factory('NavbarService', NavbarService); NavbarService.$inject = ['$state', 'CommonResource', 'CODE'] function NavbarService($state, CommonResource, CODE) { var data = { info: { status: 0, //登录状态 Login status 0:没登录 Not logged in ,1:已登录 Has logged userInfo: { unreadMsgNum: null }, navigation: { query: [], current: '' } }, fun: { logout: null, $router: null } } /** * @function [退出登录功能函数] [Exit the login function function] */ data.fun.logout = function() { var template = { promise: null } template.promise = CommonResource.User.LoginOut().$promise; template.promise.then(function(response) { switch (response.statusCode) { case CODE.COMMON.SUCCESS: { if (/(project)|(home)|(database)|(gateway)/.test($state.current.name)) { //window.location.href $state.go('index'); } else { $state.reload(); } data.info.status = 0; break; } } }) return template.promise; } /** * @function [路由更换功能函数] [Routing replacement function function] */ data.fun.$router = function() { var template = { promise: null } if (data.info.status == 1) { template.promise = CommonResource.Message.UnReadNum().$promise template.promise.then(function(response) { switch (response.statusCode) { case CODE.COMMON.SUCCESS: { if (data.info.userInfo.unreadMsgNum != response.unreadMsgNum) { data.info.userInfo.unreadMsgNum = response.unreadMsgNum; } break; } case CODE.COMMON.UNLOGIN: { data.info.status = 0; break; } default: { data.info.unreadMsgNum = 0; break; } } }); } else { template.promise = CommonResource.User.Info().$promise; template.promise.then(function(response) { switch (response.statusCode) { case CODE.COMMON.SUCCESS: { data.info.userInfo = response.userInfo; data.info.status = 1; break; } default: { data.info.status = 0; } } }); } return template.promise; } return data; } })();
batterysim/oas
tests/permutations/test_permutations.py
#------------------------------------------------------------------------------- # Copyright 2006-2012 UT-Battelle, LLC. See LICENSE for more information. #------------------------------------------------------------------------------- #from processing import Queue import gc import pprint import sys import socket import getopt import os import traceback import time import unittest import logging import string import subprocess from test_parameterized_cases import ParameterizedTestCase sys.path.append('..') from frameworkpath import * sys.path.append(fsrc) from ips import Framework from configobj import ConfigObj class test_permutations(ParameterizedTestCase): def printUsageMessage(self): print 'Usage: ips [--create-runspace | --run-setup | --run]+ --simulation=SIM_FILE_NAME --platform=PLATFORM_FILE_NAME --log=LOG_FILE_NAME [--debug | --ftb]' def setUp(self): if self.param == None: return print print '------------------------------------------------------------------------------------' print 'Parameterization for this test' print 'Command - DO_CREATE_RUNSPACE =', ("F","T")[self.param.do_create_runspace], print ' DO_RUN_SETUP =', ("F","T")[self.param.do_run_setup], print ' DO_RUN =', ("F","T")[self.param.do_run] # print 'Command - DO_CREATE_RUNSPACE = %s DO_RUN_SETUP = %s DO_RUN = %s' % \ # (self.param.do_create_runspace, self.param.do_run_setup, self.param.do_run) print 'Checklist - CREATE_RUNSPACE_DONE =', ("F","T")[self.param.create_runspace_done], print ' RUN_SETUP_DONE =', ("F","T")[self.param.run_setup_done], print ' RUN_DONE =', ("F","T")[self.param.run_done] # print 'Checklist - CREATE_RUNSPACE_DONE = %s RUN_SETUP_DONE = %s RUN_DONE = %s' % \ # (self.param.create_runspace_done, self.param.run_setup_done, self.param.run_done) print '------------------------------------------------------------------------------------' def test_given_parameters(self): if self.param == None: return # create the checklist.conf that Framework will use # checklist_file_name = os.path.join(self.fwk.sim_root, 'checklist.conf') sim_conf = ConfigObj(self.param.cfgFile_list[0], interpolation='template', file_error=True) # try making the simulation root directory try: os.makedirs(sim_conf['SIM_ROOT']) except OSError, (errno, strerror): if (errno != 17): self.services.exception('Error creating directory %s : %s' , workdir, strerror) checklist_file_name = os.path.join(sim_conf['SIM_ROOT'], 'checklist.conf') checklist_file = open(checklist_file_name, 'w') if self.param.create_runspace_done: checklist_file.write('CREATE_RUNSPACE = DONE\n') else: checklist_file.write('CREATE_RUNSPACE = NOT_DONE\n') if self.param.run_setup_done: checklist_file.write('RUN_SETUP = DONE\n') else: checklist_file.write('RUN_SETUP = NOT_DONE\n') if self.param.run_done: checklist_file.write('RUN = DONE\n') else: checklist_file.write('RUN = NOT_DONE\n') checklist_file.flush() checklist_file.close() call_args = [] call_args.append(fsrc + '/ips.py') if self.param.do_create_runspace: call_args.append('--create-runspace') if self.param.do_run_setup: call_args.append('--run-setup') if self.param.do_run: call_args.append('--run') cfg_files_str = '--simulation=' + self.param.cfgFile_list[0] for file in self.param.cfgFile_list[1:]: cfg_files_str += ',' + file call_args.append(cfg_files_str) if self.param.platform_filename: call_args.append('--platform=' + self.param.platform_filename) call_args.append('--log=' + self.param.log_file) print string.join(call_args, ' ') #test must return true if nothing bad happened, false otherwise # self.assertTrue(self.fwk.run(), 'error in running fwk') self.assertEquals(subprocess.call(call_args), 0, 'error in running IPS') """ # set correct result of CREATE_RUNSPACE parameterization if self.param.do_create_runspace or self.param.create_runspace_done: self.create_runspace_result = 'DONE' else: self.create_runspace_result = 'NOT_DONE' # set correct result of RUN_SETUP parameterization if self.param.do_run_setup and self.create_runspace_result == 'DONE': self.run_setup_result = 'DONE' elif self.param.run_setup_done and self.param.create_runspace_done: self.run_setup_result = 'DONE' elif self.param.run_setup_done and not self.param.do_create_runspace: self.run_setup_result = 'DONE' else: self.run_setup_result = 'NOT_DONE' # set correct result of RUN parameterization if self.param.do_run and self.run_setup_result == 'DONE': self.run_result = 'DONE' elif not self.param.do_run and self.param.run_done: self.run_result = 'NOT_DONE' else: self.run_result = 'NOT_DONE' """ # If you create a runspace, it doesn't matter what was in the # directory before it's now invalidated... if self.param.do_create_runspace: self.param.run_setup_done = False self.param.run_done = False # If you do run setup over a previous run, it invalidates the # run results because the inputs and outputs don't match now... if self.param.do_run_setup: self.param.run_done = False if self.param.do_create_runspace or self.param.create_runspace_done: self.create_runspace_result = 'DONE' else: self.create_runspace_result = 'NOT_DONE' if (self.param.do_run_setup or self.param.run_setup_done) and \ self.create_runspace_result == 'DONE': self.run_setup_result = 'DONE' else: self.run_setup_result = 'NOT_DONE' # (( T or F ) and F ) and T if ((self.param.do_run or self.param.run_done) and \ self.run_setup_result == 'DONE') and \ self.create_runspace_result == 'DONE': self.run_result = 'DONE' else: self.run_result = 'NOT_DONE' # read in the values the Framework wrote out self.conf = ConfigObj(checklist_file_name, interpolation = 'template', file_error = True) self.assertEquals(self.create_runspace_result, self.conf['CREATE_RUNSPACE']) self.assertEquals(self.run_setup_result, self.conf['RUN_SETUP']) self.assertEquals(self.run_result, self.conf['RUN'])
VanshMaheshwari30/DS-Algo
Array/LongestEvenOddSubarray.cpp
<reponame>VanshMaheshwari30/DS-Algo<gh_stars>1-10 #include<iostream> using namespace std; int maxEvenOdd (int arr[], int n) { int res=1, curr=1; for(int i=1; i<n; i++) { if ((arr[i]%2==0 && arr[i-1]%2!=0) || (arr[i]%2!=0 && arr[i-1]%2==0)) { curr++; res = max(res,curr); } else curr=1; } return res; } int main(void) { int n,d; cout << "Enter the size of array: "; cin >> n; int arr[n]; cout << "Enter the elements of array: \n"; for (int i=0; i<n; i++) cin >> arr[i]; cout << "The original array is: \n"; for (int i=0; i<n; i++) cout << arr[i] <<" "; cout<< "\nThe longest even-odd subarray has " << maxEvenOdd(arr,n) << " elements."; }
NostalgicGhoul/gfxtk
libs/gfxtk_core/src/gfxtk/CullMode.hpp
#ifndef GFXTK_CULLMODE_HPP #define GFXTK_CULLMODE_HPP namespace gfxtk { enum class CullMode { None = 0, Front = 1, Back = 2, }; } #endif //GFXTK_CULLMODE_HPP
lvlei14/The-base-importment-of-React
src/components/Modal/Modal.js
import React, { Component, PropTypes } from 'react'; const styles = require('./Modal.scss'); export default class Modal extends Component { static propTypes = { children: PropTypes.oneOfType([ PropTypes.array, PropTypes.object, PropTypes.string, ]), title: PropTypes.string, clickHideModal: PropTypes.func, clickConfirm: PropTypes.func, clickCancel: PropTypes.func, confirmText: PropTypes.string, cancelText: PropTypes.string, hideHideModalBtn: PropTypes.bool, hideModalFooter: PropTypes.bool, } constructor(props) { super(props); this.state = { }; } componentWillReceiveProps() { } render() { const {confirmText, cancelText} = this.props; let confirmTextCon; let cancelTextCon; if (confirmText) { confirmTextCon = confirmText; } else { confirmTextCon = '确定'; } if (cancelText) { cancelTextCon = cancelText; } else { cancelTextCon = '取消'; } return ( <div> <div className={styles.modalFa}> <div className={styles.modal}> <p className={'bodyBgWhite ' + styles.modalBg}></p> <div className={'bodyBgWhiteZindex ' + styles.modalSection}> <header className={'clearfix ' + styles.modalTitle}> <h3>{this.props.title}</h3> <span className={styles.hideHideModalBtn} style={{display: this.props.hideHideModalBtn ? 'none' : 'block'}} onClick={this.props.clickHideModal}></span> </header> <section className={styles.modalSectionSection}>{this.props.children}</section> <footer style={{display: this.props.hideModalFooter ? 'none' : 'block'}} className={styles.modalButton + ' clearfix'}> <button className="left" onClick={this.props.clickCancel}>{cancelTextCon}</button> <button className={'right ' + styles.modalConfirm} onClick={this.props.clickConfirm}>{confirmTextCon}</button> </footer> </div> </div> </div> </div> ); } }
ivanovpv/darksms
psm/src/main/java/ru/ivanovpv/gorets/psm/SettingsActivity.java
<reponame>ivanovpv/darksms package ru.ivanovpv.gorets.psm; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.*; import android.util.Log; import com.actionbarsherlock.app.SherlockPreferenceActivity; import com.actionbarsherlock.view.MenuItem; import ru.ivanovpv.gorets.psm.cipher.*; import ru.ivanovpv.gorets.psm.db.MessageDAO; import ru.ivanovpv.gorets.psm.persistent.Hash; import ru.ivanovpv.gorets.psm.persistent.Message; import ru.ivanovpv.gorets.psm.persistent.Purse; /* * Copyright (c) <NAME> (<EMAIL>) and <NAME> (<EMAIL>) 2012. * $Author: ivanovpv $ * $Rev: 493 $ * $LastChangedDate: 2014-02-02 18:18:32 +0400 (Вс, 02 фев 2014) $ * $URL: https://subversion.assembla.com/svn/ivanovpv/trunk/src/ru/ivanovpv/gorets/psm/SettingsActivity.java $ */ public class SettingsActivity extends SherlockPreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener, DialogInterface.OnCancelListener, DialogInterface.OnDismissListener { private final static String TAG = SettingsActivity.class.getName(); public final static int LOGIN_ENABLED=1; SharedPreferences sharedPreferences; private static boolean acceptChange; private Me me; @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); me=(Me )this.getApplication(); this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); getPreferenceManager().setSharedPreferencesName(Me.PREFERENCES_NAME); addPreferencesFromResource(R.xml.settings); sharedPreferences=getPreferenceScreen().getSharedPreferences(); sharedPreferences.registerOnSharedPreferenceChangeListener(this); Preference aboutAppPref = findPreference("about"); aboutAppPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Dialog dialog=new AboutDialog(SettingsActivity.this); dialog.show(); return false; } }); Preference rateAppPref = findPreference("rate"); if(Me.ENABLE_MARKET) rateAppPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { new RapeMe().launchMarket(SettingsActivity.this); return false; } }); else rateAppPref.setEnabled(false); Preference readEULAPref = findPreference("eula"); readEULAPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Eula.show(SettingsActivity.this); return false; } }); //**************************** //Ask PIN //**************************** CheckBoxPreference askPIN=(CheckBoxPreference )findPreference("askPIN"); final Hash hash=me.getHashDAO().get(); askPIN.setChecked(hash.isEnabled()); askPIN.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if(((Boolean )newValue)) { //password not set yet if(me.psmSettings.passwordSalt().get()==null || me.psmSettings.passwordSalt().get().length()==0) { Dialog dialog=new SetPINDialog(SettingsActivity.this); dialog.setOnCancelListener(SettingsActivity.this); dialog.setOnDismissListener(SettingsActivity.this); dialog.show(); } else { //there's password, so either change it or use old one new AlertDialog.Builder(SettingsActivity.this) .setTitle(SettingsActivity.this.getString(R.string.pinExists)) .setMessage(SettingsActivity.this.getString(R.string.pinChange)) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(R.string.change, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ChangePinDialog dlg=new ChangePinDialog(SettingsActivity.this); dlg.setOnCancelListener(SettingsActivity.this); dlg.setOnDismissListener(SettingsActivity.this); dlg.show(); } }) .setNegativeButton(R.string.useOld, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int whichButton) { Dialog dialog=new CheckPINDialog(SettingsActivity.this, CheckPINDialog.MODE_SET_CHECK); dialog.setOnCancelListener(SettingsActivity.this); dialog.setOnDismissListener(SettingsActivity.this); dialog.show(); } }) .setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int whichButton) { CheckBoxPreference askPIN=(CheckBoxPreference )findPreference("askPIN"); askPIN.setChecked(false); hash.disable(); me.getHashDAO().save(SettingsActivity.this, hash); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialogInterface) { CheckBoxPreference askPIN=(CheckBoxPreference )findPreference("askPIN"); askPIN.setChecked(false); hash.disable(); me.getHashDAO().save(SettingsActivity.this, hash); } }) .show(); } } else { Dialog dialog=new CheckPINDialog(SettingsActivity.this, CheckPINDialog.MODE_CLEAR_CHECK); dialog.setOnCancelListener(SettingsActivity.this); dialog.setOnDismissListener(SettingsActivity.this); dialog.show(); } return true; } }); //**************************** //Comfort PIN //**************************** final CheckBoxPreference comfortPIN=(CheckBoxPreference )findPreference("comfortPIN"); final Purse purse=Me.getMe().getMessagePurseDAO().get(this); comfortPIN.setChecked(purse.isComfortPINEnabled()); comfortPIN.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (newValue instanceof Boolean) { comfortPIN.setChecked((Boolean) newValue); purse.setComfortPINEnabled((Boolean) newValue); Me.getMe().getMessagePurseDAO().save(SettingsActivity.this, purse); } return true; } }); //**************************** //Ringtone //**************************** RingtonePreference smsRingTone = (RingtonePreference) findPreference("smsRingTone"); if(smsRingTone!=null) { Uri ringtoneUri = Uri.parse(me.psmSettings.smsRingTone().get()); if(ringtoneUri==null || ringtoneUri.toString().length()==0) ringtoneUri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); if(ringtoneUri!=null) me.psmSettings.smsRingTone().put(ringtoneUri.toString()); else me.psmSettings.smsRingTone().put(""); //silence } ListPreference protectionPrivacyLevel = (ListPreference) findPreference("protectionPrivacyLevel"); protectionPrivacyLevel.setSummary(protectionPrivacyLevel.getEntry()); ListPreference messagingPrivacyLevel = (ListPreference) findPreference("messagingPrivacyLevel"); /* messagingPrivacyLevel.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Spanned s=Html.fromHtml(SettingsActivity.this.getString(R.string.cryptoWarning)); SpannableString ss=new SpannableString(s); Linkify.addLinks(ss, Linkify.WEB_URLS); final AlertDialog ad=new AlertDialog.Builder(SettingsActivity.this) .setMessage(ss) .setPositiveButton(R.string.ok, null) .setIcon(R.drawable.psm) .create(); ad.show(); ((TextView)ad.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); return true; } });*/ messagingPrivacyLevel.setSummary(messagingPrivacyLevel.getEntry()); { Preference pref; KeyExchange keyExchange; byte[] key; byte[] sKey=Me.getMe().getHashDAO().get().getKey(); pref= findPreference("fingerPrintBasic"); keyExchange=Hash.getDefaultKeyExchange(sKey); key=keyExchange.getPublicKey(); pref.setSummary(new FingerPrint(key, Me.getDefaultKeyExchangeType()).toString()); /* if(me.getMessagingPrivacyLevel() > 0) { pref= findPreference("fingerPrintMedium"); if(pref!=null) { keyExchange = new EllipticCurve256B(sKey); key = keyExchange.getPublicKey(); pref.setSummary(new FingerPrint(key, KeyExchange.KEY_EXCHANGE_ELLIPTIC_CURVE_256B).toString()); } pref= findPreference("fingerPrintHigh"); if(pref!=null) { keyExchange = new EllipticCurve384B(sKey); key = keyExchange.getPublicKey(); pref.setSummary(new FingerPrint(key, KeyExchange.KEY_EXCHANGE_ELLIPTIC_CURVE_384B).toString()); } } else { pref= findPreference("fingerPrintMedium"); if(pref!=null) pref.setSummary(R.string.notApplicable); pref= findPreference("fingerPrintHigh"); if(pref!=null) pref.setSummary(R.string.notApplicable); }*/ } Preference resetAppPref = findPreference("reset"); resetAppPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { final AlertDialog.Builder builder_reset = new AlertDialog.Builder(SettingsActivity.this) .setTitle(R.string.reset) .setMessage(R.string.resetWarning) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { if(me.psmSettings.askPIN().get()) { final CheckPINDialog checkPINDialog=new CheckPINDialog(SettingsActivity.this, CheckPINDialog.MODE_DOESNT_MATTER); checkPINDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { return; } }); checkPINDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if(!checkPINDialog.isCanceled()) new ResetTask().execute(); } }); checkPINDialog.show(); } else { new ResetTask().execute(); } } }).setNegativeButton(R.string.no, null); builder_reset.create().show(); return true; } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("deprecation") @Override protected void onDestroy() { super.onDestroy(); getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } @SuppressWarnings("deprecation") @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if(key.compareTo("protectionPrivacyLevel")==0) { ListPreference privacyLevel = (ListPreference) findPreference("protectionPrivacyLevel"); privacyLevel.setSummary(privacyLevel.getEntry()); } if(key.compareTo("messagingPrivacyLevel")==0) { ListPreference privacyLevel = (ListPreference) findPreference("messagingPrivacyLevel"); //privacyLevel.setValueIndex(0);//always should be zero! privacyLevel.setSummary(privacyLevel.getEntry()); } else if(key.compareTo("smsRingTone")==0) { RingtonePreference smsRingTone = (RingtonePreference) findPreference("smsRingTone"); if(smsRingTone==null) return; Uri ringtoneUri = Uri.parse(me.psmSettings.smsRingTone().get()); Ringtone ringTone = RingtoneManager.getRingtone(this, ringtoneUri); smsRingTone.setSummary(ringTone==null ? "" : ringTone.getTitle(this)); } } @Override @SuppressWarnings("deprecation") public void onCancel(DialogInterface dialog) { CheckBoxPreference askPIN=(CheckBoxPreference )findPreference("askPIN"); Hash hash=me.getHashDAO().get(); if(dialog instanceof SetPINDialog) { hash.disable(); me.getHashDAO().save(this, hash); askPIN.setChecked(false); } else if(dialog instanceof CheckPINDialog) { CheckPINDialog checkPINDialog=(CheckPINDialog )dialog; if(checkPINDialog.getMode()==CheckPINDialog.MODE_CLEAR_CHECK) { askPIN.setChecked(true); hash.enable(); } else { askPIN.setChecked(false); hash.disable(); } me.getHashDAO().save(this, hash); } else if(dialog instanceof ChangePinDialog) { askPIN.setChecked(false); hash.disable(); me.getHashDAO().save(this, hash); } SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putBoolean("askPIN", askPIN.isChecked()); edit.commit(); } @Override @SuppressWarnings("deprecation") public void onDismiss(DialogInterface dialog) { CheckBoxPreference askPIN=(CheckBoxPreference )findPreference("askPIN"); Hash hash=me.getHashDAO().get(); if(dialog instanceof CheckPINDialog) { CheckPINDialog checkPINDialog=(CheckPINDialog )dialog; if(checkPINDialog.isCanceled()) return; if(checkPINDialog.getMode()==CheckPINDialog.MODE_SET_CHECK) { askPIN.setChecked(true); hash.enable(); } else { askPIN.setChecked(false); hash.disable(); } me.getHashDAO().save(this, hash); } else if(dialog instanceof ChangePinDialog) { if(((ChangePinDialog )dialog).isCanceled()) return; askPIN.setChecked(true); hash.enable(); me.getHashDAO().save(this, hash); } else if(dialog instanceof SetPINDialog) { SetPINDialog setPINDialog=(SetPINDialog )dialog; if(setPINDialog.isCanceled()) return; askPIN.setChecked(true); hash.enable(); me.getHashDAO().save(this, hash); } SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putBoolean("askPIN", askPIN.isChecked()); edit.commit(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } private class ResetTask extends AsyncTask<Void, Integer, Boolean> { Context context; ProgressDialog resetDialog; protected ResetTask() { super(); this.context=SettingsActivity.this; resetDialog = new ProgressDialog(SettingsActivity.this); resetDialog.setOwnerActivity(SettingsActivity.this); resetDialog.setCancelable(false); resetDialog.setCanceledOnTouchOutside(false); resetDialog.setProgress(0); resetDialog.setTitle(R.string.reset); resetDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); int count=Me.getMe().getMessageDAO().countMessages(context)+2; resetDialog.setMax(count); } @Override protected void onPreExecute() { super.onPreExecute(); resetDialog.show(); } @Override protected Boolean doInBackground(Void... arg) { boolean allReset=true; int progress=0; Cursor cursor=null; Message message; MessageDAO messageDAO=Me.getMe().getMessageDAO(); try { cursor=messageDAO.getMessagesCursor(context); while(cursor!=null && cursor.moveToNext()) { message=messageDAO.getSmsMessage(context, cursor); if(message.isProtected()) { if(!message.unprotectSilent(context)) allReset=false; } if(message.isCiphered()) { if(!message.decipherSilent(context)) allReset=false; } if(Me.DEBUG) Log.i(TAG, "Reset progress publish="+progress); this.publishProgress(++progress); } SharedPreferences.Editor editor=SettingsActivity.this.sharedPreferences.edit(); editor.clear(); editor.commit(); this.publishProgress(++progress); Me.getMe().getDbHelper().reset(); this.publishProgress(++progress); } catch(Exception ex) { Log.w(TAG, "Error while resetting...", ex); } finally { if(cursor!=null) cursor.close(); } return allReset; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); if(Me.DEBUG) Log.i(TAG, "Reset progress update="+values[0]); resetDialog.setProgress(values[0]); } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if(resetDialog!=null && resetDialog.isShowing()) resetDialog.dismiss(); if(!result) { new AlertDialog.Builder(context) .setTitle(R.string.reset) .setMessage(R.string.resetError) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { Me.getMe().exit(); }}).show(); } else Me.getMe().exit(); } } }
solinatx/react-stockcharts
lib/annotation/SvgPathAnnotation.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require("react"); var _react2 = _interopRequireDefault(_react); var _propTypes = require("prop-types"); var _propTypes2 = _interopRequireDefault(_propTypes); var _utils = require("../utils"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var SvgPathAnnotation = function (_Component) { _inherits(SvgPathAnnotation, _Component); function SvgPathAnnotation(props) { _classCallCheck(this, SvgPathAnnotation); var _this = _possibleConstructorReturn(this, (SvgPathAnnotation.__proto__ || Object.getPrototypeOf(SvgPathAnnotation)).call(this, props)); _this.handleClick = _this.handleClick.bind(_this); return _this; } _createClass(SvgPathAnnotation, [{ key: "handleClick", value: function handleClick(e) { var onClick = this.props.onClick; if (onClick) { var _props = this.props, xScale = _props.xScale, yScale = _props.yScale, datum = _props.datum; onClick({ xScale: xScale, yScale: yScale, datum: datum }, e); } } }, { key: "render", value: function render() { var _props2 = this.props, className = _props2.className, stroke = _props2.stroke, opacity = _props2.opacity; var _props3 = this.props, xAccessor = _props3.xAccessor, xScale = _props3.xScale, yScale = _props3.yScale, path = _props3.path; var _helper = helper(this.props, xAccessor, xScale, yScale), x = _helper.x, y = _helper.y, fill = _helper.fill, tooltip = _helper.tooltip; return _react2.default.createElement( "g", { className: className, onClick: this.handleClick }, _react2.default.createElement( "title", null, tooltip ), _react2.default.createElement("path", { d: path({ x: x, y: y }), stroke: stroke, fill: fill, opacity: opacity }) ); } }]); return SvgPathAnnotation; }(_react.Component); function helper(props, xAccessor, xScale, yScale) { var x = props.x, y = props.y, datum = props.datum, fill = props.fill, tooltip = props.tooltip, plotData = props.plotData; var xFunc = (0, _utils.functor)(x); var yFunc = (0, _utils.functor)(y); var _ref = [xFunc({ xScale: xScale, xAccessor: xAccessor, datum: datum, plotData: plotData }), yFunc({ yScale: yScale, datum: datum, plotData: plotData })], xPos = _ref[0], yPos = _ref[1]; return { x: xPos, y: yPos, fill: (0, _utils.functor)(fill)(datum), tooltip: (0, _utils.functor)(tooltip)(datum) }; } SvgPathAnnotation.propTypes = { className: _propTypes2.default.string, path: _propTypes2.default.func.isRequired, onClick: _propTypes2.default.func, xAccessor: _propTypes2.default.func, xScale: _propTypes2.default.func, yScale: _propTypes2.default.func, datum: _propTypes2.default.object, stroke: _propTypes2.default.string, fill: _propTypes2.default.string, opacity: _propTypes2.default.number }; SvgPathAnnotation.defaultProps = { className: "react-stockcharts-svgpathannotation", opacity: 1, x: function x(_ref2) { var xScale = _ref2.xScale, xAccessor = _ref2.xAccessor, datum = _ref2.datum; return xScale(xAccessor(datum)); } }; exports.default = SvgPathAnnotation; //# sourceMappingURL=SvgPathAnnotation.js.map
feiaxyt/CGACD
models/siamese/siamese.py
<gh_stars>1-10 # Copyright (c) SenseTime. All Rights Reserved. import torch import torch.nn as nn import torch.nn.functional as F def xcorr_depthwise(x, kernel): """depthwise cross correlation """ batch = kernel.size(0) channel = kernel.size(1) x = x.view(1, batch*channel, x.size(2), x.size(3)) kernel = kernel.view(batch*channel, 1, kernel.size(2), kernel.size(3)) out = F.conv2d(x, kernel, groups=batch*channel) out = out.view(batch, channel, out.size(2), out.size(3)) return out def xcorr_up(x, kernel): batch_sz = kernel.shape[0] kernel = kernel.reshape(-1, x.shape[1], kernel.shape[2], kernel.shape[3]) out = F.conv2d( x.reshape(1, -1, x.shape[2], x.shape[3]), kernel, groups=batch_sz) out = out.reshape(batch_sz, -1, out.shape[2], out.shape[3]) return out class UPXCorr(nn.Module): def __init__(self, out_channels, adjust, feat_in=256, feat_out=256): super(UPXCorr, self).__init__() self.conv_kernel = nn.Conv2d(feat_in, feat_out * out_channels, 3) self.conv_search = nn.Conv2d(feat_in, feat_out, 3) if adjust: self.adjust = nn.Conv2d(out_channels, out_channels, 1) else: self.adjust = lambda x: x def forward(self, z_f, x_f): kernel = self.conv_kernel(z_f) search = self.conv_search(x_f) out = xcorr_up(search, kernel) return self.adjust(out) class DepthwiseXCorr(nn.Module): def __init__(self, feat_in=256, feat_out=256, out_channels=1, kernel_size=3): super(DepthwiseXCorr, self).__init__() self.conv_kernel = nn.Sequential( nn.Conv2d(feat_in, feat_out, kernel_size=kernel_size, bias=False), nn.BatchNorm2d(feat_out), nn.ReLU(inplace=True), ) self.conv_search = nn.Sequential( nn.Conv2d(feat_in, feat_out, kernel_size=kernel_size, bias=False), nn.BatchNorm2d(feat_out), nn.ReLU(inplace=True), ) self.head = nn.Sequential( nn.Conv2d(feat_out, feat_out, kernel_size=1, bias=False), nn.BatchNorm2d(feat_out), nn.ReLU(inplace=True), nn.Conv2d(feat_out, out_channels, kernel_size=1) ) self.kernel = None def forward(self, kernel, search): kernel = self.conv_kernel(kernel) search = self.conv_search(search) feature = xcorr_depthwise(search, kernel) out = self.head(feature) return out class Siamese(nn.Module): def __init__(self): super(Siamese, self).__init__() def forward(self, z_f, x_f): raise NotImplementedError def normal_init(m, mean, stddev): m.weight.data.normal_(mean, stddev) m.bias.data.zero_() class UPChannelSiamese(Siamese): def __init__(self, feat_in=256, feature_out=256): super(UPChannelSiamese, self).__init__() self.cls = UPXCorr(1, False, feat_in, feature_out) self.loc = UPXCorr(4, True, feat_in, feature_out) for m in self.modules(): if isinstance(m, nn.Conv2d): normal_init(m, 0, 0.001) def forward(self, z_f, x_f): loc = self.loc(z_f[:,:,4:-4,4:-4], x_f) cls = self.cls(z_f[:,:,4:-4,4:-4], x_f) return loc, cls class DepthwiseSiamese(Siamese): def __init__(self, feat_in=256, feature_out=256): super(DepthwiseSiamese, self).__init__() self.cls = DepthwiseXCorr(feat_in, feature_out, 1) self.loc = DepthwiseXCorr(feat_in, feature_out, 4) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_( m.weight.data, mode='fan_out', nonlinearity='relu') elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1.0) m.bias.data.zero_() def forward(self, z_f, x_f): cls = self.cls(z_f, x_f) loc = self.loc(z_f, x_f) return loc, cls
jnthn/intellij-community
python/testData/inspections/PyArgumentListInspection/multipleInheritedConstructorsMRO.py
class A(object): pass class B(object): def __init__(self, *args): pass class C(B): pass class D(A, C): pass D(42)
kids-first/kf-api-dataservice
tests/test_errors.py
<reponame>kids-first/kf-api-dataservice<gh_stars>1-10 import copy import json import re import pytest from tests.conftest import (ENDPOINT_ENTITY_MAP, ENTITY_PARAMS, _add_foreign_keys) CONSTRAINT_ERR_RE = re.compile( 'could not create (\w+)\. one with \(.+\) = \(.+\) already exists\.' ) class TestErrors: """ Test general error handling """ @pytest.mark.parametrize('endpoint', ['/diagnoses', '/outcomes' ]) @pytest.mark.parametrize('kf_id', [ '', 'AABB1122', 'blah', 'blah blah' ]) def test_fk_not_exists(self, client, endpoint, kf_id): """ Test integrity errors where the foreign key does not exist """ # Create participant kwargs = { 'participant_id': kf_id } # Send post request response = client.post(endpoint, data=json.dumps(kwargs), headers={'Content-Type': 'application/json'}) assert response.status_code == 400 # Check response body response = json.loads(response.data.decode("utf-8")) # Check error message if len(kf_id) <= 11: message = '"{}" does not exist'.format(kwargs['participant_id']) assert message in response['_status']['message'] else: message = 'Longer than maximum length 11' assert message in response['_status']['message'] @pytest.mark.parametrize('endpoint', [ '/sequencing-centers', '/biospecimen-genomic-files', '/biospecimen-diagnoses', '/family-relationships', '/task-genomic-files', '/read-group-genomic-files' ]) def test_uniqueness_constraints(self, client, entities, endpoint): """ Test integrity error from uniqueness violations """ # _add_foreign_keys is destructive to ENTITY_PARAMS['fields'][endpoint] # state used by other tests, so deepcopy it here to prevent side # effects. inputs = ENTITY_PARAMS['fields'][endpoint].copy() model_cls = ENDPOINT_ENTITY_MAP.get(endpoint) entity = entities.get(model_cls)[0] _add_foreign_keys(inputs, entity) response = client.post( endpoint, data=json.dumps(inputs), headers={'Content-Type': 'application/json'} ) assert response.status_code == 400 response = json.loads(response.data.decode("utf-8")) assert CONSTRAINT_ERR_RE.match(response['_status']['message'])
GuillermoMajano/guts-emacs
.cache/lsp/npm/yaml-language-server/lib/node_modules/yaml-language-server/out/server/src/languageserver/telemetry.js
<gh_stars>0 "use strict"; /*--------------------------------------------------------------------------------------------- * Copyright (c) Red Hat, Inc. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ Object.defineProperty(exports, "__esModule", { value: true }); exports.Telemetry = void 0; class Telemetry { constructor(connection) { this.connection = connection; } send(event) { this.connection.telemetry.logEvent(event); } sendError(name, properties) { this.send({ name, type: 'track', properties: properties }); } sendTrack(name, properties) { this.send({ name, type: 'track', properties: properties }); } } exports.Telemetry = Telemetry; //# sourceMappingURL=telemetry.js.map
Nintinugga/SportsManager
app/src/main/java/com/comp/ninti/sportsmanager/DatabaseActivity.java
package com.comp.ninti.sportsmanager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageButton; import com.comp.ninti.general.NavigationUtil; public class DatabaseActivity extends AppCompatActivity { private ImageButton btnExport, btnImport; private BottomNavigationView navigation; private int menuNr = 4; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { return NavigationUtil.switchNavigation(item, DatabaseActivity.this); } }; @Override public boolean onOptionsItemSelected(MenuItem item) { if(NavigationUtil.switchNavigation(item, DatabaseActivity.this)) return true; return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.navigation, menu); return super.onCreateOptionsMenu(menu); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //setup navigation navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); navigation.getMenu().getItem(menuNr).setChecked(true); } @Override protected void onResume() { super.onResume(); navigation.getMenu().getItem(menuNr).setChecked(true); } }
cody110/flyertea
flyerteaCafes/src/main/java/com/ideal/flyerteacafes/ui/popupwindow/ForumPopupWindow.java
package com.ideal.flyerteacafes.ui.popupwindow; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.PopupWindow; import com.ideal.flyerteacafes.R; import com.ideal.flyerteacafes.model.entity.CommunityBean; import com.ideal.flyerteacafes.model.entity.CommunitySubBean; import com.ideal.flyerteacafes.model.entity.CommunitySubTypeBean; import com.ideal.flyerteacafes.ui.activity.presenter.WriteThreadPresenter; import com.ideal.flyerteacafes.ui.wheelview.OnWheelChangedListener; import com.ideal.flyerteacafes.ui.wheelview.WheelView; import com.ideal.flyerteacafes.ui.wheelview.adapters.ForumWheelOneAdapter; import com.ideal.flyerteacafes.ui.wheelview.adapters.ForumWheelThreeAdapter; import com.ideal.flyerteacafes.ui.wheelview.adapters.ForumWheelTwoAdapter; import org.xutils.view.annotation.Event; import org.xutils.view.annotation.ViewInject; import org.xutils.x; import java.util.List; /** * Created by fly on 2016/11/18. */ public class ForumPopupWindow extends PopupWindow implements OnWheelChangedListener { @ViewInject(R.id.pop_forum_wheel_layout) LinearLayout pop_forum_wheel_layout; @ViewInject(R.id.pop_forum_wheel_one_level) WheelView pop_forum_wheel_one_level; @ViewInject(R.id.pop_forum_wheel_two_level) WheelView pop_forum_wheel_two_level; @ViewInject(R.id.pop_forum_wheel_three_level) WheelView pop_forum_wheel_three_level; private ForumWheelOneAdapter oneAdapter; private ForumWheelTwoAdapter twoAdapter; private ForumWheelThreeAdapter threeAdapter; private int oneLevelSelectIndex = 0, twoLevelSelectIndex = 0, threeLevelSelectIndex = 0; private List<CommunityBean> communityBeanList; private List<CommunitySubTypeBean> communitySubTypeBeanList; private String fid1, fid2, fid3, name1, name2, name3; /** * 3种情况,只需要3级,和需要全部,问答进入,3级默认问答 */ private int IS_NEED_ONCE_THREE = 2, IS_NEED_ALL = 1, IS_WENDA = 3; private int type = IS_NEED_ALL; private Context context; private Handler handler; public ForumPopupWindow(final Context context, final Handler handler) { this.context = context; this.handler = handler; LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View mMenuView = inflater.inflate(R.layout.popupwindow_froum, null); x.view().inject(this, mMenuView); pop_forum_wheel_one_level.addChangingListener(this); pop_forum_wheel_two_level.addChangingListener(this); pop_forum_wheel_three_level.addChangingListener(this); // 设置SelectPicPopupWindow的View this.setContentView(mMenuView); // 设置SelectPicPopupWindow弹出窗体的宽 this.setWidth(ViewGroup.LayoutParams.FILL_PARENT); // 设置SelectPicPopupWindow弹出窗体的高 this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); // 设置SelectPicPopupWindow弹出窗体可点击 this.setFocusable(true); // 设置SelectPicPopupWindow弹出窗体动画效果 this.setAnimationStyle(R.style.AnimBottom); // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw = new ColorDrawable(0xb0000000); // 设置SelectPicPopupWindow弹出窗体的背景 this.setBackgroundDrawable(dw); // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框 mMenuView.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { int height = mMenuView.findViewById(R.id.pop_forum_bottom_layout).getTop(); int y = (int) event.getY(); if (event.getAction() == MotionEvent.ACTION_UP) { if (y < height) { dismiss(); } } return true; } }); } /** * 根据数据初始化页面 */ public void chooseAllFroum(List<CommunityBean> communityBeanList) { this.communityBeanList = communityBeanList; setOneLevelAdapter(); getOneSelectIndex(fid1); setTwoLevelAdapter(); getTwoSelectIndex(fid2); setThreeLevelAdapter(); } /** * 问答入口 */ public void chooseWenda(List<CommunityBean> communityBeanList) { this.communityBeanList = communityBeanList; type = IS_WENDA; pop_forum_wheel_three_level.setVisibility(View.GONE); setOneLevelAdapter(); getOneSelectIndex(fid1); setTwoLevelAdapter(); } /** * 只显示3级分类,的初始化 */ public void chooseThreeFroum(List<CommunitySubTypeBean> communitySubTypeBeanList) { this.communitySubTypeBeanList = communitySubTypeBeanList; type = IS_NEED_ONCE_THREE; pop_forum_wheel_one_level.setVisibility(View.GONE); pop_forum_wheel_two_level.setVisibility(View.GONE); setThreeLevelAdapter(communitySubTypeBeanList); } private int getOneSelectIndex(String fid) { for (int i = 0; i < communityBeanList.size(); i++) { if (TextUtils.equals(communityBeanList.get(i).getFid(), fid)) return oneLevelSelectIndex = i; } return oneLevelSelectIndex; } private int getTwoSelectIndex(String fid) { List<CommunitySubBean> communitySubBeanList = communityBeanList.get(oneLevelSelectIndex).getSubforums(); for (int i = 0; i < communitySubBeanList.size(); i++) { if (TextUtils.equals(communitySubBeanList.get(i).getFid(), fid)) return oneLevelSelectIndex = i; } return oneLevelSelectIndex; } private void setOneLevelAdapter() { oneAdapter = new ForumWheelOneAdapter(context, communityBeanList); pop_forum_wheel_one_level.setViewAdapter(oneAdapter); } private void setTwoLevelAdapter() { twoLevelSelectIndex = 0; List<CommunitySubBean> communitySubBeanList = communityBeanList.get(oneLevelSelectIndex).getSubforums(); twoAdapter = new ForumWheelTwoAdapter(context, communitySubBeanList); pop_forum_wheel_two_level.setViewAdapter(twoAdapter); pop_forum_wheel_two_level.setCurrentItem(twoLevelSelectIndex); } private void setThreeLevelAdapter() { threeLevelSelectIndex = 0; List<CommunitySubTypeBean> communitySubTypeBeanList = communityBeanList.get(oneLevelSelectIndex).getSubforums().get(twoLevelSelectIndex).getSubforumList(); if (communitySubTypeBeanList != null) { threeAdapter = new ForumWheelThreeAdapter(context, communitySubTypeBeanList); pop_forum_wheel_three_level.setViewAdapter(threeAdapter); pop_forum_wheel_three_level.setCurrentItem(threeLevelSelectIndex); } } private void setThreeLevelAdapter(List<CommunitySubTypeBean> communitySubTypeBeanList) { if (communitySubTypeBeanList != null) { threeAdapter = new ForumWheelThreeAdapter(context, communitySubTypeBeanList); pop_forum_wheel_three_level.setViewAdapter(threeAdapter); pop_forum_wheel_three_level.setCurrentItem(threeLevelSelectIndex); } } @Event({R.id.toolbar_left, R.id.toolbar_right}) private void click(View v) { switch (v.getId()) { case R.id.toolbar_left: dismiss(); break; case R.id.toolbar_right: btnOk(); break; } } @Override public void onChanged(WheelView wheel, int oldValue, int newValue) { if (wheel == pop_forum_wheel_one_level) { oneLevelSelectIndex = newValue; setTwoLevelAdapter(); if (pop_forum_wheel_three_level.getVisibility() != View.GONE) { setThreeLevelAdapter(); } } else if (wheel == pop_forum_wheel_two_level) { twoLevelSelectIndex = newValue; setThreeLevelAdapter(); } else { threeLevelSelectIndex = newValue; } } /** * 点击完成 * 返回选中数据 */ private void btnOk() { if (type == IS_NEED_ONCE_THREE) { CommunitySubTypeBean bean3 = communitySubTypeBeanList.get(threeLevelSelectIndex); fid3 = bean3.getFid(); name3 = bean3.getName(); } else if (type == IS_WENDA) { CommunityBean bean1 = communityBeanList.get(oneLevelSelectIndex); fid1 = bean1.getFid(); name1 = bean1.getName(); CommunitySubBean bean2 = communityBeanList.get(oneLevelSelectIndex).getSubforums().get(twoLevelSelectIndex); fid2 = bean2.getFid(); name2 = bean2.getName(); List<CommunitySubTypeBean> communitySubTypeBeanList = communityBeanList.get(oneLevelSelectIndex).getSubforums().get(twoLevelSelectIndex).getSubforumList(); if (communitySubTypeBeanList != null && communitySubTypeBeanList.size() > 0) { for (CommunitySubTypeBean typeBean : communitySubTypeBeanList) { if (TextUtils.equals(typeBean.getName(), "求助问答")) { fid3 = typeBean.getFid(); name3 = typeBean.getName(); } } } } else { CommunityBean bean1 = communityBeanList.get(oneLevelSelectIndex); fid1 = bean1.getFid(); name1 = bean1.getName(); CommunitySubBean bean2 = communityBeanList.get(oneLevelSelectIndex).getSubforums().get(twoLevelSelectIndex); fid2 = bean2.getFid(); name2 = bean2.getName(); List<CommunitySubTypeBean> communitySubTypeBeanList = communityBeanList.get(oneLevelSelectIndex).getSubforums().get(twoLevelSelectIndex).getSubforumList(); if (communitySubTypeBeanList != null && communitySubTypeBeanList.size() > 0) { CommunitySubTypeBean bean3 = communitySubTypeBeanList.get(threeLevelSelectIndex); fid3 = bean3.getFid(); name3 = bean3.getName(); }else{ fid3=""; name3=""; } } Message msg = Message.obtain(); Bundle bundle = new Bundle(); msg.what = WriteThreadPresenter.HANDLER_WHAT_FORUM; msg.setData(bundle); bundle.putString(WriteThreadPresenter.BUNDLE_FID_1, fid1); bundle.putString(WriteThreadPresenter.BUNDLE_FID_2, fid2); bundle.putString(WriteThreadPresenter.BUNDLE_FID_3, fid3); bundle.putString(WriteThreadPresenter.BUNDLE_NAME_1, name1); bundle.putString(WriteThreadPresenter.BUNDLE_NAME_2, name2); bundle.putString(WriteThreadPresenter.BUNDLE_NAME_3, name3); handler.sendMessage(msg); dismiss(); } }
angriestalien/ghidra
Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/support/DepthFirstIterator.java
<reponame>angriestalien/ghidra<filename>Ghidra/Framework/Docking/src/main/java/docking/widgets/tree/support/DepthFirstIterator.java /* ### * IP: GHIDRA * REVIEWED: YES * * 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 docking.widgets.tree.support; import java.util.ConcurrentModificationException; import java.util.Iterator; import docking.widgets.tree.GTree; import docking.widgets.tree.GTreeNode; public class DepthFirstIterator implements Iterator<GTreeNode> { private GTreeNode root; private GTreeNode next; private GTreeNode lastNode; private final GTree tree; private final long mod; public DepthFirstIterator(GTree tree, GTreeNode node) { this.tree = tree; this.root = node; this.next = node; this.mod = tree.getModificationID(); } public boolean hasNext() { return next != null; } public GTreeNode next() { checkForConcurrentModification(); lastNode = next; next = findNext(next); return lastNode; } private void checkForConcurrentModification() { if (tree.getModificationID() != mod) { throw new ConcurrentModificationException(); } } public void remove() { checkForConcurrentModification(); GTreeNode parent = lastNode.getParent(); if (parent == null) { throw new IllegalArgumentException("Can't delete root node!"); } parent.removeNode(lastNode); } private GTreeNode findNext(GTreeNode node) { if (node.getChildCount() > 0) { return node.getChild(0); } while(node != root) { GTreeNode parent = node.getParent(); int nextIndexInParent = node.getIndexInParent()+1; if (nextIndexInParent < parent.getChildCount()) { return parent.getChild(nextIndexInParent); } node = parent; } return null; } }
naeramarth7/joynr
java/backend-services/domain-access-controller/src/main/java/io/joynr/accesscontrol/global/GlobalDomainRoleControllerProviderImpl.java
/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.joynr.accesscontrol.global; import io.joynr.accesscontrol.DomainAccessControlStore; import io.joynr.provider.Promise; import joynr.infrastructure.GlobalDomainRoleControllerAbstractProvider; import joynr.infrastructure.DacTypes.ChangeType; import joynr.infrastructure.DacTypes.DomainRoleEntry; import joynr.infrastructure.DacTypes.Role; import com.google.inject.Inject; import com.google.inject.Singleton; /** * Manages the Role Control Lists for all providers. */ @Singleton public class GlobalDomainRoleControllerProviderImpl extends GlobalDomainRoleControllerAbstractProvider { private final DomainAccessControlStore domainAccessStore; @Inject public GlobalDomainRoleControllerProviderImpl(DomainAccessControlStore domainAccessStore) { this.domainAccessStore = domainAccessStore; } @Override public Promise<GetDomainRolesDeferred> getDomainRoles(String uid) { GetDomainRolesDeferred deferred = new GetDomainRolesDeferred(); deferred.resolve(domainAccessStore.getDomainRoles(uid).toArray(new DomainRoleEntry[0])); return new Promise<GetDomainRolesDeferred>(deferred); } @Override public Promise<UpdateDomainRoleDeferred> updateDomainRole(DomainRoleEntry updatedEntry) { UpdateDomainRoleDeferred deferred = new UpdateDomainRoleDeferred(); boolean updateSuccess = domainAccessStore.updateDomainRole(updatedEntry); if (updateSuccess) { fireDomainRoleEntryChanged(ChangeType.UPDATE, updatedEntry); } deferred.resolve(updateSuccess); return new Promise<UpdateDomainRoleDeferred>(deferred); } @Override public Promise<RemoveDomainRoleDeferred> removeDomainRole(String uid, Role role) { RemoveDomainRoleDeferred deferred = new RemoveDomainRoleDeferred(); boolean removeSuccess = domainAccessStore.removeDomainRole(uid, role); if (removeSuccess) { // To notify DRE removal only primary keys (user ID and role) must // be set. All other fields are undefined. DomainRoleEntry removedEntry = new DomainRoleEntry(uid, null, role); fireDomainRoleEntryChanged(ChangeType.REMOVE, removedEntry); } deferred.resolve(removeSuccess); return new Promise<RemoveDomainRoleDeferred>(deferred); } }
project-g7/covidAssist-webApp
frontend/src/components/Admin/pages/Dashboard.js
import React, { useEffect, useState } from "react"; import "../../../styles/AdminDashboard.css"; import DashboardCard1 from "../SubComponents/Dashboard/DashboardCard1"; import DashboardCard2 from "../SubComponents/Dashboard/DashboardCard2"; import DashboardCard3 from "../SubComponents/Dashboard/DashboardCard3"; import DashboardCard4 from "../SubComponents/Dashboard/DashboardCard4"; import LineGraph from "../SubComponents/Dashboard/LineGraph"; import BarChart from "../SubComponents/Dashboard/BarChart"; import PieChart from "../SubComponents/Dashboard/PieChart"; import axios from "axios"; import {url} from "../../config" const Dashboard = () => { const [data,setData] = useState([]); const [visible,setVisible] = useState(false); // var [count,setCount] = useState(0); useEffect(() => { getCenterData(); }, []); const getCenterData = () => { axios .get(`${url.BASE_URL}/getcenterdistrict`) .then((res) => { console.log(res.data); // setData(res.data); // setCenters(res.data[0].centerCount); let arr = []; for(let i=0;i<res.data.length;i++){ arr.push({ activity: res.data[i].activity, value: res.data[i].value, color: "#2A78E4" }) } console.log(arr); setData(arr); setVisible(true); }) .catch((err) => { console.log(err); }); }; return ( <div className="container"> <div className="row d-body"> <DashboardCard4 /> <DashboardCard1 /> <DashboardCard2 /> <DashboardCard3 /> </div> <div className="container tab-screen"> {/* <LineGraph /> */} {visible && <BarChart data={data}/>} {/* <BarChart data={data} /> */} <PieChart/> </div> </div> ); }; export default Dashboard;
ArpiJakab/reactivesearch
packages/native/src/components/shared/TouchableItem.js
import React, { Component } from 'react'; import { TouchableNativeFeedback, TouchableOpacity, Platform, View, } from 'react-native'; import types from '@appbaseio/reactivecore/lib/utils/types'; const LOLLIPOP = 21; class TouchableItem extends Component { handlePress = () => { global.requestAnimationFrame(this.props.onPress); }; render() { const { style, pressOpacity, pressColor, ...rest } = this.props; if (Platform.OS === 'android' && Platform.Version >= LOLLIPOP) { return ( <TouchableNativeFeedback onPress={this.handlePress} background={TouchableNativeFeedback.Ripple(pressColor, false)} > <View style={style}>{React.Children.only(this.props.children)}</View> </TouchableNativeFeedback> ); } return ( <TouchableOpacity {...rest} onPress={this.handlePress} style={style} activeOpacity={pressOpacity} > {this.props.children} </TouchableOpacity> ); } } TouchableItem.propTypes = { onPress: types.func, style: types.style, pressOpacity: types.number, pressColor: types.string, children: types.children, }; TouchableItem.defaultProps = { pressColor: 'rgba(0, 0, 0, .2)', }; export default TouchableItem;
deffence1776/my-ddd-sample
src/main/java/example/domain/values/user/TheaterUsername.java
package example.domain.values.user; public class TheaterUsername { String value; public TheaterUsername(String value) { this.value = value; } @Override public String toString() { return value; } public boolean isEquals(TheaterUsername user) { return user.value.equals(value); } }
terratenney/aws-tools
EC2-VPC/autostop_ec2_lambda/autostop-ec2.py
#!/usr/bin/env python import argparse import boto3 import logging # Update the root logger to get messages at DEBUG and above logging.getLogger().setLevel(logging.DEBUG) logging.getLogger("botocore").setLevel(logging.CRITICAL) logging.getLogger("boto3").setLevel(logging.CRITICAL) logging.getLogger("urllib3").setLevel(logging.CRITICAL) # App defaults DEFAULTS = { "ec2_regions": ["ap-southeast-2"], "autostop_tag_key": "AutoStop" } class StopAllEC2(object): def __init__(self, profile_name=None): self._loaded = False self.profile_name = profile_name self.ec2_regions = list() self.autostop_tag_key = DEFAULTS["autostop_tag_key"] def _load_config(self): if self._loaded: return parser = argparse.ArgumentParser(description="Create backups for EC2 instances with Tag [Service]") parser.add_argument("--regions", metavar="region", nargs="*", help="EC2 Region(s) to process for snapshots", default=DEFAULTS["ec2_regions"]) settings = parser.parse_args() for region in settings.regions: self.ec2_regions.append(region) self._loaded = True def configure_from_lambda_event(self, event_details): for setting in DEFAULTS.keys(): if setting in event_details: self.__setattr__(setting, event_details[setting]) else: self.__setattr__(setting, DEFAULTS[setting]) self._loaded = True def start_process(self): self._load_config() for region in self.ec2_regions: self.stop_all_vms(region) def stop_all_vms(self, region): """ Stopping all running VMs (with a tag AutoStop=True) in a region of all aws accounts defined in profiles """ try: ec2_client = self.ec2_resource(region=region, profile_name=self.profile_name) # find all ec2 instances which are tagged as "vm" ret = ec2_client.instances.filter( Filters=[ {"Name": "tag:Service", "Values": ["vm"]}, {"Name": "tag:{}".format(self.autostop_tag_key), "Values": ["True"]} ] ).stop() for r in ret: if "StoppingInstances" in r.keys(): checked_instances = r["StoppingInstances"] for i in checked_instances: if i["PreviousState"]["Name"] in ["pending", "running"] \ and i["CurrentState"]["Name"] in ["stopped", "stopping"]: print("{} has been stopped".format(i["InstanceId"])) elif i["PreviousState"]["Name"] in ["pending", "running"]: print("{} has been stopped and current status is {}".format( i["InstanceId"], i["CurrentState"]["Name"])) except Exception as e: print("Error: Failed to stop all VM EC2 instances") print(e) @staticmethod def ec2_resource(region, profile_name=None): """ Return a EC2 client """ if profile_name is None: ec2 = boto3.resource("ec2", region_name=region) else: session = boto3.session.Session(profile_name=profile_name) ec2 = session.resource("ec2", region) return ec2 def lambda_handler(event, context): """ Entry point for triggering from a AWS Lambda job """ helper = StopAllEC2() helper.configure_from_lambda_event(event) helper.start_process() if __name__ == "__main__": """ Entry point for running from command line """ # TODO change profile_name helper = StopAllEC2(profile_name="default") helper.start_process()
MikaelSmith/troubleshoot
pkg/collect/mysql.go
<filename>pkg/collect/mysql.go package collect import ( "database/sql" "encoding/json" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/pkg/errors" troubleshootv1beta1 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta1" ) func Mysql(ctx *Context, databaseCollector *troubleshootv1beta1.Database) (map[string][]byte, error) { databaseConnection := DatabaseConnection{} db, err := sql.Open("mysql", databaseCollector.URI) if err != nil { databaseConnection.Error = err.Error() } else { query := `select version()` row := db.QueryRow(query) version := "" if err := row.Scan(&version); err != nil { databaseConnection.Error = err.Error() } else { databaseConnection.IsConnected = true databaseConnection.Version = version } } b, err := json.Marshal(databaseConnection) if err != nil { return nil, errors.Wrap(err, "failed to marshal database connection") } collectorName := databaseCollector.CollectorName if collectorName == "" { collectorName = "mysql" } mysqlOutput := map[string][]byte{ fmt.Sprintf("mysql/%s.json", collectorName): b, } return mysqlOutput, nil }
qiuzichi/SingleMadBrain
app/src/main/java/com/unipad/utils/MD5Utils.java
package com.unipad.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * md5加密解码 * * @author Administrator三 * */ public class MD5Utils { /** * 加密成为md5串,方式二16位加密方式 * * @param s * @return */ public final static String MD5_16(String s) { return MD5_two(s).substring(8, 24); } /** * 加密成为md5串,方式二 32位加密方式 * * @param s * @return */ public final static String MD5_two(String s) { char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; try { byte[] strTemp = s.getBytes(); MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { return null; } } /** * 对字符串以SHA-256方式进行加密 * * @param strSrc * @return */ public final static String SHA_256(String strSrc) { return Encrypt(strSrc, "SHA-256"); } /** * 对字符串加密,加密算法使用MD5,SHA-1,SHA-256,默认使用SHA-256 * * @param strSrc * 要加密的字符串 * @param encName * 加密类型 * @return */ public final static String Encrypt(String strSrc, String encName) { MessageDigest md = null; String strDes = null; byte[] bt = strSrc.getBytes(); try { if (encName == null || encName.equals("")) { encName = "SHA-256"; } md = MessageDigest.getInstance(encName); md.update(bt); strDes = bytes2Hex(md.digest()); // to HexString } catch (NoSuchAlgorithmException e) { return null; } return strDes; } private static String bytes2Hex(byte[] bts) { String des = ""; String tmp = null; for (int i = 0; i < bts.length; i++) { tmp = (Integer.toHexString(bts[i] & 0xFF)); if (tmp.length() == 1) { des += "0"; } des += tmp; } return des; } }
mniip/atheme-contrib-modules
src/gen_vhostonreg.c
<filename>src/gen_vhostonreg.c /* * Copyright (c) 2005-2006 <NAME>, et al. * Rights to this code are as documented in doc/LICENSE. * * Sets usercloak metadata on register. */ #include "atheme-compat.h" /* allow us-ascii letters, digits and the following characters */ #define VALID_SPECIALS "-" static int counter = 0; static void user_add_host(myuser_t *mu) { int maxlen1, i; char newhost[COMPAT_HOSTLEN + 1]; const char *p; bool invalidchar = false; maxlen1 = COMPAT_HOSTLEN - 1 - strlen(me.hidehostsuffix); if (maxlen1 < 9) return; p = entity(mu)->name; i = 0; while (i < maxlen1 && *p != '\0') { if (isalnum((unsigned char)*p) || strchr(VALID_SPECIALS, *p)) newhost[i++] = *p; else invalidchar = true; p++; } if (invalidchar || *p != '\0') { if (i > maxlen1 - 6) i = maxlen1 - 6; snprintf(newhost + i, sizeof newhost - i, "-%05d", counter); counter++; if (counter >= 100000) counter = 0; if (nicksvs.me != NULL) { myuser_notice(nicksvs.nick, mu, "Your account name cannot be used in a vhost directly. To ensure uniqueness, a number was added."); myuser_notice(nicksvs.nick, mu, "To avoid this, register an account name containing only letters, digits and %s.", VALID_SPECIALS); if (!nicksvs.no_nick_ownership && command_find(nicksvs.me->commands, "GROUP")) myuser_notice(nicksvs.nick, mu, "If you drop %s you can group it to your new account.", entity(mu)->name); } } else newhost[i] = '\0'; mowgli_strlcat(newhost, ".", sizeof newhost); mowgli_strlcat(newhost, me.hidehostsuffix, sizeof newhost); metadata_add(mu, "private:usercloak", newhost); } static void handle_verify_register(hook_user_req_t *req) { myuser_t *mu = req->mu; mowgli_node_t *n; user_t *u; if (me.hidehostsuffix == NULL) return; user_add_host(mu); MOWGLI_ITER_FOREACH(n, mu->logins.head) { u = n->data; hook_call_user_identify(u); /* XXX */ } } static void hook_user_identify(user_t *u) { /* if they have an existing cloak, don't do anything */ if ((metadata_find(u->myuser, "private:usercloak")) || (me.hidehostsuffix == NULL)) return; /* they do not, add one. */ user_add_host(u->myuser); } static void mod_init(module_t *const restrict m) { hook_add_event("user_verify_register"); hook_add_user_verify_register(handle_verify_register); hook_add_event("user_identify"); hook_add_user_identify(hook_user_identify); counter = (CURRTIME << 8) % 100000; if (counter < 0) counter += 100000; } static void mod_deinit(const module_unload_intent_t intent) { hook_del_user_verify_register(handle_verify_register); hook_del_user_identify(hook_user_identify); } SIMPLE_DECLARE_MODULE_V1("contrib/gen_vhostonreg", MODULE_UNLOAD_CAPABILITY_OK)
HenryLong/Android_busybox
busybox-1.28.0/include/config/feature/fbset/fancy.h
<gh_stars>10-100 #define CONFIG_FEATURE_FBSET_FANCY 1
edzya/Python_RTU_08_20
Diena_7_functions/fun_g1.py
# global variable here dessert = "ice cream" # defining function def eat_food(dish): """ Orders Food """ # the above triple quoted string is documentation # printing is considered a side-effect print("Hello") print(f"Let's eat {dish}") print("Good bye") # returns None by default if not specified eat_food("potatoes") # DRY princips DO NOT REPEAT YOURSELF eat_food("fish") eat_food(dessert) eat_food(9000) print(dessert) # returning values def adder(a, b): result = a+b # result will not be available outside adder # print(a+b) # print(result) # return a+b return result # result is not visible after indentation stops my_val = adder(5, 10) my_str = adder("alus", " muca") print(my_val, my_str) print(adder(adder(5, 20), 50)) def mult(a, b): # there could be some sanitization and validation here return a * b big_result = mult(adder(5, 10), mult(2, 20)) print(big_result) def big_calc(a, b, c): result = mult(adder(a, b), adder(b, c)) # (a+b)*(b+c) return result result = big_calc(2, 3, 4) print(result) # we can add default values to parameters/argument # sane defaults def lazy_pow(a=10, b=2, pretty_print=False): result = a**b if pretty_print: print(f"Cool {a=} to the power of {b=} is {result}") return result print(lazy_pow(5, 3)) print(lazy_pow(5)) print(lazy_pow()) print(lazy_pow(pretty_print=True)) # could change order but generally not recommended print(lazy_pow(pretty_print=True, b=4, a=10)) def super_add(*argv): result = 0 for arg in argv: print(arg) result += arg # return sum(argv) return result # super_add(5, 10, "Valdis", True, 3.14) result = super_add(5, 10, 20) print(result) # print(super_add("Valdis", " likes", " coding", "and food")) my_list = [1, 2, 3] def mod_list(arg_list): arg_list.append(10) arg_list += [20] # turns out += for list is like extends in place # arg_list = arg_list + [30] this will creat a new list!! return my_list print(my_list) mod_list(my_list) print(my_list) another_list = [14, 30] mod_list(another_list) print(another_list)
paolamvhz/azure-sdk-for-java
sdk/network/mgmt-v2020_08_01/src/main/java/com/microsoft/azure/management/network/v2020_08_01/implementation/ServiceTagsListResultInner.java
<filename>sdk/network/mgmt-v2020_08_01/src/main/java/com/microsoft/azure/management/network/v2020_08_01/implementation/ServiceTagsListResultInner.java /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2020_08_01.implementation; import java.util.List; import com.microsoft.azure.management.network.v2020_08_01.ServiceTagInformation; import com.fasterxml.jackson.annotation.JsonProperty; /** * Response for the ListServiceTags API service call. */ public class ServiceTagsListResultInner { /** * The name of the cloud. */ @JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY) private String name; /** * The ID of the cloud. */ @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) private String id; /** * The azure resource type. */ @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY) private String type; /** * The iteration number. */ @JsonProperty(value = "changeNumber", access = JsonProperty.Access.WRITE_ONLY) private String changeNumber; /** * The name of the cloud. */ @JsonProperty(value = "cloud", access = JsonProperty.Access.WRITE_ONLY) private String cloud; /** * The list of service tag information resources. */ @JsonProperty(value = "values", access = JsonProperty.Access.WRITE_ONLY) private List<ServiceTagInformation> values; /** * The URL to get next page of service tag information resources. */ @JsonProperty(value = "nextLink", access = JsonProperty.Access.WRITE_ONLY) private String nextLink; /** * Get the name of the cloud. * * @return the name value */ public String name() { return this.name; } /** * Get the ID of the cloud. * * @return the id value */ public String id() { return this.id; } /** * Get the azure resource type. * * @return the type value */ public String type() { return this.type; } /** * Get the iteration number. * * @return the changeNumber value */ public String changeNumber() { return this.changeNumber; } /** * Get the name of the cloud. * * @return the cloud value */ public String cloud() { return this.cloud; } /** * Get the list of service tag information resources. * * @return the values value */ public List<ServiceTagInformation> values() { return this.values; } /** * Get the URL to get next page of service tag information resources. * * @return the nextLink value */ public String nextLink() { return this.nextLink; } }
zenwerk/littlesmalltalk
lst5/thirdparty/iup2_6_rc2_Win32_dll_lib/include/iupcells.h
<filename>lst5/thirdparty/iup2_6_rc2_Win32_dll_lib/include/iupcells.h /** \file * \brief iupcells control. * * See Copyright Notice in iup.h */ #ifndef __IUPCELLS_H #define __IUPCELLS_H #define IUP_OUT -999 #ifndef IUP_ALL #define IUP_ALL "ALL" #endif #ifndef IUP_BOXED #define IUP_BOXED "BOXED" #endif #ifndef IUP_CLIPPED #define IUP_CLIPPED "CLIPPED" #endif #ifndef IUP_TRANSPARENT #define IUP_TRANSPARENT "TRANSPARENT" #endif #ifndef IUP_NON_SCROLLABLE_LINES #define IUP_NON_SCROLLABLE_LINES "NON_SCROLLABLE_LINES" #endif #ifndef IUP_NON_SCROLLABLE_COLS #define IUP_NON_SCROLLABLE_COLS "NON_SCROLLABLE_COLS" #endif #ifndef IUP_ORIGIN #define IUP_ORIGIN "ORIGIN" #endif #ifndef IUP_NO_COLOR #define IUP_NO_COLOR "NO_COLOR" #endif #ifndef IUP_FIRST_LINE #define IUP_FIRST_LINE "FIRST_LINE" #endif #ifndef IUP_FIRST_COL #define IUP_FIRST_COL "FIRST_COL" #endif #ifndef IUP_DOUBLE_BUFFER #define IUP_DOUBLE_BUFFER "DOUBLE_BUFFER" #endif #ifndef IUP_BUFFERIZE #define IUP_BUFFERIZE "BUFFERIZE" #endif #ifndef IUP_REPAINT #define IUP_REPAINT "REPAINT" #endif #ifndef IUP_LIMITS #define IUP_LIMITS "LIMITS" #endif #ifndef IUP_CANVAS #define IUP_CANVAS "CANVAS" #endif #ifndef IUP_IMAGE_CANVAS #define IUP_IMAGE_CANVAS "IMAGE_CANVAS" #endif #ifndef IUP_FULL_VISIBLE #define IUP_FULL_VISIBLE "FULL_VISIBLE" #endif #ifndef IUP_MOUSECLICK_CB #define IUP_MOUSECLICK_CB "MOUSECLICK_CB" #endif #ifndef IUP_MOUSEMOTION_CB #define IUP_MOUSEMOTION_CB "MOUSEMOTION_CB" #endif #ifndef IUP_DRAW_CB #define IUP_DRAW_CB "DRAW_CB" #endif #ifndef IUP_WIDTH_CB #define IUP_WIDTH_CB "WIDTH_CB" #endif #ifndef IUP_HEIGHT_CB #define IUP_HEIGHT_CB "HEIGHT_CB" #endif #ifndef IUP_NLINES_CB #define IUP_NLINES_CB "NLINES_CB" #endif #ifndef IUP_NCOLS_CB #define IUP_NCOLS_CB "NCOLS_CB" #endif #ifndef IUP_HSPAN_CB #define IUP_HSPAN_CB "HSPAN_CB" #endif #ifndef IUP_VSPAN_CB #define IUP_VSPAN_CB "VSPAN_CB" #endif #ifndef IUP_SCROLLING_CB #define IUP_SCROLLING_CB "SCROLLING_CB" #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ Ihandle* IupCells(void); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _iupcells_h */
ElatedEatrs/Pikifen
Source/source/mob_types/onion_type.h
<reponame>ElatedEatrs/Pikifen /* * Copyright (c) <NAME> 2013. * The following source file belongs to the open-source project Pikifen. * Please read the included README and LICENSE files for more information. * Pikmin is copyright (c) Nintendo. * * === FILE DESCRIPTION === * Header for the Onion type class and Onion type-related functions. */ #ifndef ONION_TYPE_INCLUDED #define ONION_TYPE_INCLUDED #include "../data_file.h" #include "mob_type.h" #include "pikmin_type.h" /* ---------------------------------------------------------------------------- * An Onion type. * It's basically associated with a Pikmin type. */ class onion_type : public mob_type { public: pikmin_type* pik_type; onion_type(); ~onion_type(); void load_parameters(data_node* file); anim_conversion_vector get_anim_conversions(); }; #endif //ifndef ONION_TYPE_INCLUDED
billybecker/pants
tests/python/pants_test/source/test_filespec.py
<filename>tests/python/pants_test/source/test_filespec.py # coding=utf-8 # Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import unittest from pants.source.filespec import matches_filespec class FilespecTest(unittest.TestCase): def assert_rule_match(self, glob, expected_matches, negate=False): if negate: asserter, match_state = self.assertFalse, 'erroneously matches' else: asserter, match_state = self.assertTrue, "doesn't match" for expected in expected_matches: asserter( matches_filespec(expected, {'globs': [glob]}), '{} {} path `{}`'.format(glob, match_state, expected), ) def test_matches_single_star_0(self): self.assert_rule_match('a/b/*/f.py', ('a/b/c/f.py', 'a/b/q/f.py')) def test_matches_single_star_0_neg(self): self.assert_rule_match('a/b/*/f.py', ('a/b/c/d/f.py','a/b/f.py'), negate=True) def test_matches_single_star_1(self): self.assert_rule_match('foo/bar/*', ('foo/bar/baz', 'foo/bar/bar')) def test_matches_single_star_2(self): self.assert_rule_match('*/bar/b*', ('foo/bar/baz', 'foo/bar/bar')) def test_matches_single_star_2_neg(self): self.assert_rule_match('*/bar/b*', ('foo/koo/bar/baz', 'foo/bar/bar/zoo'), negate=True) def test_matches_single_star_3(self): self.assert_rule_match('*/[be]*/b*', ('foo/bar/baz', 'foo/bar/bar')) def test_matches_single_star_4(self): self.assert_rule_match('foo*/bar', ('foofighters/bar', 'foofighters.venv/bar')) def test_matches_single_star_4_neg(self): self.assert_rule_match('foo*/bar', ('foofighters/baz/bar',), negate=True) def test_matches_double_star_0(self): self.assert_rule_match('**', ('a/b/c', 'a')) def test_matches_double_star_1(self): self.assert_rule_match('a/**/f', ('a/f', 'a/b/c/d/e/f')) def test_matches_double_star_2(self): self.assert_rule_match('a/b/**', ('a/b/c', 'a/b/c/d/e/f')) def test_matches_double_star_2_neg(self): self.assert_rule_match('a/b/**', ('a/b'), negate=True) def test_matches_dots(self): self.assert_rule_match('.*', ('.pants.d', '.pids')) def test_matches_dots_relative(self): self.assert_rule_match('./*.py', ('f.py', 'g.py')) def test_matches_dots_neg(self): self.assert_rule_match( '.*', ('a', 'a/non/dot/dir/file.py', 'dist', 'all/nested/.dot', '.some/hidden/nested/dir/file.py'), negate=True ) def test_matches_dirs(self): self.assert_rule_match('dist/', ('dist',)) def test_matches_dirs_neg(self): self.assert_rule_match('dist/', ('not_dist', 'cdist', 'dist.py', 'dist/dist'), negate=True) def test_matches_dirs_dots(self): self.assert_rule_match( 'build-support/*.venv/', ('build-support/*.venv', 'build-support/rbt.venv') ) def test_matches_dirs_dots_neg(self): self.assert_rule_match('build-support/*.venv/', ('build-support/rbt.venv.but_actually_a_file',), negate=True) def test_matches_literals(self): self.assert_rule_match('a', ('a',)) def test_matches_literal_dir(self): self.assert_rule_match('a/b/c', ('a/b/c',)) def test_matches_literal_file(self): self.assert_rule_match('a/b/c.py', ('a/b/c.py',))
Slovty/helloGo
pkg/interdace/interface_api.go
<reponame>Slovty/helloGo package main import "fmt" type Goods struct { ID uint Price uint Name string GoodsType string } type Course struct { ID uint Price uint Name string GoodsType string } type Discount struct { Discount uint Price uint } type UserOrder struct { Id uint Price uint Name uint OrderNo string GoodsID uint } type Order interface { Pay() (uint, error) GetPrice(discount uint) (uint, error) ContinuePay(orderID uint) error } func main() { g := Goods{ ID: 1, Price: 10, Name: "apple", GoodsType: "fruit", } c := Course{ ID: 2, Price: 20, Name: "正式课", GoodsType: "course", } s := []Order{&g, &c} //通过指针实现 for _, o := range s { id, _ := o.Pay() o.GetPrice(80) o.ContinuePay(id) } //c.Pay() //c.GetPrice(80) //c.ContinuePay(1) } func (g *Goods) Pay() (uint, error) { fmt.Printf("%s成功支付了%d元\n", g.Name, g.Price) return 1, nil } func (g *Goods) GetPrice(discount uint) (uint, error) { g.Price = (g.Price * discount) / 100 return g.Price, nil } func (g *Goods) ContinuePay(orderID uint) error { fmt.Printf("订单id为:%d,%s成功继续支付了%d元\n", orderID, g.Name, g.Price) return nil } func (g *Course) Pay() (uint, error) { fmt.Printf("%s成功支付了%d元\n", g.Name, g.Price) return 1, nil } func (g *Course) GetPrice(discount uint) (uint, error) { g.Price = (g.Price * discount) / 100 return g.Price, nil } func (g *Course) ContinuePay(orderID uint) error { fmt.Printf("订单id为:%d,%s成功继续支付了%d元\n", orderID, g.Name, g.Price) return nil }
dmnyk/eightshift-frontend-libs
blocks/init/src/Blocks/components/paragraph/components/paragraph-options.js
import React from 'react'; import { __ } from '@wordpress/i18n'; import { ColorPaletteCustom, ComponentUseToggle, IconLabel, CustomSelect, checkAttr, getAttrKey, icons, getOption } from '@eightshift/frontend-libs/scripts'; import manifest from './../manifest.json'; export const ParagraphOptions = (attributes) => { const { title: manifestTitle, } = manifest; const { setAttributes, label = manifestTitle, paragraphShowControls = true, showParagraphUse = false, showLabel = false, showParagraphColor = true, showParagraphSize = true, } = attributes; if (!paragraphShowControls) { return null; } const paragraphUse = checkAttr('paragraphUse', attributes, manifest); const paragraphColor = checkAttr('paragraphColor', attributes, manifest); const paragraphSize = checkAttr('paragraphSize', attributes, manifest); return ( <> <ComponentUseToggle label={label} checked={paragraphUse} onChange={(value) => setAttributes({ [getAttrKey('paragraphUse', attributes, manifest)]: value })} showUseToggle={showParagraphUse} showLabel={showLabel} /> {paragraphUse && <> {showParagraphColor && <ColorPaletteCustom label={<IconLabel icon={icons.color} label={__('Color', 'eightshift-frontend-libs')} />} colors={getOption('paragraphColor', attributes, manifest, true)} value={paragraphColor} onChange={(value) => setAttributes({ [getAttrKey('paragraphColor', attributes, manifest)]: value })} /> } {showParagraphSize && <CustomSelect label={<IconLabel icon={icons.textSize} label={__('Text size', 'eightshift-frontend-libs')} />} value={paragraphSize} options={getOption('paragraphSize', attributes, manifest)} onChange={(value) => setAttributes({ [getAttrKey('paragraphSize', attributes, manifest)]: value })} isClearable={false} isSearchable={false} simpleValue /> } </> } </> ); };
rubera/superfly
superfly-service/src/main/java/com/payneteasy/superfly/model/ui/group/UIGroupForList.java
<reponame>rubera/superfly<filename>superfly-service/src/main/java/com/payneteasy/superfly/model/ui/group/UIGroupForList.java<gh_stars>0 package com.payneteasy.superfly.model.ui.group; import java.io.Serializable; import javax.persistence.Column; public class UIGroupForList implements Serializable { private long id; private String name; private String subsystemName; private boolean selected; public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } @Column(name = "subsystem_name") public String getSubsystemName() { return subsystemName; } public void setSubsystemName(String name) { this.subsystemName = name; } @Column(name = "grop_id") public long getId() { return id; } public void setId(long id) { this.id = id; } @Column(name = "group_name") public String getName() { return name; } public void setName(String name) { this.name = name; } }
semihshn/HRMS-Project-React
src/store/reducers/jobAdvertReducer.js
import { ADD_JOBADVERT_ERROR, ADD_JOBADVERT_SUCCESS, GETALL_JOBADVERT_ISACTIVE_ERROR, GETALL_JOBADVERT_ISACTIVE_SUCCESS, GETALL_JOBADVERT_SUCCESS } from "../actions/jobAdvertActions"; import { GETALL_JOBADVERT_ERROR } from "../actions/jobAdvertActions"; import { jobAdverts } from "../initialValues/jobAdvertInitialValues"; import { message } from "../initialValues/jobAdvertInitialValues"; const initialState = {jobAdverts,message}; export default function jobAdvertReducer(state = initialState, { type, payload }) { switch (type) { case GETALL_JOBADVERT_SUCCESS: return {...state,jobAdverts:payload}; case GETALL_JOBADVERT_ERROR: return {...state,message:payload}; case GETALL_JOBADVERT_ISACTIVE_SUCCESS: return {...state,jobAdverts:payload}; case GETALL_JOBADVERT_ISACTIVE_ERROR: return {...state,message:payload}; case ADD_JOBADVERT_SUCCESS: return {...state,message:payload}; case ADD_JOBADVERT_ERROR: return {...state,message:payload}; default: return state; } }
mailslurp/mailslurp-client-cpp-restsdk
IHttpBody.h
/** * MailSlurp API * MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://www.mailslurp.com/docs/) - [Examples](https://github.com/mailslurp/examples) repository * * The version of the OpenAPI document: 6.5.2 * * NOTE: This class is auto generated by OpenAPI-Generator 4.3.1. * https://openapi-generator.tech * Do not edit the class manually. */ /* * IHttpBody.h * * This is the interface for contents that can be sent to a remote HTTP server. */ #ifndef COM_MAILSLURP_CLIENT_MODEL_IHttpBody_H_ #define COM_MAILSLURP_CLIENT_MODEL_IHttpBody_H_ #include <iostream> namespace com { namespace mailslurp { namespace client { namespace model { class IHttpBody { public: virtual ~IHttpBody() { } virtual void writeTo( std::ostream& stream ) = 0; }; } } } } #endif /* COM_MAILSLURP_CLIENT_MODEL_IHttpBody_H_ */
stinsonga/geo-prime-workspace
work/exampleRfej.js
<reponame>stinsonga/geo-prime-workspace<filename>work/exampleRfej.js function my_function814(){ //69431273801865594350646811734515sJEIFxrhVFtWVUXySwUUgsYPvExYWMkr } function my_function465(){ //00203074766067193284640057627328bqhEwlxWkqQobuBmbdRpDendtjWYVQBz } function my_function475(){ //64470309593356241348249530298946RCEGLpTAeqrEjmATJKaRZFftwGDktfqu } function my_function868(){ //32915403552377418355435526094895efiCQVCNPuJiOpjqxjdSkKGmExdfPbSn } function my_function901(){ //57413884480948831782350813594961rwLsovEGgzYvJMWuybLdxvytGgGJosaB } function my_function020(){ //13339376447098634816818414279239htbegDdfOSQsdRVhmSynGTpyiMsxncPV } function my_function798(){ //29289478660251276549586201099930jTPNXkerRCSHWkUkctSeJFIiDagwXYGm } function my_function071(){ //22256320610473085911628977705357qYQFubJaCVXloWDhMVdMprfTDdpdTRjp } function my_function173(){ //91519048498140017530242904458341LteVKVMJbKCzJoXAmoHtqeBzXubkTPBD } function my_function390(){ //21887716388367975822837799193013bkDtgMtJajgImsZcWqFBDqXPtFqAlySd } function my_function037(){ //78982622690541530550246195880268fHmKbjOfvNFFvUgnqyKrTbOWCDsaDpEa } function my_function638(){ //69058556902983079810597438394514GuOdTnZeqNjIuWBCRESHmrCVePdgBnyo } function my_function154(){ //31284424146427292084918067079381zPZuzeyqKTLRcdBpHeLnmrdFUkCldJre } function my_function801(){ //43872144828025257287724694691944PiHyvrkvBymAkgQGmUvYOmkZSEzmtZjG } function my_function301(){ //81709815669910010688859348656506ZcPdFMBtYZuPQytXJSfATSGgtHBuiIxO } function my_function495(){ //55962617612678686074889299739988GWosdddsfBFznhbRvDIqkGaiePwCoIjQ } function my_function906(){ //46571189446858280889787647466066bQmonXcDWPamWDBYSQjHDxBioKWBMJaU } function my_function142(){ //59311451691753935844258794061016vJyOIaqcZiaSbKznOpwuBVqNovPaoswk } function my_function132(){ //97206616693010468477523348887871BZsgPHVmnjuBnAyKxntWhGeNweackbxg } function my_function236(){ //15309576580203907367840672952202IgOomhfbcOPNzCkiInngZvXyXlwVfWJD } function my_function769(){ //39821943016569235334700379391446aGnoApOHGSwwoybrxKzxHVpuOSEZksYH } function my_function796(){ //61197818078170945458457389262470ZvaQqWnmxrmCdubpfjCzdGOFnxcgbBTi } function my_function258(){ //11301390916116978582454474028525cOfsOGNldaFwdofWyuuborXvxEoseoVt } function my_function830(){ //96523528773611660222610762161588IhKVwohlHgEEFmAITelpKPpAjNJhRBnI } function my_function491(){ //04705051749542473687476183111496HUrUcYFAlBOmeAvGfZWgoDBmNlHdqath } function my_function562(){ //19488314553268254453078384006935MpqLTgeWASKWaoOssmpRujiWUmJFNrNr } function my_function374(){ //37665972841394195928797779149782JdIpRvnnRmAzYUzHMEZmotMQwxAHrCxS } function my_function735(){ //16589239772515117571405864541770awIlmfFLsqfcLSYBOLkFtvYDwkoiRyBG } function my_function245(){ //90285332503968778889920307288760abTwtEQStQCUpuiHNKYAVflPwmHldCUX } function my_function760(){ //69736342443435669284976422396969eyXhdGaOsZLFbOwNdqaOWpJiAklwQNCy } function my_function710(){ //32293994462022807413769064819422oCITbePHBmYBNvoKErVwhTSzxvhcLhMv } function my_function207(){ //50349120094312346908931780383806raAcTrDXWB<KEY> } function my_function657(){ //24793309516124629598981683316823YSOtuXlLgxeSHLPwpihdWSfOaJqnlTLK } function my_function629(){ //78354878284760695205809244064299DrblvhjFYBgbRsvCzssHrScrRbSgzAuv } function my_function613(){ //21686301051381095902407994051774PSrbElUjZeTcbzOOYMCuOYKuQXJBuqlB } function my_function777(){ //94659838327188349938892147479882cSvwmdlsNjdFrcxiuyBqJFQSFNlbnkOA } function my_function198(){ //42565685585041956119432227384346HLpLeGZnwLIokgHFCzrIQLPygTngUNQD } function my_function470(){ //33940716220221625289942922433905fSlRZTrAiGLhUwxAOnYiagqivUNJtgVO } function my_function912(){ //80697631761646639288558396267915GojniEDAsJJoNKfnZnWwwGIePUrZOAwD } function my_function984(){ //14653811471827643959687749095001vYmCcKuOivgcDbiIQHDncJOPjRZXVteA } function my_function598(){ //32002702095140797262759252972867gjvuUayPeeDifZCwStBNkEeoWHyKvyeu } function my_function313(){ //56425843679304350782879142934045xoEcLQmyRtxikHRXTsxCmQQwSYsfzqpG } function my_function074(){ //55429296508110244074375607766989fvTkQJkVoRnnaIClwCAuRufLivGTJXZk } function my_function238(){ //46785193565304159545720472245773PewGqnUElutSYkhVdNFyuBGvzHnxMMFk }
rualso/kv_engine
tests/testapp/testapp_xattr_deleted.cc
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2020 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Test extended attribute functionality related to the 'CreateAsDeleted' * doc flag. * * Initial use-case for this doc flag is Transactions. */ #include "testapp_xattr.h" using namespace mcbp::subdoc; using namespace cb::mcbp; // Negative test: The subdoc operation returns Einval as // doc_flag::CreateAsDeleted requires one of doc_flag::Mkdoc/Add. void XattrNoDocTest::testRequiresMkdocOrAdd() { auto resp = subdoc(cb::mcbp::ClientOpcode::SubdocDictAdd, name, "txn.deleted", "true", SUBDOC_FLAG_XATTR_PATH | SUBDOC_FLAG_MKDIR_P, doc_flag::CreateAsDeleted, durReqs); EXPECT_EQ(cb::mcbp::Status::Einval, resp.getStatus()); } TEST_P(XattrNoDocTest, RequiresMkdocOrAdd) { testRequiresMkdocOrAdd(); } TEST_P(XattrNoDocDurabilityTest, RequiresMkdocOrAdd) { testRequiresMkdocOrAdd(); } // Negative test: The Subdoc CreateAsDeleted doesn't allow to write in the // body. void XattrNoDocTest::testRequiresXattrPath() { // Note: subdoc-flags doesn't set SUBDOC_FLAG_XATTR_PATH auto resp = subdoc(cb::mcbp::ClientOpcode::SubdocDictAdd, name, "txn.deleted", "true", SUBDOC_FLAG_MKDIR_P, doc_flag::Mkdoc | doc_flag::CreateAsDeleted); EXPECT_EQ(cb::mcbp::Status::Einval, resp.getStatus()); } TEST_P(XattrNoDocTest, RequiresXattrPath) { testRequiresXattrPath(); } TEST_P(XattrNoDocDurabilityTest, RequiresXattrPath) { testRequiresXattrPath(); } // Positive test: Can User XAttrs be added to a document which doesn't exist // (and doesn't have a tombstone) using the new CreateAsDeleted flag. void XattrNoDocTest::testSinglePathDictAdd() { if (durReqs && !supportSyncRepl()) { GTEST_SKIP(); } // let's add a user XATTR to a non-existing document auto resp = subdoc(cb::mcbp::ClientOpcode::SubdocDictAdd, name, "txn.deleted", "true", SUBDOC_FLAG_XATTR_PATH | SUBDOC_FLAG_MKDIR_P, doc_flag::Mkdoc | doc_flag::CreateAsDeleted, durReqs); EXPECT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); // Check that the User XATTR is present. resp = subdoc_get( "txn.deleted", SUBDOC_FLAG_XATTR_PATH, doc_flag::AccessDeleted); ASSERT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); EXPECT_EQ("true", resp.getValue()); // Check that the value is deleted and empty - which is treated as // not existing with normal subdoc operations. auto lookup = subdoc_multi_lookup( {{cb::mcbp::ClientOpcode::Get, SUBDOC_FLAG_NONE, ""}}, mcbp::subdoc::doc_flag::AccessDeleted); EXPECT_EQ(cb::mcbp::Status::SubdocMultiPathFailureDeleted, lookup.getStatus()); // Also check via getMeta - which should show the document exists but // as deleted. auto meta = getConnection().getMeta(name, Vbid(0), GetMetaVersion::V2); EXPECT_EQ(cb::mcbp::Status::Success, meta.first); EXPECT_EQ(PROTOCOL_BINARY_DATATYPE_XATTR, meta.second.datatype); EXPECT_EQ(1, meta.second.deleted); } TEST_P(XattrNoDocTest, SinglePathDictAdd) { testSinglePathDictAdd(); } TEST_P(XattrNoDocDurabilityTest, SinglePathDictAdd) { testSinglePathDictAdd(); } // Positive tests: Can User XAttrs be added to a document which doesn't exist // (and doesn't have a tombstone) using the new CreateAsDeleted flag, using // multi-mutation with each mutation opcode. void XattrNoDocTest::testMultipathDictAdd() { if (durReqs && !supportSyncRepl()) { GTEST_SKIP(); } BinprotSubdocMultiMutationCommand cmd( name, {{ClientOpcode::SubdocDictAdd, SUBDOC_FLAG_XATTR_PATH, "txn", "\"foo\""}}, doc_flag::Mkdoc | doc_flag::CreateAsDeleted, durReqs); auto resp = subdocMultiMutation(cmd); EXPECT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); // Check the last path was created correctly. resp = subdoc_get("txn", SUBDOC_FLAG_XATTR_PATH, doc_flag::AccessDeleted); ASSERT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); EXPECT_EQ("\"foo\"", resp.getValue()); // Check that the value is deleted and empty - which is treated as // not existing with normal subdoc operations. auto lookup = subdoc_multi_lookup( {{cb::mcbp::ClientOpcode::Get, SUBDOC_FLAG_NONE, ""}}, mcbp::subdoc::doc_flag::AccessDeleted); EXPECT_EQ(cb::mcbp::Status::SubdocMultiPathFailureDeleted, lookup.getStatus()); // Also check via getMeta - which should show the document exists but // as deleted. auto meta = getConnection().getMeta(name, Vbid(0), GetMetaVersion::V2); EXPECT_EQ(cb::mcbp::Status::Success, meta.first); EXPECT_EQ(PROTOCOL_BINARY_DATATYPE_XATTR, meta.second.datatype); EXPECT_EQ(1, meta.second.deleted); } TEST_P(XattrNoDocTest, MultipathDictAdd) { testMultipathDictAdd(); } TEST_P(XattrNoDocDurabilityTest, MultipathDictAdd) { testMultipathDictAdd(); } void XattrNoDocTest::testMultipathDictUpsert() { if (durReqs && !supportSyncRepl()) { GTEST_SKIP(); } BinprotSubdocMultiMutationCommand cmd( name, {{ClientOpcode::SubdocDictUpsert, SUBDOC_FLAG_XATTR_PATH, "txn", "\"bar\""}}, doc_flag::Mkdoc | doc_flag::CreateAsDeleted, durReqs); auto resp = subdocMultiMutation(cmd); EXPECT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); resp = subdoc_get("txn", SUBDOC_FLAG_XATTR_PATH, doc_flag::AccessDeleted); ASSERT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); EXPECT_EQ("\"bar\"", resp.getValue()); } TEST_P(XattrNoDocTest, MultipathDictUpsert) { testMultipathDictUpsert(); } TEST_P(XattrNoDocDurabilityTest, MultipathDictUpsert) { testMultipathDictUpsert(); } void XattrNoDocTest::testMultipathArrayPushLast() { if (durReqs && !supportSyncRepl()) { GTEST_SKIP(); } BinprotSubdocMultiMutationCommand cmd( name, {{ClientOpcode::SubdocArrayPushLast, SUBDOC_FLAG_XATTR_PATH, "array", "1"}}, doc_flag::Mkdoc | doc_flag::CreateAsDeleted, durReqs); auto resp = subdocMultiMutation(cmd); EXPECT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); resp = subdoc_get("array", SUBDOC_FLAG_XATTR_PATH, doc_flag::AccessDeleted); ASSERT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); EXPECT_EQ("[1]", resp.getValue()); } TEST_P(XattrNoDocTest, MultipathArrayPushLast) { testMultipathArrayPushLast(); } TEST_P(XattrNoDocDurabilityTest, MultipathArrayPushLast) { testMultipathArrayPushLast(); } void XattrNoDocTest::testMultipathArrayPushFirst() { if (durReqs && !supportSyncRepl()) { GTEST_SKIP(); } BinprotSubdocMultiMutationCommand cmd( name, {{ClientOpcode::SubdocArrayPushFirst, SUBDOC_FLAG_XATTR_PATH, "array", "2"}}, doc_flag::Mkdoc | doc_flag::CreateAsDeleted, durReqs); auto resp = subdocMultiMutation(cmd); EXPECT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); resp = subdoc_get("array", SUBDOC_FLAG_XATTR_PATH, doc_flag::AccessDeleted); ASSERT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); EXPECT_EQ("[2]", resp.getValue()); } TEST_P(XattrNoDocTest, MultipathArrayPushFirst) { testMultipathArrayPushFirst(); } TEST_P(XattrNoDocDurabilityTest, MultipathArrayPushFirst) { testMultipathArrayPushFirst(); } // @todo MB-39545: This test fails because doc_flag::Mkdoc is invalid with // ArrayInsert (the test fails at validation for ArrayInsert with "Invalid // arguments"). // By changing to doc_flag::Add (valid for ArrayInsert) the test gets to the // execution of ArrayInsert but is fails with SubdocMultiPathFailure. // Specific and simple (single-path) tests on ArrayInsert suggests that we may // have some existing issue in that area that we should address in a dedicated // patch. TEST_P(XattrNoDocTest, DISABLED_MultipathArrayInsert) { BinprotSubdocMultiMutationCommand cmd( name, {{ClientOpcode::SubdocArrayPushFirst, SUBDOC_FLAG_XATTR_PATH, "array", "0"}, {ClientOpcode::SubdocArrayInsert, SUBDOC_FLAG_XATTR_PATH, "array.[0]", "1"}}, doc_flag::Mkdoc | doc_flag::CreateAsDeleted, durReqs); auto resp = subdocMultiMutation(cmd); EXPECT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); resp = subdoc_get("array", SUBDOC_FLAG_XATTR_PATH, doc_flag::AccessDeleted); ASSERT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); EXPECT_EQ("[0,1]", resp.getValue()); } void XattrNoDocTest::testMultipathArrayAddUnique() { if (durReqs && !supportSyncRepl()) { GTEST_SKIP(); } BinprotSubdocMultiMutationCommand cmd( name, {{ClientOpcode::SubdocArrayAddUnique, SUBDOC_FLAG_XATTR_PATH, "array", "4"}}, doc_flag::Mkdoc | doc_flag::CreateAsDeleted, durReqs); auto resp = subdocMultiMutation(cmd); EXPECT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); resp = subdoc_get("array", SUBDOC_FLAG_XATTR_PATH, doc_flag::AccessDeleted); ASSERT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); EXPECT_EQ("[4]", resp.getValue()); } TEST_P(XattrNoDocTest, MultipathArrayAddUnique) { testMultipathArrayAddUnique(); } TEST_P(XattrNoDocDurabilityTest, MultipathArrayAddUnique) { testMultipathArrayAddUnique(); } void XattrNoDocTest::testMultipathCounter() { if (durReqs && !supportSyncRepl()) { GTEST_SKIP(); } BinprotSubdocMultiMutationCommand cmd( name, {{ClientOpcode::SubdocCounter, SUBDOC_FLAG_XATTR_PATH, "counter", "5"}}, doc_flag::Mkdoc | doc_flag::CreateAsDeleted, durReqs); auto resp = subdocMultiMutation(cmd); EXPECT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); // Check the last path was created correctly. resp = subdoc_get( "counter", SUBDOC_FLAG_XATTR_PATH, doc_flag::AccessDeleted); ASSERT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); EXPECT_EQ("5", resp.getValue()); } TEST_P(XattrNoDocTest, MultipathCounter) { testMultipathCounter(); } TEST_P(XattrNoDocDurabilityTest, MultipathCounter) { testMultipathCounter(); } // Positive test: Can User XAttrs be added to a document which doesn't exist // using the new CreateAsDeleted flag, using a combination of subdoc-multi // mutation types. void XattrNoDocTest::testMultipathCombo() { if (durReqs && !supportSyncRepl()) { GTEST_SKIP(); } auto cmd = makeSDKTxnMultiMutation(); cmd.addDocFlag(doc_flag::Mkdoc); cmd.addDocFlag(doc_flag::CreateAsDeleted); if (durReqs) { cmd.setDurabilityReqs(*durReqs); } auto& conn = getConnection(); conn.sendCommand(cmd); BinprotSubdocResponse resp; conn.recvResponse(resp); EXPECT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); // Check the last path was created correctly. resp = subdoc_get( "txn.counter", SUBDOC_FLAG_XATTR_PATH, doc_flag::AccessDeleted); ASSERT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); EXPECT_EQ("1", resp.getValue()); } TEST_P(XattrNoDocTest, MultipathCombo) { testMultipathCombo(); } TEST_P(XattrNoDocDurabilityTest, MultipathCombo) { testMultipathCombo(); } // Positive test: Can User XAttrs be added to a document which doesn't exist // (and doesn't have a tombstone) using the new CreateAsDeleted flag alongside // AccessDeleted (to check for an existing tombstone). // This is also a regression test for MB-40162. void XattrNoDocTest::testMultipathAccessDeletedCreateAsDeleted() { if (durReqs && !supportSyncRepl()) { GTEST_SKIP(); } auto cmd = makeSDKTxnMultiMutation(); cmd.addDocFlag(doc_flag::Add); cmd.addDocFlag(doc_flag::AccessDeleted); cmd.addDocFlag(doc_flag::CreateAsDeleted); if (durReqs) { cmd.setDurabilityReqs(*durReqs); } auto& conn = getConnection(); conn.sendCommand(cmd); BinprotSubdocResponse resp; conn.recvResponse(resp); EXPECT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); // Check the last path was created correctly. resp = subdoc_get( "txn.counter", SUBDOC_FLAG_XATTR_PATH, doc_flag::AccessDeleted); ASSERT_EQ(cb::mcbp::Status::SubdocSuccessDeleted, resp.getStatus()); EXPECT_EQ("1", resp.getValue()); } TEST_P(XattrNoDocTest, MultipathAccessDeletedCreateAsDeleted) { testMultipathAccessDeletedCreateAsDeleted(); } TEST_P(XattrNoDocDurabilityTest, MultipathAccessDeletedCreateAsDeleted) { testMultipathAccessDeletedCreateAsDeleted(); }
OpenMPDK/SMDK
lib/linux-5.18-rc3-smdk/mm/damon/ops-common.c
<filename>lib/linux-5.18-rc3-smdk/mm/damon/ops-common.c // SPDX-License-Identifier: GPL-2.0 /* * Common Primitives for Data Access Monitoring * * Author: <NAME> <<EMAIL>> */ #include <linux/mmu_notifier.h> #include <linux/page_idle.h> #include <linux/pagemap.h> #include <linux/rmap.h> #include "ops-common.h" /* * Get an online page for a pfn if it's in the LRU list. Otherwise, returns * NULL. * * The body of this function is stolen from the 'page_idle_get_page()'. We * steal rather than reuse it because the code is quite simple. */ struct page *damon_get_page(unsigned long pfn) { struct page *page = pfn_to_online_page(pfn); if (!page || !PageLRU(page) || !get_page_unless_zero(page)) return NULL; if (unlikely(!PageLRU(page))) { put_page(page); page = NULL; } return page; } void damon_ptep_mkold(pte_t *pte, struct mm_struct *mm, unsigned long addr) { bool referenced = false; struct page *page = damon_get_page(pte_pfn(*pte)); if (!page) return; if (pte_young(*pte)) { referenced = true; *pte = pte_mkold(*pte); } #ifdef CONFIG_MMU_NOTIFIER if (mmu_notifier_clear_young(mm, addr, addr + PAGE_SIZE)) referenced = true; #endif /* CONFIG_MMU_NOTIFIER */ if (referenced) set_page_young(page); set_page_idle(page); put_page(page); } void damon_pmdp_mkold(pmd_t *pmd, struct mm_struct *mm, unsigned long addr) { #ifdef CONFIG_TRANSPARENT_HUGEPAGE bool referenced = false; struct page *page = damon_get_page(pmd_pfn(*pmd)); if (!page) return; if (pmd_young(*pmd)) { referenced = true; *pmd = pmd_mkold(*pmd); } #ifdef CONFIG_MMU_NOTIFIER if (mmu_notifier_clear_young(mm, addr, addr + ((1UL) << HPAGE_PMD_SHIFT))) referenced = true; #endif /* CONFIG_MMU_NOTIFIER */ if (referenced) set_page_young(page); set_page_idle(page); put_page(page); #endif /* CONFIG_TRANSPARENT_HUGEPAGE */ } #define DAMON_MAX_SUBSCORE (100) #define DAMON_MAX_AGE_IN_LOG (32) int damon_pageout_score(struct damon_ctx *c, struct damon_region *r, struct damos *s) { unsigned int max_nr_accesses; int freq_subscore; unsigned int age_in_sec; int age_in_log, age_subscore; unsigned int freq_weight = s->quota.weight_nr_accesses; unsigned int age_weight = s->quota.weight_age; int hotness; max_nr_accesses = c->aggr_interval / c->sample_interval; freq_subscore = r->nr_accesses * DAMON_MAX_SUBSCORE / max_nr_accesses; age_in_sec = (unsigned long)r->age * c->aggr_interval / 1000000; for (age_in_log = 0; age_in_log < DAMON_MAX_AGE_IN_LOG && age_in_sec; age_in_log++, age_in_sec >>= 1) ; /* If frequency is 0, higher age means it's colder */ if (freq_subscore == 0) age_in_log *= -1; /* * Now age_in_log is in [-DAMON_MAX_AGE_IN_LOG, DAMON_MAX_AGE_IN_LOG]. * Scale it to be in [0, 100] and set it as age subscore. */ age_in_log += DAMON_MAX_AGE_IN_LOG; age_subscore = age_in_log * DAMON_MAX_SUBSCORE / DAMON_MAX_AGE_IN_LOG / 2; hotness = (freq_weight * freq_subscore + age_weight * age_subscore); if (freq_weight + age_weight) hotness /= freq_weight + age_weight; /* * Transform it to fit in [0, DAMOS_MAX_SCORE] */ hotness = hotness * DAMOS_MAX_SCORE / DAMON_MAX_SUBSCORE; /* Return coldness of the region */ return DAMOS_MAX_SCORE - hotness; }
fabiomsr/my-workshop
app/src/main/java/org/fabiomsr/mitaller/module/receipt/detail/ReceiptDetailFragmentPager.java
package org.fabiomsr.mitaller.module.receipt.detail; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.fabiomsr.mitaller.R; import org.fabiomsr.mitaller.app.base.BaseFragment; import org.fabiomsr.mitaller.domain.Receipt; import org.fabiomsr.mitaller.module.receipt.detail.adapter.ReceiptDetailPageAdapter; import butterknife.Bind; import butterknife.ButterKnife; public class ReceiptDetailFragmentPager extends BaseFragment { @Bind(R.id.detail_tab_layout) TabLayout mTabLayout; @Bind(R.id.receipt_view_pager) ViewPager mViewPager; /** * The fragment argument representing the item that this fragment * represents. */ public static final String ARG_RECEIPT = "receipt"; /** * Receipt content this fragment is presenting. */ private Receipt mReceipt; public static ReceiptDetailFragmentPager newInstance(Receipt receipt){ ReceiptDetailFragmentPager fragment = new ReceiptDetailFragmentPager(); Bundle args = new Bundle(); args.putParcelable(ARG_RECEIPT, receipt); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_raceipt_detail_pager, container, false); ButterKnife.bind(this, rootView); return rootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ReceiptDetailPageAdapter pageAdapter = new ReceiptDetailPageAdapter(getChildFragmentManager(), mReceipt); mViewPager.setAdapter(pageAdapter); mTabLayout.setupWithViewPager(mViewPager); } @Override protected void readArguments(@NonNull Bundle args) { mReceipt = getArguments().getParcelable(ARG_RECEIPT); } }
IOTechSystems/iotech-c-utils
include/iot/iot.h
// // Copyright (c) 2019-2020 IOTech Ltd // // SPDX-License-Identifier: Apache-2.0 // #ifndef _IOT_IOT_H_ #define _IOT_IOT_H_ /** * @file * @brief IOTech IOT API */ #include "iot/defs.h" #include "iot/data.h" #include "iot/config.h" #include "iot/base64.h" #include "iot/time.h" #include "iot/hash.h" #include "iot/component.h" #include "iot/container.h" #include "iot/logger.h" #include "iot/thread.h" #include "iot/json.h" #include "iot/scheduler.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Start IOT / Initialise IOT data */ extern void iot_init (void); /** * @brief Stop IOT / Cleanup IOT data */ extern void iot_fini (void); /** * @brief Load configuration from file * * The function to load a configuration from a file * * @param name Name of the configuration * @param uri URI for configuration file * @return Configuration string loaded from the file */ extern char * iot_file_config_loader (const char * name, const char * uri); /** * @brief Save configuration to file * * The function to save a configuration to a file * * @param name Name of the configuration * @param uri URI for configuration file * @param config Configuration string to save * @return Whether configuration saved successfully */ extern bool iot_file_config_saver (const char * name, const char * uri, const char * config); /** * @brief Load string from a file * * Function to return file contents as a NULL terminated string * * @param path File path * @return String loaded from the file (client needs to free) */ extern char * iot_file_read (const char * path); /** * @brief Write a string to a file * * Function to write a NULL terminated string to a file, overwriting any existing contents. * * @param path File path * @param str String to write * @return Whether the string was successfully written to the file */ extern bool iot_file_write (const char * path, const char * str); /** * @brief Delete a file * * Function to delete a file * * @param path File path * @return Whether the file was successfully deleted */ extern bool iot_file_delete (const char * path); /** * @brief Load binary data from a file * * Function to return a binary array of file contents * * @param path File path * @param len Length of returned binary array * @return Binary contents of file (client needs to free) */ extern uint8_t * iot_file_read_binary (const char * path, size_t * len); /** * @brief Write binary data to a file * * Function to write a binary of given size to a file, overwriting any existing contents * * @param path File path * @param binary The binary array to be written * @param len Length of binary array to be written * @return Whether the binary was successfully written to the file */ extern bool iot_file_write_binary (const char * path, const uint8_t * binary, size_t len); #ifdef __cplusplus } #endif #endif
qiqingfu/streamify-your-node-program
example/tools/merge-stream-async.js
var merge = require('merge-stream') var Stream = require('stream') var wait = Stream.Transform() var merged = merge(wait) setTimeout(function() { merged.add(createReadable('aBc').pipe(toUpperCase())) }, 10) setTimeout(function() { merged.add(createReadable('DeF').pipe(toLowerCase())) wait.end() }, 20) merged.pipe(process.stdout) function createReadable(s) { var source = s.split('') return Stream.Readable({ read: function () { process.nextTick(() => { this.push(source.shift() || null) }) }, }) } function toUpperCase() { return Stream.Transform({ transform: function (buf, enc, next) { next(null, buf.toString().toUpperCase()) }, }) } function toLowerCase() { return Stream.Transform({ transform: function (buf, enc, next) { next(null, buf.toString().toLowerCase()) }, }) }
tyaga001/Rest_Assured_API_Automation_Test
src/main/java/TestUtils/TestUtil.java
<filename>src/main/java/TestUtils/TestUtil.java package TestUtils; import java.io.File; import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Hashtable; import TestSetup.APISetUp; import io.restassured.specification.RequestSpecification; public class TestUtil extends APISetUp { public static RequestSpecification setFormParam(String arguments, RequestSpecification reqSpecs) { String[] listOfAruments = arguments.split(","); for (String singleArgumen : listOfAruments) { String[] keyValue = singleArgumen.split(":"); { String key = keyValue[0]; String value = keyValue[1]; // reqSpecs.body(arg0) reqSpecs.formParam(key, value); } } return reqSpecs; } public static void archiveTestReport() { String reportName = configProperty.getTestReportName(); String lastTestReportFilePath = System.getProperty("user.dir")+"/src/test/resources/testReports/"; String archiveReportPath = System.getProperty("user.dir")+"/src/test/resources/archivedTestReport/"; Date date = new Date(); SimpleDateFormat dateFormate = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss"); String formatedDate = dateFormate.format(date); String archiveTestReportName = formatedDate + "_" + reportName; File oldReport = new File(lastTestReportFilePath + reportName); File newFile = new File(archiveReportPath + archiveTestReportName); System.out.println(oldReport.exists()); if (oldReport.exists()) { System.out.println("inside if"); oldReport.renameTo(newFile); oldReport.delete(); } } }
pierre/collector
src/test/java/com/ning/metrics/collector/guice/TestHealthChecksModule.java
/* * Copyright 2010-2012 Ning, Inc. * * Ning 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 com.ning.metrics.collector.guice; import com.ning.metrics.collector.binder.config.CollectorConfig; import com.ning.metrics.collector.hadoop.processing.EventSpoolDispatcher; import com.ning.metrics.collector.hadoop.processing.PersistentWriterFactory; import com.ning.metrics.collector.hadoop.processing.WriterStats; import com.ning.metrics.collector.healthchecks.HadoopHealthCheck; import com.ning.metrics.collector.healthchecks.RealtimeHealthCheck; import com.ning.metrics.collector.healthchecks.WriterHealthCheck; import com.ning.metrics.collector.realtime.EventQueueProcessor; import com.ning.metrics.collector.realtime.EventQueueProcessorImpl; import com.ning.metrics.collector.realtime.GlobalEventQueueStats; import com.ning.metrics.serialization.hadoop.FileSystemAccess; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.yammer.metrics.reporting.AdminServlet; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; public class TestHealthChecksModule { @Test(groups = "fast") public void testConfigure() { try { final Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(FileSystemAccess.class).toInstance(Mockito.mock(FileSystemAccess.class)); bind(EventQueueProcessor.class).toInstance(Mockito.mock(EventQueueProcessorImpl.class)); bind(GlobalEventQueueStats.class).toInstance(Mockito.mock(GlobalEventQueueStats.class)); bind(EventSpoolDispatcher.class).toInstance(Mockito.mock(EventSpoolDispatcher.class)); bind(PersistentWriterFactory.class).toInstance(Mockito.mock(PersistentWriterFactory.class)); bind(WriterStats.class).toInstance(Mockito.mock(WriterStats.class)); bind(CollectorConfig.class).toInstance(Mockito.mock(CollectorConfig.class)); } }, new HealthChecksModule()); Assert.assertNotNull(injector.getBinding(AdminServlet.class)); Assert.assertNotNull(injector.getBinding(HadoopHealthCheck.class)); Assert.assertNotNull(injector.getBinding(RealtimeHealthCheck.class)); Assert.assertNotNull(injector.getBinding(WriterHealthCheck.class)); } catch (Exception e) { Assert.fail(e.getMessage()); } } }
nitrologic/emu
mame/src/mame/includes/namcos22.h
<filename>mame/src/mame/includes/namcos22.h<gh_stars>10-100 #define USE_NAMCOS22_SPEED_HACK #define GFX_CHAR 0 #define GFX_TEXTURE_TILE 1 #define GFX_SPRITE 2 extern enum namcos22_gametype { NAMCOS22_AIR_COMBAT22, NAMCOS22_ALPINE_RACER, NAMCOS22_CYBER_COMMANDO, NAMCOS22_CYBER_CYCLES, NAMCOS22_PROP_CYCLE, NAMCOS22_RAVE_RACER, NAMCOS22_RIDGE_RACER, NAMCOS22_RIDGE_RACER2, NAMCOS22_TIME_CRISIS, NAMCOS22_VICTORY_LAP, NAMCOS22_ACE_DRIVER, NAMCOS22_ALPINE_RACER_2, NAMCOS22_ALPINE_SURFER, NAMCOS22_TOKYO_WARS, NAMCOS22_AQUA_JET, NAMCOS22_DIRT_DASH } namcos22_gametype; #define NAMCOS22_NUM_ROWS 30 #define NAMCOS22_NUM_COLS 40 #define NAMCOS22_PALETTE_SIZE 0x8000 /*----------- defined in video/namcos22.c -----------*/ extern UINT32 *namcos22_cgram; extern UINT32 *namcos22_textram; extern UINT32 *namcos22_polygonram; extern UINT32 *namcos22_gamma; extern UINT32 *namcos22_vics_data; extern UINT32 *namcos22_vics_control; extern UINT32 *namcos22_czattr; extern UINT32 *namcos22_tilemapattr; WRITE16_HANDLER( namcos22_dspram16_bank_w ); READ16_HANDLER( namcos22_dspram16_r ); WRITE16_HANDLER( namcos22_dspram16_w ); READ32_HANDLER( namcos22_cgram_r ); WRITE32_HANDLER( namcos22_cgram_w ); READ32_HANDLER( namcos22_czram_r ); WRITE32_HANDLER( namcos22_czram_w ); WRITE32_HANDLER(namcos22_port800000_w); READ32_HANDLER( namcos22_paletteram_r ); WRITE32_HANDLER( namcos22_paletteram_w ); READ32_HANDLER( namcos22_textram_r ); WRITE32_HANDLER( namcos22_textram_w ); READ32_HANDLER( namcos22_gamma_r ); WRITE32_HANDLER( namcos22_gamma_w ); READ32_HANDLER( namcos22_dspram_r ); WRITE32_HANDLER( namcos22_dspram_w ); VIDEO_START( namcos22 ); VIDEO_UPDATE( namcos22 ); VIDEO_START( namcos22s ); VIDEO_UPDATE( namcos22s ); void namcos22_draw_direct_poly( running_machine *machine, const UINT16 *pSource ); extern UINT32 namcos22_point_rom_r( offs_t offs ); extern void namcos22_enable_slave_simulation( void );
Tecnarca/whitenoise-system
sdk/opendp/smartnoise/reader/rowset.py
import numpy as np import datetime import operator from opendp.smartnoise.report import Report class TypedRowset: """ Represents a typed rowset supporting the types used in differentially private query. """ def __init__(self, rows, types): """ Initialize rowset :param rows: A list of tuples representing rows, with the first tuple being the column names, and the rest being the rows of the rowset. :param types: A list of types for the columns """ header = [c.lower() for c in rows[0]] body = rows[1:] self.n_rows = len(body) # Columns may be anonymous, in which case we generate a unique name prefix = "Col" cur_col = 1 self.types = {} self.colnames = [] self.report = Report() for idx in range(len(header)): cname = header[idx] while cname == "???" or cname in self.types: cname = prefix + str(cur_col) cur_col += 1 self.types[cname] = types[idx] self.colnames.append(cname) # for quick lookup self.colidx = dict(list(zip(self.colnames, range(len(self.colnames))))) self.idxcol = dict(list(zip(range(len(self.colnames)), self.colnames))) self.m_cols = {} # Now read each row into separate columns tempcols = {} for cn in self.colnames: tempcols[cn] = [] for row in body: for idx in range(len(row)): cn = self.idxcol[idx] tempcols[cn].append(row[idx]) for cn in self.colnames: self[cn] = tempcols[cn] # verify all lengths the same if not all([len(self.m_cols[colname]) == len(body) for colname in self.colnames]): raise ValueError("Some columns have different number of rows!") def __str__(self): if len(self) == 0: return "(empty)" widths = [self.get_width(colname) + 3 for colname in self.colnames] header = [self.format_width(colname, width) for colname, width in zip(self.colnames, widths)] divider = ["-" * width for width in widths] rows = [header, divider] for idx in range(self.n_rows): row = [" " + self.format_width(self.m_cols[colname][idx], width - 1) for colname, width in zip(self.colnames, widths)] rows.append(row) return "\n".join([" " + "|".join(r) for r in rows]) def __len__(self): return self.n_rows def __getitem__(self, key): if isinstance(key, str): key = self.unescape(key) return self.m_cols[key] elif type(key) is int: return self[self.idxcol[key]] else: raise ValueError("Must use string or int to index the rowset") def __setitem__(self, key, value): if isinstance(key, str): key = self.unescape(key) if self.n_rows == 0: self.n_rows = len(value) if len(value) != self.n_rows: raise ValueError("Trying to add column with {0} rows to rowset with {1} rows".format(len(value), self.n_rows)) cn = key t = self.types[cn] if t == "string": self.m_cols[cn] = np.array([str(v) if v is not None else v for v in value]) elif t == "boolean": self.m_cols[cn] = np.array([bool(v) if v is not None else v for v in value]) elif t == "int": self.m_cols[cn] = np.array([int(v) if v is not None else v for v in value]) elif t == "float": self.m_cols[cn] = np.array([float(v) if v is not None else v for v in value]) elif t == "datetime": self.m_cols[cn] = np.array([datetime.datetime(v) if v is not None else None for v in value]) else: raise ValueError("Trying to load unknown type " + t) elif type(key) is int: self[self.idxcol[key]] = value else: raise ValueError("Must index by string or int") def filter(self, colname, relation, value): ops = {'>': operator.gt, '<': operator.lt, '>=': operator.ge, '<=': operator.le, '=': operator.eq} col = self[colname] types = [self.types[name] for name in self.colnames] rows = [tuple(self.colnames)] for idx in range(self.n_rows): if ops[relation](col[idx], value): rows.append(tuple(self[name][idx] for name in self.colnames)) filtered_rs = TypedRowset(rows, types) filtered_rs.report = self.report return filtered_rs def rows(self, header=True): return ([self.colnames] if header else []) + [tuple(self.m_cols[name][idx] for name in self.colnames) for idx in range(self.n_rows)] def get_width(self, colname): t = self.types[colname] if t == "string": return max([len(s) for s in self.m_cols[colname]]) elif t == "boolean": return 6 elif t == "datetime": return 10 elif t == "int": return int(max([4] + [np.floor(np.log10(abs(n))) + 1 for n in self.m_cols[colname] if n != 0])) elif t == "float": return int(max([4] + [np.floor(np.log10(abs(n))) + 5 for n in self.m_cols[colname] if n != 0] )) else: raise ValueError("Unknown type: " + t) def format_width(self, val, width): if type(val) is float: str_val = "{0:.3f}".format(val) else: str_val = str(val) if len(str_val) > width: str_val = str_val[:width] padding = "" else: padding = " " * (width - len(str_val)) if type(val) is float or type(val) is int: return padding[:(len(padding)-1)] + str_val + " " else: return str_val + padding def compare(self, other, ratio=0.05): for idx in range(len(self.colnames)): sval = self[idx] oval = other[idx] if self.types[self.idxcol[idx]] != other.types[other.idxcol[idx]]: return False if self.types[self.idxcol[idx]] in ["int", "float"]: lbound = np.multiply(sval, (1.0 - ratio)) ubound = np.multiply(sval, (1.0 + ratio)) if not all([l < o and u > o for l, u, o in zip(lbound, ubound, oval)]): return False else: if not all([s == o for s, o in zip(sval, oval)]): return False return True def unescape(self, value): # remove identifier escaping return value.replace('"', '').replace('`', '').replace('[', '').replace(']', '')
zxqfl/flix
main/test/ca/uwaterloo/flix/library/TestInt64.scala
/* * Copyright 2016 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ca.uwaterloo.flix.library import ca.uwaterloo.flix.api.Flix import ca.uwaterloo.flix.util.Options import org.scalatest.FunSuite class TestInt64 extends FunSuite { val options = Options.DefaultTest def runTest(input: String, output: Long) { val flix = new Flix().setOptions(options).addPath("main/src/library/Int64.flix").addStr(input) assertResult(output)(flix.solve().get.getConstant("r")) } test("maxValue.01") { val input = "def r: Int64 = Int64.maxValue()" runTest(input, Long.MaxValue) } test("minValue.01") { val input = "def r: Int64 = Int64.minValue()" runTest(input, Long.MinValue) } test("size.01") { val input = "def r: Int32 = Int64.size()" runTest(input, 64L) } test("min.01") { val input = "def r: Int64 = Int64.min(1i64, 2i64)" runTest(input, 1L) } test("min.02") { val input = "def r: Int64 = Int64.min(2i64, -1i64)" runTest(input, -1L) } test("min.03") { val input = "def r: Int64 = Int64.min(-33i64, -66i64)" runTest(input, -66L) } test("max.01") { val input = "def r: Int64 = Int64.max(48i64, 49i64)" runTest(input, 49L) } test("max.02") { val input = "def r: Int64 = Int64.max(4i64, -16i64)" runTest(input, 4L) } test("max.03") { val input = "def r: Int64 = Int64.max(-34i64, -16i64)" runTest(input, -16L) } test("abs.01") { val input = "def r: Int64 = Int64.abs(31i64)" runTest(input, 31L) } test("abs.02") { val input = "def r: Int64 = Int64.abs(-31i64)" runTest(input, 31L) } test("abs.03") { val input = "def r: Int64 = Int64.abs(0i64)" runTest(input, 0L) } test("abs.04") { val input = "def r: Int64 = Int64.abs(9223372036854775807i64)" runTest(input, Long.MaxValue) } test("abs.05") { val input = "def r: Int64 = Int64.abs(-9223372036854775807i64)" runTest(input, Long.MaxValue) } test("abs.06") { val input = "def r: Int64 = Int64.abs(-9223372036854775808i64)" runTest(input, -1L) } test("dist.01") { val input = "def r: Int64 = Int64.dist(31i64, -7i64)" runTest(input, 38L) } test("dist.02") { val input = "def r: Int64 = Int64.dist(-44i64, -1i64)" runTest(input, 43L) } test("dist.03") { val input = "def r: Int64 = Int64.dist(-2i64, -2i64)" runTest(input, 0L) } test("dist.04") { val input = "def r: Int64 = Int64.dist(-9223372036854775808i64, -1i64)" runTest(input, Long.MaxValue) } test("dist.05") { val input = "def r: Int64 = Int64.dist(-9223372036854775808i64, 0i64)" runTest(input, -1L) } test("dist.06") { val input = "def r: Int64 = Int64.dist(-9223372036854775803i64, 4i64)" runTest(input, Long.MaxValue) } test("dist.07") { val input = "def r: Int64 = Int64.dist(-9223372036854775803i64, 5i64)" runTest(input, -1L) } test("dist.08") { val input = "def r: Int64 = Int64.dist(-9223372035854765803i64, 1000010004i64)" runTest(input, Long.MaxValue) } test("dist.09") { val input = "def r: Int64 = Int64.dist(-9223372035854765803i64, 1000010005i64)" runTest(input, -1L) } test("compare.01") { val input = "def r: Int32 = Int64.compare(-1i64, 44i64)" runTest(input, -1) } test("compare.02") { val input = "def r: Int32 = Int64.compare(-1i64, -44i64)" runTest(input, 1) } test("compare.03") { val input = "def r: Int32 = Int64.compare(88i64, 88i64)" runTest(input, 0) } test("signum.01") { val input = "def r: Int32 = Int64.signum(-22i64)" runTest(input, -1) } test("signum.02") { val input = "def r: Int32 = Int64.signum(22i64)" runTest(input, 1) } test("signum.03") { val input = "def r: Int32 = Int64.signum(0i64)" runTest(input, 0) } test("logicalRightShift.01") { val input = "def r: Int64 = Int64.logicalRightShift(2233i64, 4)" runTest(input, 2233L >>> 4) } test("logicalRightShift.02") { val input = "def r: Int64 = Int64.logicalRightShift(22336688888i64, 33)" runTest(input, 22336688888L >>> 33) } test("logicalRightShift.03") { val input = "def r: Int64 = Int64.logicalRightShift(2233i64, -8)" runTest(input, 2233L >>> -8) } test("logicalRightShift.04") { val input = "def r: Int64 = Int64.logicalRightShift(2233i64, 4)" runTest(input, 2233L >>> 4) } test("logicalRightShift.05") { val input = "def r: Int64 = Int64.logicalRightShift(-1i64, 1)" runTest(input, -1L >>> 1) } test("logicalRightShift.06") { val input = "def r: Int64 = Int64.logicalRightShift(-358888899999i64, 4)" runTest(input, -358888899999L >>> 4) } test("logicalRightShift.07") { val input = "def r: Int64 = Int64.logicalRightShift(-277732323232i64, -2777)" runTest(input, -277732323232L >>> -2777) } test("logicalRightShift.08") { val input = "def r: Int64 = Int64.logicalRightShift(-23328384858i64, 64)" runTest(input, -23328384858L >>> 64) } test("logicalRightShift.09") { val input = "def r: Int64 = Int64.logicalRightShift(-27000000000000i64, 0)" runTest(input, -27000000000000L >>> 0) } test("logicalRightShift.10") { val input = "def r: Int64 = Int64.logicalRightShift(9223372036854775807i64, 1)" runTest(input, Long.MaxValue >>> 1) } test("logicalRightShift.11") { val input = "def r: Int64 = Int64.logicalRightShift(-9223372036854775808i64, 1)" runTest(input, Long.MinValue >>> 1) } test("bitCount.01") { val input = "def r: Int32 = Int64.bitCount(1990911889900134i64)" runTest(input, 25) } test("bitCount.02") { val input = "def r: Int32 = Int64.bitCount(-1i64)" runTest(input, 64) } test("bitCount.03") { val input = "def r: Int32 = Int64.bitCount(-999888888114322199i64)" runTest(input, 35) } test("bitCount.04") { val input = "def r: Int32 = Int64.bitCount(0i64)" runTest(input, 0) } test("bitCount.05") { val input = "def r: Int32 = Int64.bitCount(-9223372036854775808i64)" runTest(input, 1) } test("bitCount.06") { val input = "def r: Int32 = Int64.bitCount(-9223372036854775805i64)" runTest(input, 3) } test("bitCount.07") { val input = "def r: Int32 = Int64.bitCount(9223372036854775807i64)" runTest(input, 63) } test("bitCount.08") { val input = "def r: Int32 = Int64.bitCount(9223372036854775806i64)" runTest(input, 62) } test("bitCount.09") { val input = "def r: Int32 = Int64.bitCount(9223372036854775791i64)" runTest(input, 62) } test("rotateLeft.01") { val input = "def r: Int64 = Int64.rotateLeft(-99991001265258663i64, 7)" runTest(input, 5647895911756442879L) } test("rotateLeft.02") { val input = "def r: Int64 = Int64.rotateLeft(-983667729064i64, 24)" runTest(input, 1943538110990123007L) } test("rotateLeft.03") { val input = "def r: Int64 = Int64.rotateLeft(-983667729064i64, -104)" runTest(input, 1943538110990123007L) } test("rotateLeft.04") { val input = "def r: Int64 = Int64.rotateLeft(1478293001i64, 23)" runTest(input, 12400820494532608L) } test("rotateLeft.05") { val input = "def r: Int64 = Int64.rotateLeft(1478293001i64, -41)" runTest(input, 12400820494532608L) } test("rotateLeft.06") { val input = "def r: Int64 = Int64.rotateLeft(1478293001i64, 87)" runTest(input, 12400820494532608L) } test("rotateLeft.07") { val input = "def r: Int64 = Int64.rotateLeft(-1i64, -36678)" runTest(input, -1L) } test("rotateLeft.08") { val input = "def r: Int64 = Int64.rotateLeft(-1i64, 667)" runTest(input, -1L) } test("rotateLeft.09") { val input = "def r: Int64 = Int64.rotateLeft(-1i64, -11111)" runTest(input, -1L) } test("rotateLeft.10") { val input = "def r: Int64 = Int64.rotateLeft(-9223372036854775808i64, 3)" runTest(input, 4L) } test("rotateLeft.11") { val input = "def r: Int64 = Int64.rotateLeft(9223372036854775807i64, 2)" runTest(input, -3L) } test("rotateRight.01") { val input = "def r: Int64 = Int64.rotateRight(-99991001265258663i64, 57)" runTest(input, 5647895911756442879L) } test("rotateRight.02") { val input = "def r: Int64 = Int64.rotateRight(-983667729064i64, 40)" runTest(input, 1943538110990123007L) } test("rotateRight.03") { val input = "def r: Int64 = Int64.rotateRight(-983667729064i64, -88)" runTest(input, 1943538110990123007L) } test("rotateRight.04") { val input = "def r: Int64 = Int64.rotateRight(1478293001i64, 41)" runTest(input, 12400820494532608L) } test("rotateRight.05") { val input = "def r: Int64 = Int64.rotateRight(1478293001i64, -23)" runTest(input, 12400820494532608L) } test("rotateRight.06") { val input = "def r: Int64 = Int64.rotateRight(1478293001i64, 105)" runTest(input, 12400820494532608L) } test("rotateRight.07") { val input = "def r: Int64 = Int64.rotateRight(-1i64, -36678)" runTest(input, -1L) } test("rotateRight.08") { val input = "def r: Int64 = Int64.rotateRight(-1i64, 667)" runTest(input, -1L) } test("rotateRight.09") { val input = "def r: Int64 = Int64.rotateRight(-1i64, -11111)" runTest(input, -1L) } test("rotateRight.10") { val input = "def r: Int64 = Int64.rotateRight(-9223372036854775808i64, 3)" runTest(input, 1152921504606846976L) } test("rotateRight.11") { val input = "def r: Int64 = Int64.rotateRight(9223372036854775807i64, 2)" runTest(input, -2305843009213693953L) } test("highestOneBitPosition.01") { val input = "def r: Int32 = Int64.highestOneBitPosition(-1i64)" runTest(input, 63) } test("highestOneBitPosition.02") { val input = "def r: Int32 = Int64.highestOneBitPosition(-9223372036854775808i64)" runTest(input, 63) } test("highestOneBitPosition.03") { val input = "def r: Int32 = Int64.highestOneBitPosition(1i64)" runTest(input, 0) } test("highestOneBitPosition.04") { val input = "def r: Int32 = Int64.highestOneBitPosition(2i64)" runTest(input, 1) } test("highestOneBitPosition.05") { val input = "def r: Int32 = Int64.highestOneBitPosition(3i64)" runTest(input, 1) } test("highestOneBitPosition.06") { val input = "def r: Int32 = Int64.highestOneBitPosition(20i64)" runTest(input, 4) } test("highestOneBitPosition.07") { val input = "def r: Int32 = Int64.highestOneBitPosition(2i64 ** 30i64)" runTest(input, 30) } test("highestOneBitPosition.08") { val input = "def r: Int32 = Int64.highestOneBitPosition(9223372036854775807i64)" runTest(input, 62) } test("highestOneBitPosition.09") { val input = "def r: Int32 = Int64.highestOneBitPosition(0i64)" runTest(input, -1) } test("highestOneBitPosition.10") { val input = "def r: Int32 = Int64.highestOneBitPosition(2i64 ** 23i64 + 2i64 ** 60i64)" runTest(input, 60) } test("highestOneBitPosition.11") { val input = "def r: Int32 = Int64.highestOneBitPosition(2i64 ** 20i64 + 2i64 ** 59i64)" runTest(input, 59) } test("highestOneBitPosition.12") { val input = "def r: Int32 = Int64.highestOneBitPosition(-44556677i64)" runTest(input, 63) } test("highestOneBit.01") { val input = "def r: Int64 = Int64.highestOneBit(-1i64)" runTest(input, Long.MinValue) } test("highestOneBit.02") { val input = "def r: Int64 = Int64.highestOneBit(-9223372036854775808i64)" runTest(input, Long.MinValue) } test("highestOneBit.03") { val input = "def r: Int64 = Int64.highestOneBit(-778899i64)" runTest(input, Long.MinValue) } test("highestOneBit.04") { val input = "def r: Int64 = Int64.highestOneBit(2i64)" runTest(input, 2L) } test("highestOneBit.05") { val input = "def r: Int64 = Int64.highestOneBit(3i64)" runTest(input, 2L) } test("highestOneBit.06") { val input = "def r: Int64 = Int64.highestOneBit(20i64)" runTest(input, 16L) } test("highestOneBit.07") { val input = "def r: Int64 = Int64.highestOneBit(2i64 ** 57i64 + 2i64 ** 32i64)" runTest(input, 144115188075855872L) } test("highestOneBit.08") { val input = "def r: Int64 = Int64.highestOneBit(9223372036854775807i64)" runTest(input, 4611686018427387904L) } test("highestOneBit.09") { val input = "def r: Int64 = Int64.highestOneBit(0i64)" runTest(input, 0L) } test("highestOneBit.10") { val input = "def r: Int64 = Int64.highestOneBit(2i64 ** 44i64 + 2i64 ** 18i64)" runTest(input, 17592186044416L) } test("numberOfLeadingZeros.01") { val input = "def r: Int32 = Int64.numberOfLeadingZeros(0i64)" runTest(input, 64) } test("numberOfLeadingZeros.02") { val input = "def r: Int32 = Int64.numberOfLeadingZeros(-9223372036854775808i64)" runTest(input, 0) } test("numberOfLeadingZeros.03") { val input = "def r: Int32 = Int64.numberOfLeadingZeros(-1i64)" runTest(input, 0) } test("numberOfLeadingZeros.04") { val input = "def r: Int32 = Int64.numberOfLeadingZeros(9223372036854775807i64)" runTest(input, 1) } test("numberOfLeadingZeros.05") { val input = "def r: Int32 = Int64.numberOfLeadingZeros(2i64 ** 62i64)" runTest(input, 1) } test("numberOfLeadingZeros.06") { val input = "def r: Int32 = Int64.numberOfLeadingZeros(2i64 ** 61i64 + 2i64 ** 18i64)" runTest(input, 2) } test("numberOfLeadingZeros.07") { val input = "def r: Int32 = Int64.numberOfLeadingZeros(2i64 ** 20i64 + 2i64 ** 18i64)" runTest(input, 43) } test("numberOfLeadingZeros.08") { val input = "def r: Int32 = Int64.numberOfLeadingZeros(20i64)" runTest(input, 59) } test("numberOfLeadingZeros.09") { val input = "def r: Int32 = Int64.numberOfLeadingZeros(1i64)" runTest(input, 63) } test("lowestOneBitPosition.01") { val input = "def r: Int32 = Int64.lowestOneBitPosition(-1i64)" runTest(input, 0) } test("lowestOneBitPosition.02") { val input = "def r: Int32 = Int64.lowestOneBitPosition(-9223372036854775808i64)" runTest(input, 63) } test("lowestOneBitPosition.03") { val input = "def r: Int32 = Int64.lowestOneBitPosition(1i64)" runTest(input, 0) } test("lowestOneBitPosition.04") { val input = "def r: Int32 = Int64.lowestOneBitPosition(2i64)" runTest(input, 1) } test("lowestOneBitPosition.05") { val input = "def r: Int32 = Int64.lowestOneBitPosition(3i64)" runTest(input, 0) } test("lowestOneBitPosition.06") { val input = "def r: Int32 = Int64.lowestOneBitPosition(4i64)" runTest(input, 2) } test("lowestOneBitPosition.07") { val input = "def r: Int32 = Int64.lowestOneBitPosition(12i64)" runTest(input, 2) } test("lowestOneBitPosition.08") { val input = "def r: Int32 = Int64.lowestOneBitPosition(2i64 ** 30i64)" runTest(input, 30) } test("lowestOneBitPosition.09") { val input = "def r: Int32 = Int64.lowestOneBitPosition(2i64 ** 57i64 + 2i64 ** 18i64)" runTest(input, 18) } test("lowestOneBitPosition.10") { val input = "def r: Int32 = Int64.lowestOneBitPosition(9223372036854775807i64)" runTest(input, 0) } test("lowestOneBitPosition.11") { val input = "def r: Int32 = Int64.lowestOneBitPosition(0i64)" runTest(input, -1) } test("lowestOneBit.01") { val input = "def r: Int64 = Int64.lowestOneBit(-1i64)" runTest(input, 1L) } test("lowestOneBit.02") { val input = "def r: Int64 = Int64.lowestOneBit(-9223372036854775808i64)" runTest(input, Long.MinValue) } test("lowestOneBit.03") { val input = "def r: Int64 = Int64.lowestOneBit(1i64)" runTest(input, 1L) } test("lowestOneBit.04") { val input = "def r: Int64 = Int64.lowestOneBit(2i64)" runTest(input, 2L) } test("lowestOneBit.05") { val input = "def r: Int64 = Int64.lowestOneBit(6i64)" runTest(input, 2L) } test("lowestOneBit.06") { val input = "def r: Int64 = Int64.lowestOneBit(12i64)" runTest(input, 4L) } test("lowestOneBit.07") { val input = "def r: Int64 = Int64.lowestOneBit(2i64 ** 6i64 + 2i64 ** 18i64 + 2i64 ** 27i64)" runTest(input, 64L) } test("lowestOneBit.08") { val input = "def r: Int64 = Int64.lowestOneBit(2i64 ** 54i64)" runTest(input, 18014398509481984L) } test("lowestOneBit.09") { val input = "def r: Int64 = Int64.lowestOneBit(2i64 ** 62i64 + 2i64 ** 18i64)" runTest(input, 262144L) } test("lowestOneBit.10") { val input = "def r: Int64 = Int64.lowestOneBit(9223372036854775807i64)" runTest(input, 1L) } test("lowestOneBit.11") { val input = "def r: Int64 = Int64.lowestOneBit(0i64)" runTest(input, 0L) } test("numberOfTrailingZeros.01") { val input = "def r: Int32 = Int64.numberOfTrailingZeros(0i64)" runTest(input, 64) } test("numberOfTrailingZeros.02") { val input = "def r: Int32 = Int64.numberOfTrailingZeros(3i64)" runTest(input, 0) } test("numberOfTrailingZeros.03") { val input = "def r: Int32 = Int64.numberOfTrailingZeros(42i64)" runTest(input, 1) } test("numberOfTrailingZeros.04") { val input = "def r: Int32 = Int64.numberOfTrailingZeros(2i64 ** 16i64 + 2i64 ** 22i64)" runTest(input, 16) } test("numberOfTrailingZeros.05") { val input = "def r: Int32 = Int64.numberOfTrailingZeros(2i64 ** 57i64)" runTest(input, 57) } test("numberOfTrailingZeros.06") { val input = "def r: Int32 = Int64.numberOfTrailingZeros(-1i64)" runTest(input, 0) } test("numberOfTrailingZeros.07") { val input = "def r: Int32 = Int64.numberOfTrailingZeros(-9223372036854775808i64)" runTest(input, 63) } test("bit.01") { val input = "def r: Int32 = Int64.bit(-1i64, 5)" runTest(input, 1) } test("bit.02") { val input = "def r: Int32 = Int64.bit(-1000000i64, 31)" runTest(input, 1) } test("bit.03") { val input = "def r: Int32 = Int64.bit(2i64 ** 23i64, 23)" runTest(input, 1) } test("bit.04") { val input = "def r: Int32 = Int64.bit(2i64 ** 23i64, 22)" runTest(input, 0) } test("bit.05") { val input = "def r: Int32 = Int64.bit(2i64 ** 23i64, 24)" runTest(input, 0) } test("bit.06") { val input = "def r: Int32 = Int64.bit(-1i64 - 2i64 ** 61i64, 61)" runTest(input, 0) } test("bit.07") { val input = "def r: Int32 = Int64.bit(-1i64 - 2i64 ** 61i64, 60)" runTest(input, 1) } test("bit.08") { val input = "def r: Int32 = Int64.bit(0i64, 17)" runTest(input, 0) } }
chenzhibini/common_module
common/src/main/java/com/hdyg/common/util/pay/WxApiWrapper.java
package com.hdyg.common.util.pay; import android.text.TextUtils; import com.hdyg.common.common.CommonModule; import com.tencent.mm.opensdk.openapi.IWXAPI; import com.tencent.mm.opensdk.openapi.WXAPIFactory; /** * @author CZB * @describe 微信工具 * @time 2020/4/9 11:42 */ public class WxApiWrapper { private static WxApiWrapper sInstance; private IWXAPI mApi; private String mAppID; private WxApiWrapper() { } public static WxApiWrapper getInstance() { if (sInstance == null) { synchronized (WxApiWrapper.class) { if (sInstance == null) { sInstance = new WxApiWrapper(); } } } return sInstance; } public void setAppID(String appID) { if (!TextUtils.isEmpty(appID)) { if (!appID.equals(mAppID) || mApi == null) { if (mApi != null) { mApi.unregisterApp(); } mAppID = appID; mApi = WXAPIFactory.createWXAPI(CommonModule.getAppContext(), appID); mApi.registerApp(appID); } } } public String getAppID() { return mAppID; } public IWXAPI getWxApi() { return mApi; } }
qipadabaitu/dawdler-series
dawdler/dawdler-client-plug-velocity/src/main/java/com/anywide/dawdler/clientplug/velocity/direct/XssUtil.java
<gh_stars>0 package com.anywide.dawdler.clientplug.velocity.direct; import org.jsoup.Jsoup; import org.jsoup.safety.Safelist; /** * @author jackson.song * @version V1.0 * @Title XssUtil.java * @date 2010年4月5日 * @email <EMAIL> */ public class XssUtil { private final static Safelist user_content_filter = Safelist.basic(); static { user_content_filter.addTags("embed", "object", "td", "param", "span", "div", "p", "strong", "b", "font", "img", "tr", "li", "th", "ul", "br", "h1", "h2", "h3", "h4", "h5", "h6", "ol", "table", "tbody"); user_content_filter.addAttributes(":all", "style", "type", "class", "id", "name", "color", "src", "width", "height"); user_content_filter.addAttributes("object", "width", "height", "classid", "codebase", "alert"); user_content_filter.addAttributes("param", "name", "value"); user_content_filter.addAttributes("embed", "src", "quality", "width", "height", "allowFullScreen", "allowScriptAccess", "flashvars", "name", "type", "pluginspage"); user_content_filter.addAttributes("a", "href"); } // 只去除ipt事件或脚本 保留以上定义的 public static String filterScript(String value) { if (value == null) { return null; } return Jsoup.clean(value, user_content_filter); } // 替换所有脚本 转换成&lt; &gt; 等等 public static String filter(String value) { if (value == null) { return null; } char[] content = value.toCharArray(); StringBuffer result = new StringBuffer(content.length + 30); for (int i = 0; i < content.length; i++) { switch (content[i]) { case '<': result.append("&lt;"); break; case '>': result.append("&gt;"); break; case '&': result.append("&amp;"); break; case '"': result.append("&quot;"); break; case '\'': result.append("&#39;"); break; default: result.append(content[i]); } } return result.toString(); } }
dainst/cilantro
service/staging/staging_controller.py
import os import logging import shutil import zipfile import json from flask import Blueprint, jsonify, request, send_file from werkzeug.utils import secure_filename from service.errors import ApiError from service.user.user_service import auth from utils import cilantro_info_file staging_controller = Blueprint('staging', __name__) staging_dir = os.environ['STAGING_DIR'] allowed_extensions = ['pdf', 'tif', 'tiff', 'zip', 'txt'] log = logging.getLogger(__name__) def _get_directory_structure(dir_path, depths=0): """ Recursively creates a dictionary of the directory structure (files and subdirectories) for dir_path. Arguments: dir_path: string - The root directory that should be evaluated. depths: int - The recursion depths, if you provide a negative value, the complete directory structure for dir_path is retrieved (default 0, only listing top level contents). """ tree = {} with os.scandir(dir_path) as it: for entry in sorted(it, key=lambda e: e.name): if entry.is_file(): tree[entry.name] = {"type": "file", "name": entry.name} else: tree[entry.name] = {"type": "directory", "name": entry.name} if depths != 0: path = os.path.join(dir_path, entry.name) # handle directories with legacy .info file, existence implies successful import if os.path.exists(os.path.join(path, ".info")): tree[entry.name]["job_info"] = {"status": "success", "msg": cilantro_info_file.DEFAULT_SUCCESS_MESSAGE} else: tree[entry.name]["job_info"] = _parse_info_file(os.path.join(path, cilantro_info_file.FILE_NAME)) tree[entry.name]["contents"] = _get_directory_structure(path, depths-1) return tree def _parse_info_file(path): if not os.path.exists(path): return None else: with open(path, 'r') as f: return json.load(f) @staging_controller.route('', methods=['GET'], strict_slashes=False, defaults={'path': '.'}) @staging_controller.route('/<path:path>', methods=['GET'], strict_slashes=False) @auth.login_required def get_path(path): """ Retrieve a file or folder content from the staging folder. Returns A JSON array containing all files, if it's a directory or the file's content if it's a file. .. :quickref: Staging Controller; Retrieve file/folder from staging folder **Example request**: .. sourcecode:: http GET /staging/<path>?depths=5 HTTP/1.1 **Example response ERROR**: .. sourcecode:: http HTTP/1.1 404 NOT FOUND { "error": { "code": "file_not_found", "message": "No resource was found under the path test" }, "success": false } :reqheader Accept: application/json :param str path: path to file :param int depths: the directory stucture depths to reteive at `path` (default: 1, returns direct subdirectories of path and their direct subdirectories.). If depths < 0 the complete subdirectory structure will be returned. :resheader Content-Type: application/json :status 200: array containing all file names, if it's a directory or the file's content if it's a file :status 404: file was not found """ depths = request.args.get('depths', 1, int) abs_path = _get_absolute_path(path) if os.path.isdir(abs_path): return jsonify(_get_directory_structure(abs_path, depths=depths)) elif os.path.isfile(abs_path): return send_file(abs_path) else: raise ApiError("file_not_found", f"No resource was found under the path {path}", 404) @staging_controller.route('/<path:path>', methods=['DELETE'], strict_slashes=False) @auth.login_required def delete_from_staging(path): """ Delete file or directory from the staging area. .. :quickref: Staging Controller; Delete file or dir from the staging area **Example request**: .. sourcecode:: http DELETE /staging/<path> HTTP/1.1 **Example response SUCCESS**: .. sourcecode:: http HTTP/1.1 200 OK { "success": true } **Example response ERROR**: .. sourcecode:: http HTTP/1.1 404 NOT FOUND { "error": { "code": "file_not_found", "message": "No resource was found under the path <path>" }, "success": false } :reqheader Accept: application/json :resheader Content-Type: application/json :param str path: path to file or directory to be deleted """ abs_path = _get_absolute_path(path) try: os.remove(abs_path) except (FileNotFoundError, IsADirectoryError): try: shutil.rmtree(abs_path) except FileNotFoundError: raise ApiError("file_not_found", f"No resource was found under the path {path}", 404) return jsonify({"success": True}), 200 @staging_controller.route('/folder', methods=['POST'], strict_slashes=False) @auth.login_required def create_folder(): """ Create folders in the staging area. Can be passed folders with subfolders separated by slashes. .. :quickref: Staging Controller; Upload files to the staging area **Example request**: .. sourcecode:: http POST /staging/folder HTTP/1.1 { "folderpath": "test-folder/subfolder" } **Example response SUCCESS**: .. sourcecode:: http HTTP/1.1 200 OK { "success": true } :reqheader Accept: application/json :<json string folderpath: folders to be created :resheader Content-Type: application/json :>json dict: operation result :status 200: OK :return: A JSON object containing the status of the operation """ if not request.data: raise ApiError("no_payload_found", "No request payload found") params = request.get_json(force=True) if not params['folderpath']: raise ApiError("param_not found", "Missing folderpath parameter") folderpath = params['folderpath'] try: os.makedirs( _get_absolute_path(folderpath), exist_ok=True ) return jsonify({"success": True}), 200 except Exception as e: return _generate_error_result( folderpath, "folder_creation_failed", "An unknown error occurred.", e) @staging_controller.route('', methods=['POST'], strict_slashes=False) @auth.login_required def upload_to_staging(): """ Upload files to the staging area. If the names of the given files contain folders, these are created in the staging area if not already present. Alternatively you can pass an extra argument 'target_folder' which is prepended to all passed file names. The upload endpoint is able to handle single and multiple files provided under any key. .. :quickref: Staging Controller; Upload files to the staging area **Example request**: .. sourcecode:: http POST /staging/ HTTP/1.1 **Example response SUCCESS**: .. sourcecode:: http HTTP/1.1 200 OK { "result": { "<filename>": { "success": true } } } **Example response ERROR**: .. sourcecode:: http HTTP/1.1 400 BAD REQUEST { "error": { "code": "no_files_provided", "message": "The request did not contain any files" }, "success": false } :reqheader Accept: multipart/form-data :formparam file: file to be uploaded :formparam target_folder: (optional) target folder for all files :resheader Content-Type: application/json :>json dict: operation result :status 200: OK :status 400: no files were provided :status 415: one of the files' extension is not allowed :return: a JSON object """ log.debug(f"Uploading {len(request.files)} files") results = {} if 'target_folder' in request.form: target_folder = request.form['target_folder'] else: target_folder = "" abs_path = _get_absolute_path(target_folder) if request.files: for key in request.files: for file in request.files.getlist(key): file.path = f"{abs_path}/{file.filename}" results[file.filename] = _process_file(file) return jsonify({"result": results}), 200 raise ApiError("no_files_provided", f"The request did not contain any files") @staging_controller.route('/move', methods=['POST'], strict_slashes=False) @auth.login_required def move(): """ Move a file or folder inside the staging area. Folders inside the target path must already exist. Uses :py:func:~os.rename. .. :quickref: Staging Controller; Move files inside the staging area **Example request**: .. sourcecode:: http POST /staging/move HTTP/1.1 { "source": "test-folder/file.txt", "target": "test-folder2/subfolder/" } **Example response SUCCESS**: .. sourcecode:: http HTTP/1.1 200 OK { "success": true } :reqheader Accept: application/json :<json string source: path of the file to be moved :<json string target: new path of the file to be moved :resheader Content-Type: application/json :>json dict: operation result :status 200: OK :return: A JSON object containing the status of the operation """ if not request.data: raise ApiError("no_payload_found", "No request payload found") params = request.get_json(force=True) if 'source' not in params: raise ApiError("param_not found", "Missing source parameter") if 'target' not in params: raise ApiError("param_not found", "Missing target parameter") source = _get_absolute_path(params['source']) target = _get_absolute_path(params['target']) try: os.rename(source, target) return jsonify({"success": True}), 200 except Exception as e: return _generate_error_result( source, "move_failed", "An unknown error occurred.", e) def _process_file(file): if not _is_allowed_file_extension(file.filename): return _generate_error_result( file, "extension_not_allowed", f"File extension '{_get_file_extension(file.filename)}'" f" is not allowed.") elif os.path.exists(file.path): return _generate_error_result( file, "file_already_exists", f"File already exists in folder.") else: try: _upload_file(file) if _get_file_extension(file.filename) == "zip": _unzip_file(file.path) return {"success": True} except Exception as e: return _generate_error_result( file, "upload_failed", "An unknown error occurred.", e) def _generate_error_result(file, code, message, e=None): log.error(f"Error during upload of {file.filename}. {message}.") if e: log.error(f" Cause: {str(e)}") return { "success": False, "error": { "code": code, "message": message} } def _upload_file(file): directory_structure, filename = os.path.split(file.path) os.makedirs(directory_structure, exist_ok=True) file.save(file.path) def _unzip_file(path): target_path = os.path.dirname(path) with zipfile.ZipFile(path, 'r') as zip_ref: zip_ref.extractall(target_path) os.remove(path) def _is_allowed_file_extension(filename): return _get_file_extension(filename) in allowed_extensions def _get_file_extension(filename): if '.' not in filename: return "" else: return filename.rsplit('.', 1)[1].lower() def _get_absolute_path(path): if auth.username() == "admin": return os.path.join(staging_dir, path) return os.path.join(staging_dir, auth.username(), path)
lujunzju/MachineLearningForAirTicketPredicting
Regression/RegressionKNN.py
# system library import numpy as np # user-library import RegressionBase # third-party library from sklearn import neighbors from sklearn.grid_search import GridSearchCV from sklearn.metrics import mean_squared_error from sklearn.learning_curve import validation_curve import matplotlib.pyplot as plt class RegressionKNN(RegressionBase.RegressionBase): def __init__(self, isTrain): super(RegressionKNN, self).__init__(isTrain) # data preprocessing #self.dataPreprocessing() # Create KNN regression object # first parameter is the K neighbors # 'uniform' assigns uniform weights to each neighbor # 'distance' assigns weights proportional to the inverse of the distance from the query point # default metric is euclidean distance self.regr = neighbors.KNeighborsRegressor(86, weights='distance') def dataPreprocessing(self): # due to the observation, standization does not help the optimization. # So do not use it! #self.Standardization() pass def parameterChoosing(self): # Set the parameters by cross-validation tuned_parameters = [{'weights': ['uniform', 'distance'], 'n_neighbors': range(2,100) } ] reg = GridSearchCV(neighbors.KNeighborsRegressor(), tuned_parameters, cv=5, scoring='mean_squared_error') reg.fit(self.X_train, self.y_train) print "Best parameters set found on development set:\n" print reg.best_params_ print "Grid scores on development set:\n" for params, mean_score, scores in reg.grid_scores_: print "%0.3f (+/-%0.03f) for %r\n" % (mean_score, scores.std() * 2, params) print reg.scorer_ print "MSE for test data set:" y_true, y_pred = self.y_test, reg.predict(self.X_test) print mean_squared_error(y_pred, y_true) def drawValidationCurve(self): """ To draw the validation curve :return:NA """ X, y = self.X_train, self.y_train.ravel() indices = np.arange(y.shape[0]) #np.random.shuffle(indices) X, y = X[indices], y[indices] train_sizes = range(2,100,2) train_scores, valid_scores = validation_curve(self.regr, X, y, "n_neighbors", train_sizes, cv=5, scoring='mean_squared_error') train_scores = -1.0/5*train_scores valid_scores = -1.0/5*valid_scores train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) valid_scores_mean = np.mean(valid_scores, axis=1) valid_scores_std = np.std(valid_scores, axis=1) plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(train_sizes, valid_scores_mean - valid_scores_std, valid_scores_mean + valid_scores_std, alpha=0.1, color="g") plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training MSE") plt.plot(train_sizes, valid_scores_mean, '*-', color="g", label="Cross-validation MSE") plt.legend(loc="best") plt.xlabel('K Neighbors') plt.ylabel('MSE') plt.title('Validation Curve with KNN Regression on the parameter of K Neighbors') plt.grid(True) plt.show() def training(self): # train the linear regression model self.regr.fit(self.X_train, self.y_train) def predict(self): # predict the test data self.y_pred = self.regr.predict(self.X_test) # print MSE mse = mean_squared_error(self.y_pred, self.y_test) print "MSE: {}".format(mse)
Kabimon/Streamis
streamis-jobmanager/streamis-job-manager/streamis-job-manager-base/src/main/java/com/webank/wedatasphere/streamis/jobmanager/manager/entity/StreamJobCodeResource.java
<gh_stars>0 package com.webank.wedatasphere.streamis.jobmanager.manager.entity; public class StreamJobCodeResource { private Long id; private Long jobVersionId; private Long bmlId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getJobVersionId() { return jobVersionId; } public void setJobVersionId(Long jobVersionId) { this.jobVersionId = jobVersionId; } public Long getBmlId() { return bmlId; } public void setBmlId(Long bmlId) { this.bmlId = bmlId; } }
SmallTianTian/dingtalk
model/oapi_enterprise_familydr_li.go
package model import ( "github.com/SmallTianTian/dingtalk/model/taobao" "github.com/SmallTianTian/dingtalk/utils" ) func NewOapiEnterpriseFamilydrListRequest() *OapiEnterpriseFamilydrListRequest { return &OapiEnterpriseFamilydrListRequest{} } type OapiEnterpriseFamilydrListRequest struct { taobao.SimpleTaobaoRequest taobao.SimpleResponse Resp OapiEnterpriseFamilydrListResponse CorpId string OrderBy string PageSize int64 PageStart int64 ReturnFields string StatDate string TopHttpMethod string TopResponseType string } func (this *OapiEnterpriseFamilydrListRequest) GetTopHttpMethod() string { return "POST" } func (this *OapiEnterpriseFamilydrListRequest) GetTopResponseType() string { return taobao.RESPONSE_TYPE_DINGTALK_OAPI } func (this *OapiEnterpriseFamilydrListRequest) SetCorpId(corpId2 string) { this.CorpId = corpId2 } func (this *OapiEnterpriseFamilydrListRequest) GetCorpId() string { return this.CorpId } func (this *OapiEnterpriseFamilydrListRequest) SetOrderBy(orderBy2 string) { this.OrderBy = orderBy2 } func (this *OapiEnterpriseFamilydrListRequest) GetOrderBy() string { return this.OrderBy } func (this *OapiEnterpriseFamilydrListRequest) SetPageSize(pageSize2 int64) { this.PageSize = pageSize2 } func (this *OapiEnterpriseFamilydrListRequest) GetPageSize() int64 { return this.PageSize } func (this *OapiEnterpriseFamilydrListRequest) SetPageStart(pageStart2 int64) { this.PageStart = pageStart2 } func (this *OapiEnterpriseFamilydrListRequest) GetPageStart() int64 { return this.PageStart } func (this *OapiEnterpriseFamilydrListRequest) SetReturnFields(returnFields2 string) { this.ReturnFields = returnFields2 } func (this *OapiEnterpriseFamilydrListRequest) GetReturnFields() string { return this.ReturnFields } func (this *OapiEnterpriseFamilydrListRequest) SetStatDate(statDate2 string) { this.StatDate = statDate2 } func (this *OapiEnterpriseFamilydrListRequest) GetStatDate() string { return this.StatDate } func (this *OapiEnterpriseFamilydrListRequest) GetApiMethodName() string { return "dingtalk.oapi.enterprise.familydr.list" } func (this *OapiEnterpriseFamilydrListRequest) SetTopResponseType(topResponseType2 string) { this.TopResponseType = topResponseType2 } func (this *OapiEnterpriseFamilydrListRequest) GetTopApiCallType() string { return "oapi" } func (this *OapiEnterpriseFamilydrListRequest) SetTopHttpMethod(topHttpMethod2 string) { this.TopHttpMethod = topHttpMethod2 } func (this *OapiEnterpriseFamilydrListRequest) SetHttpMethod(httpMethod string) { this.SetTopHttpMethod(httpMethod) } func (this *OapiEnterpriseFamilydrListRequest) GetTextParams() map[string]interface{} { txtParams := make(map[string]interface{}) txtParams["corp_id"] = this.CorpId txtParams["order_by"] = this.OrderBy txtParams["page_size"] = this.PageSize txtParams["page_start"] = this.PageStart txtParams["return_fields"] = this.ReturnFields txtParams["stat_date"] = this.StatDate return txtParams } func (this *OapiEnterpriseFamilydrListRequest) Check() *taobao.ApiRuleError { if err := utils.CheckNotEmpty(this.CorpId, "corpId"); err != nil { return err } return nil } func (this *OapiEnterpriseFamilydrListRequest) GetRespInstance() interface{} { return &this.Resp } func (this *OapiEnterpriseFamilydrListRequest) GetTaobaoResp() *taobao.TaobaoResponse { return &this.Resp.TaobaoResponse } type OrderBy struct { Field string `json:"field,omitempty"` Order string `json:"order,omitempty"` } type OapiEnterpriseFamilydrListResponse struct { taobao.TaobaoResponse Result []FamilyDoctorDataVo `json:"result,omitempty"` Success bool `json:"success,omitempty"` } type FamilyDoctorDataVo struct { CorpId string `json:"corp_id,omitempty"` DeptNameLv2 string `json:"dept_name_lv2,omitempty"` DeptNameLv3 string `json:"dept_name_lv3,omitempty"` LiveLaunchSuccUserCnt1d string `json:"live_launch_succ_user_cnt_1d,omitempty"` LiveLaunchSuccUserCnt1w string `json:"live_launch_succ_user_cnt_1w,omitempty"` LivePlayUserCnt1d string `json:"live_play_user_cnt_1d,omitempty"` LivePlayUserCnt1w string `json:"live_play_user_cnt_1w,omitempty"` StatDate string `json:"stat_date,omitempty"` }
smdb21/java-miape-api
src/main/java/org/proteored/miapeapi/cv/ms/DissociationMethod.java
<reponame>smdb21/java-miape-api package org.proteored.miapeapi.cv.ms; import org.proteored.miapeapi.cv.Accession; import org.proteored.miapeapi.cv.ControlVocabularyManager; import org.proteored.miapeapi.cv.ControlVocabularySet; public class DissociationMethod extends ControlVocabularySet { public static final Accession DISSOCIATION_METHOD_ACCESSION = new Accession("MS:1000044"); /* * ELECTRON_TRANSFER_DISSOCIATION("MS:1000598", * "electron transfer dissociation"), * COLLISION_INDUCED_DISSOCIATION("MS:1000133", * "collision-induced dissociation"), DISSOCIATION_METHOD("MS:1000044", * "dissociation method"), * BLACKBODY_INFRARED_RADIATIVE_DISSOCIATION("MS:1000242", * "blackbody infrared radiative dissociation"), * SUSTAINED_OFF_RESONANCE_IRRADIATION("MS:1000282", * "sustained off-resonance irradiation"), * INFRARED_MULTIPHOTON_DISSOCIATION("MS:1000262", * "infrared multiphoton dissociation"), * ELECTRON_CAPTURE_DISSOCIATION("MS:1000250", * "electron capture dissociation"), PHOTODISSOCIATION("MS:1000435", * "photodissociation"), * LOW_ENERGY_COLLISION_INDUCED_DISSOCIATION("MS:1000433", * "low-energy collision-induced dissociation"), * PLASMA_DESORPTION("MS:1000134", "plasma desorption"), * SURFACE_INDUCED_DISSOCIATION("MS:1000136", * "surface-induced dissociation"), POST_SOURCE_DECAY("MS:1000135", * "post-source decay"), PULSED_Q_DISSOCIATION("MS:1000599", * "pulsed q dissociation"), * HIGH_ENERGY_COLLISION_INDUCED_DISSOCIATION("MS:1000422", * "high-energy collision-induced dissociation"), ; */ private static DissociationMethod instance; public static DissociationMethod getInstance(ControlVocabularyManager cvManager) { if (instance == null) instance = new DissociationMethod(cvManager); return instance; } private DissociationMethod(ControlVocabularyManager cvManager) { super(cvManager); String[] parentAccessionsTMP = { "MS:1000044" }; this.parentAccessions = parentAccessionsTMP; this.miapeSection = 217; } }
nturay/quiet-dsp
examples/firdespm_example.c
// // firdespm_example.c // // This example demonstrates finite impulse response filter design // using the Parks-McClellan algorithm. // SEE ALSO: firdes_kaiser_example.c // #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <math.h> #include "liquid.h" #define OUTPUT_FILENAME "firdespm_example.m" // print usage/help message void usage() { printf("firdespm_example:\n"); printf(" u/h : print usage/help\n"); printf(" f : filter cutoff frequency, 0 < f < 0.5, default: 0.2\n"); printf(" t : filter transition bandwidth, 0 < t < 0.5, default: 0.1\n"); printf(" s : stop-band attenuation [dB], 0 < s, default: 60\n"); } int main(int argc, char*argv[]) { // options float fc=0.2f; // filter cutoff frequency float ft=0.1f; // filter transition float As=60.0f; // stop-band attenuation [dB] int dopt; while ((dopt = getopt(argc,argv,"uhf:t:s:")) != EOF) { switch (dopt) { case 'u': case 'h': usage(); return 0; case 'f': fc = atof(optarg); break; case 't': ft = atof(optarg); break; case 's': As = atof(optarg); break; default: exit(1); } } printf("filter design parameters\n"); printf(" cutoff frequency : %12.8f\n", fc); printf(" transition bandwidth : %12.8f\n", ft); printf(" stop-band attenuation [dB] : %12.8f\n", As); // derived values unsigned int h_len = estimate_req_filter_len(ft,As); printf("h_len : %u\n", h_len); float fp = fc - 0.5*ft; // pass-band cutoff frequency float fs = fc + 0.5*ft; // stop-band cutoff frequency liquid_firdespm_btype btype = LIQUID_FIRDESPM_BANDPASS; // derived values unsigned int num_bands = 2; float bands[4] = {0.0f, fp, fs, 0.5f}; float des[2] = {1.0f, 0.0f}; float weights[2] = {1.0f, 1.0f}; liquid_firdespm_wtype wtype[2] = {LIQUID_FIRDESPM_FLATWEIGHT, LIQUID_FIRDESPM_EXPWEIGHT}; unsigned int i; float h[h_len]; #if 0 firdespm q = firdespm_create(n,num_bands,bands,des,weights,wtype,btype); firdespm_print(q); firdespm_execute(q,h); firdespm_destroy(q); #else firdespm_run(h_len,num_bands,bands,des,weights,wtype,btype,h); #endif // print coefficients for (i=0; i<h_len; i++) printf("h(%4u) = %16.12f;\n", i+1, h[i]); // open output file FILE*fid = fopen(OUTPUT_FILENAME,"w"); fprintf(fid,"%% %s : auto-generated file\n", OUTPUT_FILENAME); fprintf(fid,"clear all;\n"); fprintf(fid,"close all;\n\n"); fprintf(fid,"h_len=%u;\n", h_len); fprintf(fid,"fc=%12.4e;\n",fc); fprintf(fid,"As=%12.4e;\n",As); for (i=0; i<h_len; i++) fprintf(fid,"h(%4u) = %20.8e;\n", i+1, h[i]); fprintf(fid,"nfft=1024;\n"); fprintf(fid,"H=20*log10(abs(fftshift(fft(h,nfft))));\n"); fprintf(fid,"f=[0:(nfft-1)]/nfft-0.5;\n"); fprintf(fid,"figure; plot(f,H,'Color',[0 0.5 0.25],'LineWidth',2);\n"); fprintf(fid,"grid on;\n"); fprintf(fid,"xlabel('normalized frequency');\n"); fprintf(fid,"ylabel('PSD [dB]');\n"); fprintf(fid,"title(['Filter design/Kaiser window f_c: %f, S_L: %f, h: %u']);\n", fc, -As, h_len); fprintf(fid,"axis([-0.5 0.5 -As-40 10]);\n"); fclose(fid); printf("results written to %s.\n", OUTPUT_FILENAME); printf("done.\n"); return 0; }
digital-ECMT/acuity-vahub
vahub-model/src/main/java/com/acuity/visualisations/rawdatamodel/service/event/SurgicalHistoryService.java
/* * Copyright 2021 The University of Manchester * * 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.acuity.visualisations.rawdatamodel.service.event; import com.acuity.visualisations.rawdatamodel.filters.SurgicalHistoryFilters; import com.acuity.visualisations.rawdatamodel.service.BaseEventService; import com.acuity.visualisations.rawdatamodel.service.ssv.SsvSummaryTableService; import com.acuity.visualisations.rawdatamodel.trellis.grouping.SurgicalHistoryGroupByOptions; import com.acuity.visualisations.rawdatamodel.vo.SurgicalHistoryRaw; import com.acuity.visualisations.rawdatamodel.vo.wrappers.SurgicalHistory; import com.acuity.va.security.acl.domain.Datasets; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import static com.acuity.visualisations.rawdatamodel.util.Column.DatasetType; @Service public class SurgicalHistoryService extends BaseEventService<SurgicalHistoryRaw, SurgicalHistory, SurgicalHistoryGroupByOptions> implements SsvSummaryTableService { @Override public List<Map<String, String>> getSingleSubjectData(Datasets datasets, String subjectId) { return getSingleSubjectData(datasets, subjectId, SurgicalHistoryFilters.empty()); } @Override public Map<String, String> getSingleSubjectColumns(DatasetType datasetType) { return ssvCommonService.getColumns(datasetType, SurgicalHistory.class, SurgicalHistoryRaw.class); } @Override public String getSsvTableName() { return "surgicalHistory"; } @Override public String getSsvTableDisplayName() { return "SURGICAL HISTORY"; } @Override public String getHeaderName() { return "PATIENT HISTORY"; } @Override public double getOrder() { return 4; } }