code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace GovITHub.Auth.Common.Services.Impl
{
/// <summary>
/// Base email sender
/// </summary>
public abstract class BaseEmailSender : IEmailSender
{
public EmailProviderSettings Settings { get; set; }
protected ILogger<EmailService> Logger { get; set; }
protected IHostingEnvironment Env { get; set; }
public abstract Task SendEmailAsync(string email, string subject, string message);
public BaseEmailSender(EmailProviderSettings settingsValue, ILogger<EmailService> logger, IHostingEnvironment env)
{
this.Logger = logger;
this.Env = env;
Settings = settingsValue;
}
/// <summary>
/// Build settings
/// </summary>
/// <param name="settingsValue">settings</param>
protected virtual void Build(string settingsValue)
{
if (string.IsNullOrEmpty(settingsValue))
{
throw new ArgumentNullException("settings");
}
Settings = JsonConvert.DeserializeObject<EmailProviderSettings>(settingsValue);
if (string.IsNullOrEmpty(Settings.Address))
{
throw new ArgumentNullException("settings.Address");
}
}
}
}
|
gov-ithub/auth-sso
|
src/GovITHub.Auth.Common/Services/Impl/BaseEmailSender.cs
|
C#
|
apache-2.0
| 1,437 |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.api.ads.admanager.jaxws.v202202;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
*
* An error that occurs while parsing {@link Statement} objects.
*
*
* <p>Java class for StatementError complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="StatementError">
* <complexContent>
* <extension base="{https://www.google.com/apis/ads/publisher/v202202}ApiError">
* <sequence>
* <element name="reason" type="{https://www.google.com/apis/ads/publisher/v202202}StatementError.Reason" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "StatementError", propOrder = {
"reason"
})
public class StatementError
extends ApiError
{
@XmlSchemaType(name = "string")
protected StatementErrorReason reason;
/**
* Gets the value of the reason property.
*
* @return
* possible object is
* {@link StatementErrorReason }
*
*/
public StatementErrorReason getReason() {
return reason;
}
/**
* Sets the value of the reason property.
*
* @param value
* allowed object is
* {@link StatementErrorReason }
*
*/
public void setReason(StatementErrorReason value) {
this.reason = value;
}
}
|
googleads/googleads-java-lib
|
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202202/StatementError.java
|
Java
|
apache-2.0
| 2,266 |
using System;
using NUnit.Framework;
using PCLActivitySet.Domain.Recurrence;
using PCLActivitySet.Dto.Recurrence;
namespace PCLActivitySet.Test.Domain.Recurrence
{
[TestFixture]
public class DateProjectionTest
{
[Test]
public void TranslateProjectionType()
{
const int periodCount = 1;
const EMonth month = EMonth.February;
const int dayOfMonth = 3;
const EDaysOfWeekExt dayOfWeekExt = EDaysOfWeekExt.Thursday;
const EDaysOfWeekFlags dayOfWeekFlags = EDaysOfWeekFlags.Friday;
const EWeeksInMonth weekInMonth = EWeeksInMonth.Last;
DateProjection prj = new DateProjection(EDateProjectionType.Daily)
{
PeriodCount = periodCount,
Month = month,
DayOfMonth = dayOfMonth,
DaysOfWeekExt = dayOfWeekExt,
DaysOfWeekFlags = dayOfWeekFlags,
WeeksInMonth = weekInMonth,
};
prj.ProjectionType = EDateProjectionType.Weekly;
Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Weekly"));
prj.ProjectionType = EDateProjectionType.Monthly;
Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Monthly"));
prj.ProjectionType = EDateProjectionType.MonthlyRelative;
Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Monthly Relative"));
prj.ProjectionType = EDateProjectionType.Yearly;
Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Yearly"));
prj.ProjectionType = EDateProjectionType.YearlyRelative;
Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Yearly Relative"));
prj.ProjectionType = EDateProjectionType.Daily;
Assert.That(DateProjection.ToShortDescription(prj), Is.EqualTo("Daily"));
Assert.That(prj.PeriodCount, Is.EqualTo(periodCount));
Assert.That(prj.Month, Is.EqualTo(month));
Assert.That(prj.DayOfMonth, Is.EqualTo(dayOfMonth));
Assert.That(prj.DaysOfWeekExt, Is.EqualTo(dayOfWeekExt));
Assert.That(prj.DaysOfWeekFlags, Is.EqualTo(dayOfWeekFlags));
Assert.That(prj.WeeksInMonth, Is.EqualTo(weekInMonth));
Assert.That(DateProjection.ToShortDescription(null), Is.EqualTo("None"));
}
[Test]
public void TranslateToInvalidProjectionType()
{
var prj = new DateProjection();
Assert.That(() => prj.ProjectionType = (EDateProjectionType) int.MaxValue, Throws.TypeOf<InvalidOperationException>());
}
}
}
|
Merlin9999/PCLActivitySet
|
src/PCLActivitySet/PCLActivitySet.Test/Domain/Recurrence/DateProjectionTest.cs
|
C#
|
apache-2.0
| 2,704 |
using System;
using CJia.Net.Communication;
using CJia.Net.Tcp;
using CJia.Net.Communication.Messengers;
using CJia.Net.Client;
namespace CJia.Net.Server
{
/// <summary>
/// Represents a client from a perspective of a server.
/// </summary>
public interface IServerClient : IMessenger
{
/// <summary>
/// This event is raised when client disconnected from server.
/// </summary>
event EventHandler Disconnected;
/// <summary>
/// Unique identifier for this client in server.
/// </summary>
long ClientId { get; }
///<summary>
/// Gets endpoint of remote application.
///</summary>
CJiaEndPoint RemoteEndPoint { get; }
/// <summary>
/// Gets the current communication state.
/// </summary>
CommunicationStates CommunicationState { get; }
/// <summary>
/// Disconnects from server.
/// </summary>
void Disconnect();
}
}
|
leborety/CJia
|
CJia.Framework/CJia.Net/Server/IServerClient.cs
|
C#
|
apache-2.0
| 1,018 |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: sample-weight-meta.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='sample-weight-meta.proto',
package='com.webank.ai.fate.common.mlmodel.buffer',
syntax='proto3',
serialized_options=_b('B\025SampleWeightMetaProto'),
serialized_pb=_b('\n\x18sample-weight-meta.proto\x12(com.webank.ai.fate.common.mlmodel.buffer\"S\n\x10SampleWeightMeta\x12\x10\n\x08need_run\x18\x01 \x01(\x08\x12\x1a\n\x12sample_weight_name\x18\x02 \x01(\t\x12\x11\n\tnormalize\x18\x03 \x01(\x08\x42\x17\x42\x15SampleWeightMetaProtob\x06proto3')
)
_SAMPLEWEIGHTMETA = _descriptor.Descriptor(
name='SampleWeightMeta',
full_name='com.webank.ai.fate.common.mlmodel.buffer.SampleWeightMeta',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='need_run', full_name='com.webank.ai.fate.common.mlmodel.buffer.SampleWeightMeta.need_run', index=0,
number=1, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='sample_weight_name', full_name='com.webank.ai.fate.common.mlmodel.buffer.SampleWeightMeta.sample_weight_name', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='normalize', full_name='com.webank.ai.fate.common.mlmodel.buffer.SampleWeightMeta.normalize', index=2,
number=3, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=70,
serialized_end=153,
)
DESCRIPTOR.message_types_by_name['SampleWeightMeta'] = _SAMPLEWEIGHTMETA
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
SampleWeightMeta = _reflection.GeneratedProtocolMessageType('SampleWeightMeta', (_message.Message,), {
'DESCRIPTOR' : _SAMPLEWEIGHTMETA,
'__module__' : 'sample_weight_meta_pb2'
# @@protoc_insertion_point(class_scope:com.webank.ai.fate.common.mlmodel.buffer.SampleWeightMeta)
})
_sym_db.RegisterMessage(SampleWeightMeta)
DESCRIPTOR._options = None
# @@protoc_insertion_point(module_scope)
|
FederatedAI/FATE
|
python/federatedml/protobuf/generated/sample_weight_meta_pb2.py
|
Python
|
apache-2.0
| 3,206 |
/*
Copyright 2022 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.kubernetes.client.openapi.models;
/** Generated */
public interface V1beta1CronJobSpecFluent<
A extends io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent<A>>
extends io.kubernetes.client.fluent.Fluent<A> {
public java.lang.String getConcurrencyPolicy();
public A withConcurrencyPolicy(java.lang.String concurrencyPolicy);
public java.lang.Boolean hasConcurrencyPolicy();
/** Method is deprecated. use withConcurrencyPolicy instead. */
@java.lang.Deprecated
public A withNewConcurrencyPolicy(java.lang.String original);
public java.lang.Integer getFailedJobsHistoryLimit();
public A withFailedJobsHistoryLimit(java.lang.Integer failedJobsHistoryLimit);
public java.lang.Boolean hasFailedJobsHistoryLimit();
/**
* This method has been deprecated, please use method buildJobTemplate instead.
*
* @return The buildable object.
*/
@java.lang.Deprecated
public io.kubernetes.client.openapi.models.V1beta1JobTemplateSpec getJobTemplate();
public io.kubernetes.client.openapi.models.V1beta1JobTemplateSpec buildJobTemplate();
public A withJobTemplate(io.kubernetes.client.openapi.models.V1beta1JobTemplateSpec jobTemplate);
public java.lang.Boolean hasJobTemplate();
public io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<A>
withNewJobTemplate();
public io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<A>
withNewJobTemplateLike(io.kubernetes.client.openapi.models.V1beta1JobTemplateSpec item);
public io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<A>
editJobTemplate();
public io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<A>
editOrNewJobTemplate();
public io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<A>
editOrNewJobTemplateLike(io.kubernetes.client.openapi.models.V1beta1JobTemplateSpec item);
public java.lang.String getSchedule();
public A withSchedule(java.lang.String schedule);
public java.lang.Boolean hasSchedule();
/** Method is deprecated. use withSchedule instead. */
@java.lang.Deprecated
public A withNewSchedule(java.lang.String original);
public java.lang.Long getStartingDeadlineSeconds();
public A withStartingDeadlineSeconds(java.lang.Long startingDeadlineSeconds);
public java.lang.Boolean hasStartingDeadlineSeconds();
public java.lang.Integer getSuccessfulJobsHistoryLimit();
public A withSuccessfulJobsHistoryLimit(java.lang.Integer successfulJobsHistoryLimit);
public java.lang.Boolean hasSuccessfulJobsHistoryLimit();
public java.lang.Boolean getSuspend();
public A withSuspend(java.lang.Boolean suspend);
public java.lang.Boolean hasSuspend();
public interface JobTemplateNested<N>
extends io.kubernetes.client.fluent.Nested<N>,
io.kubernetes.client.openapi.models.V1beta1JobTemplateSpecFluent<
io.kubernetes.client.openapi.models.V1beta1CronJobSpecFluent.JobTemplateNested<N>> {
public N and();
public N endJobTemplate();
}
}
|
kubernetes-client/java
|
fluent/src/main/java/io/kubernetes/client/openapi/models/V1beta1CronJobSpecFluent.java
|
Java
|
apache-2.0
| 3,688 |
package com.github.hayataka.hibernatevalidatorsample.context;
import java.io.Closeable;
/**
* tryでのresourceCloseを行うための仕組
* @author hayakawatakahiko
*/
interface AutoCloseable extends Closeable {
/**
* 開放すべきリソースを閉じる処理.
*/
void close();
}
|
hayataka/hibernateValidatorSample
|
src/main/java/com/github/hayataka/hibernatevalidatorsample/context/AutoCloseable.java
|
Java
|
apache-2.0
| 297 |
// +build windows
package handlers
import (
"syscall"
"golang.org/x/crypto/ssh"
)
var SyscallSignals = map[ssh.Signal]syscall.Signal{
ssh.SIGABRT: syscall.SIGABRT,
ssh.SIGALRM: syscall.SIGALRM,
ssh.SIGFPE: syscall.SIGFPE,
ssh.SIGHUP: syscall.SIGHUP,
ssh.SIGILL: syscall.SIGILL,
ssh.SIGINT: syscall.SIGINT,
ssh.SIGKILL: syscall.SIGKILL,
ssh.SIGPIPE: syscall.SIGPIPE,
ssh.SIGQUIT: syscall.SIGQUIT,
ssh.SIGSEGV: syscall.SIGSEGV,
ssh.SIGTERM: syscall.SIGTERM,
}
var SSHSignals = map[syscall.Signal]ssh.Signal{
syscall.SIGABRT: ssh.SIGABRT,
syscall.SIGALRM: ssh.SIGALRM,
syscall.SIGFPE: ssh.SIGFPE,
syscall.SIGHUP: ssh.SIGHUP,
syscall.SIGILL: ssh.SIGILL,
syscall.SIGINT: ssh.SIGINT,
syscall.SIGKILL: ssh.SIGKILL,
syscall.SIGPIPE: ssh.SIGPIPE,
syscall.SIGQUIT: ssh.SIGQUIT,
syscall.SIGSEGV: ssh.SIGSEGV,
syscall.SIGTERM: ssh.SIGTERM,
}
|
cloudfoundry-incubator/diego-ssh-windows
|
handlers/signals_windows.go
|
GO
|
apache-2.0
| 867 |
/*
* Copyright 2005-2017 Dozer 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 org.dozer.vo.interfacerecursion;
/**
* @author Christoph Goldner
*/
public interface UserPrime {
String getFirstName();
void setFirstName(String aFirstName);
String getLastName();
void setLastName(String aLastName);
UserGroupPrime getUserGroup();
void setUserGroup(UserGroupPrime aUserGroup);
}
|
STRiDGE/dozer
|
core/src/test/java/org/dozer/vo/interfacerecursion/UserPrime.java
|
Java
|
apache-2.0
| 973 |
package ludum.mighty.ld36.animations;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import ludum.mighty.ld36.settings.DefaultValues;
public class AnimatorSonicBoom {
private Texture kidTexture;
private TextureRegion[][] kidTR;
private TextureRegion[][] kidTRflip;
public Animation animUP, animDOWN, animLEFT, animRIGHT,
animStopUP, animStopDOWN, animStopLEFT, animStopRIGHT,
animNE, animNW, animSE, animSW,
animStopNE, animStopNW, animStopSE, animStopSW,
anim;
public AnimatorSonicBoom(String textureSheet) {
kidTexture = new Texture(textureSheet);
kidTR = TextureRegion.split(kidTexture, DefaultValues.TILESIZE, DefaultValues.TILESIZE);
kidTRflip = TextureRegion.split(kidTexture, DefaultValues.TILESIZE, DefaultValues.TILESIZE);
kidTRflip[2][7].flip(true, false);
kidTRflip[2][8].flip(true, false);
kidTRflip[2][9].flip(true, false);
kidTRflip[3][7].flip(true, false);
kidTRflip[3][8].flip(true, false);
kidTRflip[3][9].flip(true, false);
kidTRflip[4][7].flip(true, false);
kidTRflip[4][8].flip(true, false);
kidTRflip[4][9].flip(true, false);
// Create animations for movement
animDOWN = new Animation(0.25f, kidTR[5][7], kidTR[5][8], kidTR[5][9], kidTR[5][7]);
animRIGHT = new Animation(0.25f, kidTR[4][7], kidTR[4][8], kidTR[4][9], kidTR[4][7]);
animUP = new Animation(0.25f, kidTR[1][7], kidTR[1][8], kidTR[1][9], kidTR[1][7]);
animLEFT = new Animation(0.25f, kidTRflip[4][7], kidTRflip[4][8], kidTRflip[4][9], kidTRflip[4][7]);
animNE = new Animation(0.25f, kidTR[2][7], kidTR[2][8], kidTR[2][9], kidTR[2][7]);
animNW = new Animation(0.25f, kidTRflip[2][7], kidTRflip[2][8], kidTRflip[2][9], kidTRflip[2][7]);
animSE = new Animation(0.25f, kidTR[3][7], kidTR[3][8], kidTR[3][9], kidTR[3][7]);
animSW = new Animation(0.25f, kidTRflip[3][7], kidTRflip[3][8], kidTRflip[3][9], kidTRflip[3][7]);
animStopDOWN = new Animation(0.25f, kidTR[5][7]);
animStopRIGHT = new Animation(0.25f, kidTR[4][7]);
animStopUP = new Animation(0.25f, kidTR[1][7]);
animStopLEFT = new Animation(0.25f, kidTRflip[4][7]);
animStopNE = new Animation(0.25f, kidTR[2][7]);
animStopNW = new Animation(0.25f, kidTRflip[2][7]);
animStopSE = new Animation(0.25f, kidTR[3][7]);
animStopSW = new Animation(0.25f, kidTRflip[3][7]);
// Set initial position of the kid
anim = animStopDOWN;
}
}
|
punkto/mightyLD36
|
core/src/ludum/mighty/ld36/animations/AnimatorSonicBoom.java
|
Java
|
apache-2.0
| 2,485 |
#include "arg_conversion.h"
#include "command_buffer.h"
static command_buffer buffer;
int piss_off(int a, double b) {
return printf("piss_off called with %d, %f\n", a, b);
}
static const char piss_off_usage[] = "piss_off int double\nYell numbers!";
void kill_player(const std::string& name) {
printf("Killing player \"%s\"\n", name.c_str());
}
static const char kill_usage[] = "kill player_name";
int main() {
function_mapping fm;
fm.add_mapping("howdy", piss_off, piss_off_usage);
fm.add_mapping("kill", kill_player, kill_usage);
buffer.push_command("howdy 5 6.2");
buffer.push_command("no_such_command arg1");
buffer.push_command("kill jared 5");
buffer.push_command("kill jared");
fm.execute_command(buffer.pop_command());
fm.execute_command(buffer.pop_command());
fm.execute_command(buffer.pop_command());
fm.execute_command(buffer.pop_command());
}
|
n00btime/gen_wrapper
|
my_test.cpp
|
C++
|
apache-2.0
| 871 |
package com.joey.bak.base.ui;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.joe.zatuji.MyApplication;
import com.joe.zatuji.R;
import com.joe.zatuji.base.BasePresenter;
import com.joe.zatuji.base.LoadingView;
import com.joe.zatuji.utils.KToast;
import com.joe.zatuji.utils.TUtil;
import com.joe.zatuji.view.LoadingDialog;
import com.squareup.leakcanary.RefWatcher;
/**
* Created by Joe on 2016/4/16.
*/
public abstract class BaseFragment<T extends BasePresenter> extends android.support.v4.app.Fragment implements LoadingView {
protected Activity mActivity;
protected View mRootView;
protected AlertDialog dialog;
protected MyApplication myApplication;
protected LoadingDialog mLoadingDialog;
protected T mPresenter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mActivity=getActivity();
this.myApplication= (MyApplication) mActivity.getApplication();
//initLeakCanary();
onSaveFragmentInstance(savedInstanceState);
initLoading();
}
private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN";
private void onSaveFragmentInstance(Bundle savedInstanceState) {
if (savedInstanceState != null) {
boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN);
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (isSupportHidden) {
ft.hide(this);
} else {
ft.show(this);
}
ft.commit();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_SAVE_IS_HIDDEN,isHidden());
}
protected void initLeakCanary(){
RefWatcher refWatcher = MyApplication.getRefWatcher(mActivity);
refWatcher.watch(this);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.mActivity=getActivity();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRootView = inflater.inflate(getLayout(),null);
initPM();
initView();
initPresenter();
initListener();
return mRootView;
}
protected void initPM() {
mPresenter = TUtil.getT(this,0);
if(mPresenter!=null) mPresenter.onStart();
}
protected void initLoading() {
dialog = new AlertDialog.Builder(mActivity).create();
}
protected void initListener() {
}
protected abstract int getLayout();
protected void initView(){
}
protected abstract void initPresenter();
@Override
public void showLoading() {
View loadingView=View.inflate(mActivity, R.layout.dialog_loading,null);
dialog.setContentView(loadingView);
dialog.show();
}
@Override
public void doneLoading() {
if(mLoadingDialog!=null){
mLoadingDialog.dismiss();
}
// dialog.dismiss();
}
@Override
public void showError(String str) {
KToast.show(str);
}
protected void showEmptyView(){
}
public void showLoading(String msg){
if(mLoadingDialog==null) mLoadingDialog = new LoadingDialog(mActivity,msg);
mLoadingDialog.setMessage(msg);
mLoadingDialog.show();
}
@Override
public void onDestroy() {
super.onDestroy();
if(mPresenter!=null) mPresenter.onRemove();
}
protected View findView(int id){
return mRootView.findViewById(id);
}
}
|
JoeSteven/HuaBan
|
bak/src/main/java/com/joey/bak/base/ui/BaseFragment.java
|
Java
|
apache-2.0
| 3,988 |
/*!
* ${copyright}
*/
// Provides control sap.ui.commons.HorizontalDivider.
sap.ui.define([
'./library',
'sap/ui/core/Control',
'./HorizontalDividerRenderer'
],
function(library, Control, HorizontalDividerRenderer) {
"use strict";
// shortcut for sap.ui.commons.HorizontalDividerHeight
var HorizontalDividerHeight = library.HorizontalDividerHeight;
// shortcut for sap.ui.commons.HorizontalDividerType
var HorizontalDividerType = library.HorizontalDividerType;
/**
* Constructor for a new HorizontalDivider.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Divides the screen in visual areas.
* @extends sap.ui.core.Control
* @version ${version}
*
* @constructor
* @public
* @deprecated Since version 1.38.
* @alias sap.ui.commons.HorizontalDivider
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var HorizontalDivider = Control.extend("sap.ui.commons.HorizontalDivider", /** @lends sap.ui.commons.HorizontalDivider.prototype */ { metadata : {
library : "sap.ui.commons",
deprecated: true,
properties : {
/**
* Defines the width of the divider.
*/
width : {type : "sap.ui.core.CSSSize", group : "Appearance", defaultValue : '100%'},
/**
* Defines the type of the divider.
*/
type : {type : "sap.ui.commons.HorizontalDividerType", group : "Appearance", defaultValue : HorizontalDividerType.Area},
/**
* Defines the height of the divider.
*/
height : {type : "sap.ui.commons.HorizontalDividerHeight", group : "Appearance", defaultValue : HorizontalDividerHeight.Medium}
}
}});
// No Behaviour
return HorizontalDivider;
});
|
SAP/openui5
|
src/sap.ui.commons/src/sap/ui/commons/HorizontalDivider.js
|
JavaScript
|
apache-2.0
| 1,812 |
/*
* 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 mina.udp.perf;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
/**
* An UDP server used for performance tests.
*
* It does nothing fancy, except receiving the messages, and counting the number of
* received messages.
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class UdpServer extends IoHandlerAdapter {
/** The listening port (check that it's not already in use) */
public static final int PORT = 18567;
/** The number of message to receive */
public static final int MAX_RECEIVED = 100000;
/** The starting point, set when we receive the first message */
private static long t0;
/** A counter incremented for every recieved message */
private AtomicInteger nbReceived = new AtomicInteger(0);
/**
* {@inheritDoc}
*/
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
cause.printStackTrace();
session.close(true);
}
/**
* {@inheritDoc}
*/
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
int nb = nbReceived.incrementAndGet();
if (nb == 1) {
t0 = System.currentTimeMillis();
}
if (nb == MAX_RECEIVED) {
long t1 = System.currentTimeMillis();
System.out.println("-------------> end " + (t1 - t0));
}
if (nb % 10000 == 0) {
System.out.println("Received " + nb + " messages");
}
// If we want to MapDB.test the write operation, uncomment this line
session.write(message);
}
/**
* {@inheritDoc}
*/
@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("Session closed...");
// Reinitialize the counter and expose the number of received messages
System.out.println("Nb message received : " + nbReceived.get());
nbReceived.set(0);
}
/**
* {@inheritDoc}
*/
@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("Session created...");
}
/**
* {@inheritDoc}
*/
@Override
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
System.out.println("Session idle...");
}
/**
* {@inheritDoc}
*/
@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("Session Opened...");
}
/**
* Create the UDP server
*/
public UdpServer() throws IOException {
NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
acceptor.setHandler(this);
// The logger, if needed. Commented atm
//DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
//chain.addLast("logger", new LoggingFilter());
DatagramSessionConfig dcfg = acceptor.getSessionConfig();
acceptor.bind(new InetSocketAddress(PORT));
System.out.println("Server started...");
}
/**
* The entry point.
*/
public static void main(String[] args) throws IOException {
new UdpServer();
}
}
|
iloveyou416068/CookNIOServer
|
demos/mina/src/mina/udp/perf/UdpServer.java
|
Java
|
apache-2.0
| 4,387 |
/*
* Copyright (C) 2011-2016 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <assert.h>
#include "parserfactory.h"
#include "util.h"
#include "elf32parser.h"
#include "elf64parser.h"
namespace {
bin_fmt_t check_elf_format(const uint8_t* start_addr, uint64_t len)
{
assert(start_addr != NULL);
const Elf32_Ehdr* ehdr = (const Elf32_Ehdr *) start_addr;
if (len < sizeof(Elf32_Ehdr))
return BF_UNKNOWN;
if (strncmp((const char *)ehdr->e_ident, ELFMAG, SELFMAG) != 0)
return BF_UNKNOWN;
switch (ehdr->e_ident[EI_CLASS])
{
case ELFCLASS32: return BF_ELF32;
case ELFCLASS64: return BF_ELF64;
default: return BF_UNKNOWN;
}
}
}
namespace binparser {
/* Note, the `start_addr' should NOT be NULL! */
BinParser* get_parser(const uint8_t* start_addr, uint64_t len)
{
assert(start_addr != NULL);
bin_fmt_t bf = BF_UNKNOWN;
bf = check_elf_format(start_addr, len);
if (bf == BF_ELF64) return new Elf64Parser(start_addr, len);
/* Doesn't matter whether it is an ELF32 shared library or not,
* here we just make sure that the factory method won't return
* NULL.
*/
return new Elf32Parser(start_addr, len);
}
}
|
shwetasshinde24/Panoply
|
patched-driver-sdk/customSDK/psw/urts/parser/parserfactory.cpp
|
C++
|
apache-2.0
| 2,856 |
<?php
// Heading
$_['heading_title'] = 'Quốc Gia';
// Text
$_['text_success'] = 'Hoàn tất: Bạn đã sửa đổi các Quốc Gia!';
$_['text_list'] = 'Danh sách các Quốc gia';
$_['text_add'] = 'Thêm Quốc gia';
$_['text_edit'] = 'Sửa Quốc Gia';
// Column
$_['column_name'] = 'Tên Quốc Gia';
$_['column_iso_code_2'] = 'Mã ISO (2)';
$_['column_iso_code_3'] = 'Mã ISO (3)';
$_['column_action'] = 'Thao tác';
// Entry
$_['entry_name'] = 'Tên Quốc Gia:';
$_['entry_iso_code_2'] = 'Mã ISO (2):';
$_['entry_iso_code_3'] = 'Mã ISO (3):';
$_['entry_address_format'] = 'Định dạng địa chỉ :';
$_['entry_postcode_required']= 'Yêu cầu mã vùng:';
$_['entry_status'] = 'Tình trạng:';
// Help
$_['help_address_format'] = 'Họ = {firstname}<br />Tên = {lastname}<br />Công ty = {company}<br />Địa chỉ 1 = {address_1}<br />Địa chỉ 2 = {address_2}<br />Quận, Huyện = {city}<br />Mã vùng = {postcode}<br />Tỉnh, Thành phố = {zone}<br />Mã Tỉnh, Thành phố = {zone_code}<br />Quốc Gia = {country}';
// Error
$_['error_permission'] = 'Cảnh báo: Bạn không được phép sửa đổi các quốc gia!';
$_['error_name'] = 'Tên quốc gia phải lớn hơn 3 và nhỏ hơn 128 ký tự!';
$_['error_default'] = 'Cảnh báo: Bạn không thể xóa Quốc gia này!';
$_['error_store'] = 'Cảnh báo: Bạn không thể xóa Quốc gia này vì nó đang được thiết lập cho gian hàng %s!';
$_['error_address'] = 'Cảnh báo: Bạn không thể xóa Quốc gia này!';
$_['error_affiliate'] = 'Cảnh báo: Nước này không thể bị xóa khi nó hiện thời được gán tới %s chi nhánh.!';
$_['error_zone'] = 'Cảnh báo: Quốc gia này có thể không bị xóa!';
$_['error_zone_to_geo_zone'] = 'Cảnh báo: Quốc gia này có thể không bị xóa!';
?>
|
duythanhitc/ShopCartClean
|
admin/language/vi-vn/localisation/country.php
|
PHP
|
apache-2.0
| 2,084 |
<?php
/**
* Copyright 2015 Xenofon Spafaridis
*
* 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.
*/
//Show all errors
error_reporting(E_ALL);
ini_set('display_errors', '1');
//This autoload path is for loading current version of phramework
require __DIR__ . '/../vendor/autoload.php';
//define controller namespace, as shortcut
define('NS', '\\Phramework\\Examples\\API\\Controllers\\');
use \Phramework\Phramework;
/**
* @package examples/post
* Define APP as function
*/
$APP = function () {
//Include settings
$settings = include __DIR__ . '/../settings.php';
$URIStrategy = new \Phramework\URIStrategy\URITemplate([
['book/', NS . 'BookController', 'GET', Phramework::METHOD_GET],
['book/{id}', NS . 'BookController', 'GETSingle', Phramework::METHOD_GET],
['book/', NS . 'BookController', 'POST', Phramework::METHOD_POST]
]);
//Initialize API
$phramework = new Phramework($settings, $URIStrategy);
unset($settings);
Phramework::setViewer(
\Phramework\Viewers\JSON::class
);
//Execute API
$phramework->invoke();
};
/**
* Execute APP
*/
$APP();
|
phramework/examples-api
|
public/index.php
|
PHP
|
apache-2.0
| 1,649 |
/*
* Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.storagegateway.model;
/**
* <p>
* A JSON object containing the following fields:
* </p>
*
* <ul>
* <li> GatewayARN </li>
* <li> DescribeMaintenanceStartTimeOutput$DayOfWeek </li>
* <li> DescribeMaintenanceStartTimeOutput$HourOfDay </li>
* <li> DescribeMaintenanceStartTimeOutput$MinuteOfHour </li>
* <li> DescribeMaintenanceStartTimeOutput$Timezone </li>
*
* </ul>
*/
public class DescribeMaintenanceStartTimeResult {
/**
* The Amazon Resource Name (ARN) of the gateway. Use the
* <a>ListGateways</a> operation to return a list of gateways for your
* account and region.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>50 - 500<br/>
*/
private String gatewayARN;
/**
* A number between 0 and 23 that represents the hour of day. The hour of
* day is in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 23<br/>
*/
private Integer hourOfDay;
/**
* A number between 0 and 59 that represents the minute of hour. The
* minute of hour is in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 59<br/>
*/
private Integer minuteOfHour;
/**
* An ordinal number between 0 and 6 that represents the day of the week,
* where 0 represents Sunday and 6 represents Saturday. The day of week
* is in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 6<br/>
*/
private Integer dayOfWeek;
/**
* One of the <a>GatewayTimezone</a> values that indicates the time zone
* that is set for the gateway. The start time and day of week specified
* should be in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00
*/
private String timezone;
/**
* The Amazon Resource Name (ARN) of the gateway. Use the
* <a>ListGateways</a> operation to return a list of gateways for your
* account and region.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>50 - 500<br/>
*
* @return The Amazon Resource Name (ARN) of the gateway. Use the
* <a>ListGateways</a> operation to return a list of gateways for your
* account and region.
*/
public String getGatewayARN() {
return gatewayARN;
}
/**
* The Amazon Resource Name (ARN) of the gateway. Use the
* <a>ListGateways</a> operation to return a list of gateways for your
* account and region.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>50 - 500<br/>
*
* @param gatewayARN The Amazon Resource Name (ARN) of the gateway. Use the
* <a>ListGateways</a> operation to return a list of gateways for your
* account and region.
*/
public void setGatewayARN(String gatewayARN) {
this.gatewayARN = gatewayARN;
}
/**
* The Amazon Resource Name (ARN) of the gateway. Use the
* <a>ListGateways</a> operation to return a list of gateways for your
* account and region.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Length: </b>50 - 500<br/>
*
* @param gatewayARN The Amazon Resource Name (ARN) of the gateway. Use the
* <a>ListGateways</a> operation to return a list of gateways for your
* account and region.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DescribeMaintenanceStartTimeResult withGatewayARN(String gatewayARN) {
this.gatewayARN = gatewayARN;
return this;
}
/**
* A number between 0 and 23 that represents the hour of day. The hour of
* day is in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 23<br/>
*
* @return A number between 0 and 23 that represents the hour of day. The hour of
* day is in the time zone of the gateway.
*/
public Integer getHourOfDay() {
return hourOfDay;
}
/**
* A number between 0 and 23 that represents the hour of day. The hour of
* day is in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 23<br/>
*
* @param hourOfDay A number between 0 and 23 that represents the hour of day. The hour of
* day is in the time zone of the gateway.
*/
public void setHourOfDay(Integer hourOfDay) {
this.hourOfDay = hourOfDay;
}
/**
* A number between 0 and 23 that represents the hour of day. The hour of
* day is in the time zone of the gateway.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 23<br/>
*
* @param hourOfDay A number between 0 and 23 that represents the hour of day. The hour of
* day is in the time zone of the gateway.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DescribeMaintenanceStartTimeResult withHourOfDay(Integer hourOfDay) {
this.hourOfDay = hourOfDay;
return this;
}
/**
* A number between 0 and 59 that represents the minute of hour. The
* minute of hour is in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 59<br/>
*
* @return A number between 0 and 59 that represents the minute of hour. The
* minute of hour is in the time zone of the gateway.
*/
public Integer getMinuteOfHour() {
return minuteOfHour;
}
/**
* A number between 0 and 59 that represents the minute of hour. The
* minute of hour is in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 59<br/>
*
* @param minuteOfHour A number between 0 and 59 that represents the minute of hour. The
* minute of hour is in the time zone of the gateway.
*/
public void setMinuteOfHour(Integer minuteOfHour) {
this.minuteOfHour = minuteOfHour;
}
/**
* A number between 0 and 59 that represents the minute of hour. The
* minute of hour is in the time zone of the gateway.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 59<br/>
*
* @param minuteOfHour A number between 0 and 59 that represents the minute of hour. The
* minute of hour is in the time zone of the gateway.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DescribeMaintenanceStartTimeResult withMinuteOfHour(Integer minuteOfHour) {
this.minuteOfHour = minuteOfHour;
return this;
}
/**
* An ordinal number between 0 and 6 that represents the day of the week,
* where 0 represents Sunday and 6 represents Saturday. The day of week
* is in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 6<br/>
*
* @return An ordinal number between 0 and 6 that represents the day of the week,
* where 0 represents Sunday and 6 represents Saturday. The day of week
* is in the time zone of the gateway.
*/
public Integer getDayOfWeek() {
return dayOfWeek;
}
/**
* An ordinal number between 0 and 6 that represents the day of the week,
* where 0 represents Sunday and 6 represents Saturday. The day of week
* is in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 6<br/>
*
* @param dayOfWeek An ordinal number between 0 and 6 that represents the day of the week,
* where 0 represents Sunday and 6 represents Saturday. The day of week
* is in the time zone of the gateway.
*/
public void setDayOfWeek(Integer dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}
/**
* An ordinal number between 0 and 6 that represents the day of the week,
* where 0 represents Sunday and 6 represents Saturday. The day of week
* is in the time zone of the gateway.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Range: </b>0 - 6<br/>
*
* @param dayOfWeek An ordinal number between 0 and 6 that represents the day of the week,
* where 0 represents Sunday and 6 represents Saturday. The day of week
* is in the time zone of the gateway.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DescribeMaintenanceStartTimeResult withDayOfWeek(Integer dayOfWeek) {
this.dayOfWeek = dayOfWeek;
return this;
}
/**
* One of the <a>GatewayTimezone</a> values that indicates the time zone
* that is set for the gateway. The start time and day of week specified
* should be in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00
*
* @return One of the <a>GatewayTimezone</a> values that indicates the time zone
* that is set for the gateway. The start time and day of week specified
* should be in the time zone of the gateway.
*
* @see GatewayTimezone
*/
public String getTimezone() {
return timezone;
}
/**
* One of the <a>GatewayTimezone</a> values that indicates the time zone
* that is set for the gateway. The start time and day of week specified
* should be in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00
*
* @param timezone One of the <a>GatewayTimezone</a> values that indicates the time zone
* that is set for the gateway. The start time and day of week specified
* should be in the time zone of the gateway.
*
* @see GatewayTimezone
*/
public void setTimezone(String timezone) {
this.timezone = timezone;
}
/**
* One of the <a>GatewayTimezone</a> values that indicates the time zone
* that is set for the gateway. The start time and day of week specified
* should be in the time zone of the gateway.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00
*
* @param timezone One of the <a>GatewayTimezone</a> values that indicates the time zone
* that is set for the gateway. The start time and day of week specified
* should be in the time zone of the gateway.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*
* @see GatewayTimezone
*/
public DescribeMaintenanceStartTimeResult withTimezone(String timezone) {
this.timezone = timezone;
return this;
}
/**
* One of the <a>GatewayTimezone</a> values that indicates the time zone
* that is set for the gateway. The start time and day of week specified
* should be in the time zone of the gateway.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00
*
* @param timezone One of the <a>GatewayTimezone</a> values that indicates the time zone
* that is set for the gateway. The start time and day of week specified
* should be in the time zone of the gateway.
*
* @see GatewayTimezone
*/
public void setTimezone(GatewayTimezone timezone) {
this.timezone = timezone.toString();
}
/**
* One of the <a>GatewayTimezone</a> values that indicates the time zone
* that is set for the gateway. The start time and day of week specified
* should be in the time zone of the gateway.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Allowed Values: </b>GMT-12:00, GMT-11:00, GMT-10:00, GMT-9:00, GMT-8:00, GMT-7:00, GMT-6:00, GMT-5:00, GMT-4:00, GMT-3:30, GMT-3:00, GMT-2:00, GMT-1:00, GMT, GMT+1:00, GMT+2:00, GMT+3:00, GMT+3:30, GMT+4:00, GMT+4:30, GMT+5:00, GMT+5:30, GMT+5:45, GMT+6:00, GMT+7:00, GMT+8:00, GMT+9:00, GMT+9:30, GMT+10:00, GMT+11:00, GMT+12:00
*
* @param timezone One of the <a>GatewayTimezone</a> values that indicates the time zone
* that is set for the gateway. The start time and day of week specified
* should be in the time zone of the gateway.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*
* @see GatewayTimezone
*/
public DescribeMaintenanceStartTimeResult withTimezone(GatewayTimezone timezone) {
this.timezone = timezone.toString();
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (gatewayARN != null) sb.append("GatewayARN: " + gatewayARN + ", ");
if (hourOfDay != null) sb.append("HourOfDay: " + hourOfDay + ", ");
if (minuteOfHour != null) sb.append("MinuteOfHour: " + minuteOfHour + ", ");
if (dayOfWeek != null) sb.append("DayOfWeek: " + dayOfWeek + ", ");
if (timezone != null) sb.append("Timezone: " + timezone + ", ");
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getGatewayARN() == null) ? 0 : getGatewayARN().hashCode());
hashCode = prime * hashCode + ((getHourOfDay() == null) ? 0 : getHourOfDay().hashCode());
hashCode = prime * hashCode + ((getMinuteOfHour() == null) ? 0 : getMinuteOfHour().hashCode());
hashCode = prime * hashCode + ((getDayOfWeek() == null) ? 0 : getDayOfWeek().hashCode());
hashCode = prime * hashCode + ((getTimezone() == null) ? 0 : getTimezone().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof DescribeMaintenanceStartTimeResult == false) return false;
DescribeMaintenanceStartTimeResult other = (DescribeMaintenanceStartTimeResult)obj;
if (other.getGatewayARN() == null ^ this.getGatewayARN() == null) return false;
if (other.getGatewayARN() != null && other.getGatewayARN().equals(this.getGatewayARN()) == false) return false;
if (other.getHourOfDay() == null ^ this.getHourOfDay() == null) return false;
if (other.getHourOfDay() != null && other.getHourOfDay().equals(this.getHourOfDay()) == false) return false;
if (other.getMinuteOfHour() == null ^ this.getMinuteOfHour() == null) return false;
if (other.getMinuteOfHour() != null && other.getMinuteOfHour().equals(this.getMinuteOfHour()) == false) return false;
if (other.getDayOfWeek() == null ^ this.getDayOfWeek() == null) return false;
if (other.getDayOfWeek() != null && other.getDayOfWeek().equals(this.getDayOfWeek()) == false) return false;
if (other.getTimezone() == null ^ this.getTimezone() == null) return false;
if (other.getTimezone() != null && other.getTimezone().equals(this.getTimezone()) == false) return false;
return true;
}
}
|
frsyuki/aws-sdk-for-java
|
src/main/java/com/amazonaws/services/storagegateway/model/DescribeMaintenanceStartTimeResult.java
|
Java
|
apache-2.0
| 18,484 |
from __future__ import absolute_import
from django.utils.translation import ugettext as _
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate
from zerver.decorator import authenticated_json_post_view, has_request_variables, REQ
from zerver.lib.actions import do_change_password, \
do_change_full_name, do_change_enable_desktop_notifications, \
do_change_enter_sends, do_change_enable_sounds, \
do_change_enable_offline_email_notifications, do_change_enable_digest_emails, \
do_change_enable_offline_push_notifications, do_change_autoscroll_forever, \
do_change_default_desktop_notifications, \
do_change_enable_stream_desktop_notifications, do_change_enable_stream_sounds, \
do_regenerate_api_key, do_change_avatar_source, do_change_twenty_four_hour_time, do_change_left_side_userlist
from zerver.lib.avatar import avatar_url
from zerver.lib.response import json_success, json_error
from zerver.lib.upload import upload_avatar_image
from zerver.lib.validator import check_bool
from zerver.models import UserProfile
from zerver.lib.rest import rest_dispatch as _rest_dispatch
rest_dispatch = csrf_exempt((lambda request, *args, **kwargs: _rest_dispatch(request, globals(), *args, **kwargs)))
def name_changes_disabled(realm):
return settings.NAME_CHANGES_DISABLED or realm.name_changes_disabled
@authenticated_json_post_view
@has_request_variables
def json_change_ui_settings(request, user_profile,
autoscroll_forever=REQ(validator=check_bool,
default=None),
default_desktop_notifications=REQ(validator=check_bool,
default=None)):
result = {}
if autoscroll_forever is not None and \
user_profile.autoscroll_forever != autoscroll_forever:
do_change_autoscroll_forever(user_profile, autoscroll_forever)
result['autoscroll_forever'] = autoscroll_forever
if default_desktop_notifications is not None and \
user_profile.default_desktop_notifications != default_desktop_notifications:
do_change_default_desktop_notifications(user_profile, default_desktop_notifications)
result['default_desktop_notifications'] = default_desktop_notifications
return json_success(result)
@authenticated_json_post_view
@has_request_variables
def json_change_settings(request, user_profile,
full_name=REQ(),
old_password=REQ(default=""),
new_password=REQ(default=""),
confirm_password=REQ(default="")):
if new_password != "" or confirm_password != "":
if new_password != confirm_password:
return json_error(_("New password must match confirmation password!"))
if not authenticate(username=user_profile.email, password=old_password):
return json_error(_("Wrong password!"))
do_change_password(user_profile, new_password)
result = {}
if user_profile.full_name != full_name and full_name.strip() != "":
if name_changes_disabled(user_profile.realm):
# Failingly silently is fine -- they can't do it through the UI, so
# they'd have to be trying to break the rules.
pass
else:
new_full_name = full_name.strip()
if len(new_full_name) > UserProfile.MAX_NAME_LENGTH:
return json_error(_("Name too long!"))
do_change_full_name(user_profile, new_full_name)
result['full_name'] = new_full_name
return json_success(result)
@authenticated_json_post_view
@has_request_variables
def json_time_setting(request, user_profile, twenty_four_hour_time=REQ(validator=check_bool, default=None)):
result = {}
if twenty_four_hour_time is not None and \
user_profile.twenty_four_hour_time != twenty_four_hour_time:
do_change_twenty_four_hour_time(user_profile, twenty_four_hour_time)
result['twenty_four_hour_time'] = twenty_four_hour_time
return json_success(result)
@authenticated_json_post_view
@has_request_variables
def json_left_side_userlist(request, user_profile, left_side_userlist=REQ(validator=check_bool, default=None)):
result = {}
if left_side_userlist is not None and \
user_profile.left_side_userlist != left_side_userlist:
do_change_left_side_userlist(user_profile, left_side_userlist)
result['left_side_userlist'] = left_side_userlist
return json_success(result)
@authenticated_json_post_view
@has_request_variables
def json_change_notify_settings(request, user_profile,
enable_stream_desktop_notifications=REQ(validator=check_bool,
default=None),
enable_stream_sounds=REQ(validator=check_bool,
default=None),
enable_desktop_notifications=REQ(validator=check_bool,
default=None),
enable_sounds=REQ(validator=check_bool,
default=None),
enable_offline_email_notifications=REQ(validator=check_bool,
default=None),
enable_offline_push_notifications=REQ(validator=check_bool,
default=None),
enable_digest_emails=REQ(validator=check_bool,
default=None)):
result = {}
# Stream notification settings.
if enable_stream_desktop_notifications is not None and \
user_profile.enable_stream_desktop_notifications != enable_stream_desktop_notifications:
do_change_enable_stream_desktop_notifications(
user_profile, enable_stream_desktop_notifications)
result['enable_stream_desktop_notifications'] = enable_stream_desktop_notifications
if enable_stream_sounds is not None and \
user_profile.enable_stream_sounds != enable_stream_sounds:
do_change_enable_stream_sounds(user_profile, enable_stream_sounds)
result['enable_stream_sounds'] = enable_stream_sounds
# PM and @-mention settings.
if enable_desktop_notifications is not None and \
user_profile.enable_desktop_notifications != enable_desktop_notifications:
do_change_enable_desktop_notifications(user_profile, enable_desktop_notifications)
result['enable_desktop_notifications'] = enable_desktop_notifications
if enable_sounds is not None and \
user_profile.enable_sounds != enable_sounds:
do_change_enable_sounds(user_profile, enable_sounds)
result['enable_sounds'] = enable_sounds
if enable_offline_email_notifications is not None and \
user_profile.enable_offline_email_notifications != enable_offline_email_notifications:
do_change_enable_offline_email_notifications(user_profile, enable_offline_email_notifications)
result['enable_offline_email_notifications'] = enable_offline_email_notifications
if enable_offline_push_notifications is not None and \
user_profile.enable_offline_push_notifications != enable_offline_push_notifications:
do_change_enable_offline_push_notifications(user_profile, enable_offline_push_notifications)
result['enable_offline_push_notifications'] = enable_offline_push_notifications
if enable_digest_emails is not None and \
user_profile.enable_digest_emails != enable_digest_emails:
do_change_enable_digest_emails(user_profile, enable_digest_emails)
result['enable_digest_emails'] = enable_digest_emails
return json_success(result)
@authenticated_json_post_view
def json_set_avatar(request, user_profile):
if len(request.FILES) != 1:
return json_error(_("You must upload exactly one avatar."))
user_file = list(request.FILES.values())[0]
upload_avatar_image(user_file, user_profile, user_profile.email)
do_change_avatar_source(user_profile, UserProfile.AVATAR_FROM_USER)
user_avatar_url = avatar_url(user_profile)
json_result = dict(
avatar_url = user_avatar_url
)
return json_success(json_result)
@has_request_variables
def regenerate_api_key(request, user_profile):
do_regenerate_api_key(user_profile)
json_result = dict(
api_key = user_profile.api_key
)
return json_success(json_result)
@has_request_variables
def change_enter_sends(request, user_profile,
enter_sends=REQ('enter_sends', validator=check_bool)):
do_change_enter_sends(user_profile, enter_sends)
return json_success()
|
peiwei/zulip
|
zerver/views/user_settings.py
|
Python
|
apache-2.0
| 9,076 |
import path from 'path'
import chromedriver from 'chromedriver'
import webdriver from 'selenium-webdriver'
import electronPath from 'electron-prebuilt'
import homeStyles from '../app/components/Home.css'
import counterStyles from '../app/components/Counter.css'
chromedriver.start() // on port 9515
process.on('exit', chromedriver.stop)
const delay = time => new Promise(resolve => setTimeout(resolve, time))
describe('main window', function spec() {
this.timeout(5000)
before(async () => {
await delay(1000) // wait chromedriver start time
this.driver = new webdriver.Builder()
.usingServer('http://localhost:9515')
.withCapabilities({
chromeOptions: {
binary: electronPath,
args: ['app=' + path.resolve()],
},
})
.forBrowser('electron')
.build()
})
after(async () => {
await this.driver.quit()
})
const findCounter = () => {
return this.driver.findElement(webdriver.By.className(counterStyles.counter))
}
const findButtons = () => {
return this.driver.findElements(webdriver.By.className(counterStyles.btn))
}
it('should open window', async () => {
const title = await this.driver.getTitle()
expect(title).to.equal('Hello Electron React!')
})
it('should to Counter with click "to Counter" link', async () => {
const link = await this.driver.findElement(webdriver.By.css(`.${homeStyles.container} > a`))
link.click()
const counter = await findCounter()
expect(await counter.getText()).to.equal('0')
})
it('should display updated count after increment button click', async () => {
const buttons = await findButtons()
buttons[0].click()
const counter = await findCounter()
expect(await counter.getText()).to.equal('1')
})
it('should display updated count after descrement button click', async () => {
const buttons = await findButtons()
const counter = await findCounter()
buttons[1].click() // -
expect(await counter.getText()).to.equal('0')
})
it('shouldnt change if even and if odd button clicked', async () => {
const buttons = await findButtons()
const counter = await findCounter()
buttons[2].click() // odd
expect(await counter.getText()).to.equal('0')
})
it('should change if odd and if odd button clicked', async () => {
const buttons = await findButtons()
const counter = await findCounter()
buttons[0].click() // +
buttons[2].click() // odd
expect(await counter.getText()).to.equal('2')
})
it('should change if async button clicked and a second later', async () => {
const buttons = await findButtons()
const counter = await findCounter()
buttons[3].click() // async
expect(await counter.getText()).to.equal('2')
await this.driver.wait(() =>
counter.getText().then(text => text === '3')
, 1000, 'count not as expected')
})
it('should back to home if back button clicked', async () => {
const link = await this.driver.findElement(webdriver.By.css(`.${counterStyles.backButton} > a`))
link.click()
await this.driver.findElement(webdriver.By.className(homeStyles.container))
})
})
|
3-strand-code/3sc-desktop
|
test/e2e.js
|
JavaScript
|
apache-2.0
| 3,188 |
package com.example.apkdownloadspeedtest;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper_downloader extends SQLiteOpenHelper {
public DBHelper_downloader(Context context) {
//"download.db" is the name of database
super(context, "download.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table IF NOT EXISTS download_info("
+ "task_id integer,"
+ "thread_id integer,"
+ "start_pos integer,"
+ "end_pos integer,"
+ "cur_pos integer,"
+ "seg_size integer,"
+ "complete_size integer,"
+ "is_done integer,"
+ "url text,"
+ "primary key(url, thread_id)"
+ ")"
);
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
|
princegyw/Personal-Utils
|
keep-old/FileDownloader_v5.0/DBHelper_downloader.java
|
Java
|
apache-2.0
| 929 |
package com.ogove.hr.Activities.Notification;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.ogove.hr.R;
public class NotificationDepartmentCreate extends AppCompatActivity implements View.OnClickListener{
private EditText ndcTitle,ndcContent;
private Button ndcCreate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_department_create);
addControl();
}
private void addControl() {
ndcCreate = (Button) findViewById(R.id.ndcCreate);
ndcTitle = (EditText) findViewById(R.id.ndcTitle);
ndcContent = (EditText) findViewById(R.id.ndcContent);
ndcCreate.setOnClickListener(this);
ndcTitle.setOnClickListener(this);
ndcContent.setOnClickListener(this);
}
@Override
public void onClick(View v) {
}
}
|
LyokoVN/HRManager
|
app/src/main/java/com/ogove/hr/Activities/Notification/NotificationDepartmentCreate.java
|
Java
|
apache-2.0
| 1,077 |
/*
* 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.wicket.settings;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.apache.wicket.Application;
import org.apache.wicket.Component;
import org.apache.wicket.IResourceFactory;
import org.apache.wicket.Localizer;
import org.apache.wicket.core.util.resource.locator.IResourceStreamLocator;
import org.apache.wicket.core.util.resource.locator.ResourceStreamLocator;
import org.apache.wicket.core.util.resource.locator.caching.CachingResourceStreamLocator;
import org.apache.wicket.css.ICssCompressor;
import org.apache.wicket.javascript.IJavaScriptCompressor;
import org.apache.wicket.markup.head.PriorityFirstComparator;
import org.apache.wicket.markup.head.ResourceAggregator.RecordedHeaderItem;
import org.apache.wicket.markup.html.IPackageResourceGuard;
import org.apache.wicket.markup.html.SecurePackageResourceGuard;
import org.apache.wicket.request.http.WebResponse;
import org.apache.wicket.request.resource.caching.FilenameWithVersionResourceCachingStrategy;
import org.apache.wicket.request.resource.caching.IResourceCachingStrategy;
import org.apache.wicket.request.resource.caching.NoOpResourceCachingStrategy;
import org.apache.wicket.request.resource.caching.version.CachingResourceVersion;
import org.apache.wicket.request.resource.caching.version.IResourceVersion;
import org.apache.wicket.request.resource.caching.version.LastModifiedResourceVersion;
import org.apache.wicket.request.resource.caching.version.MessageDigestResourceVersion;
import org.apache.wicket.request.resource.caching.version.RequestCycleCachedResourceVersion;
import org.apache.wicket.resource.IPropertiesFactoryContext;
import org.apache.wicket.resource.PropertiesFactory;
import org.apache.wicket.resource.loader.ClassStringResourceLoader;
import org.apache.wicket.resource.loader.ComponentStringResourceLoader;
import org.apache.wicket.resource.loader.IStringResourceLoader;
import org.apache.wicket.resource.loader.InitializerStringResourceLoader;
import org.apache.wicket.resource.loader.PackageStringResourceLoader;
import org.apache.wicket.resource.loader.ValidatorStringResourceLoader;
import org.apache.wicket.util.file.IFileCleaner;
import org.apache.wicket.util.file.IResourceFinder;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.lang.Generics;
import org.apache.wicket.util.resource.IResourceStream;
import org.apache.wicket.util.time.Duration;
import org.apache.wicket.util.watch.IModificationWatcher;
import org.apache.wicket.util.watch.ModificationWatcher;
/**
* Class for resource related settings
* <p>
* <i>resourcePollFrequency </i> (defaults to no polling frequency) - Frequency at which resources
* should be polled for changes.
* <p>
* <i>resourceFinders</i> - Add/modify this to alter the search path for resources.
* <p>
* <i>useDefaultOnMissingResource </i> (defaults to true) - Set to true to return a default value if
* available when a required string resource is not found. If set to false then the
* throwExceptionOnMissingResource flag is used to determine how to behave. If no default is
* available then this is the same as if this flag were false
* <p>
* <i>A ResourceStreamLocator </i>- An Application's ResourceStreamLocator is used to find resources
* such as images or markup files. You can supply your own ResourceStreamLocator if your prefer to
* store your application's resources in a non-standard location (such as a different filesystem
* location, a particular JAR file or even a database) by overriding the getResourceLocator()
* method.
* <p>
* <i>Resource Factories </i>- Resource factories can be used to create resources dynamically from
* specially formatted HTML tag attribute values. For more details, see {@link IResourceFactory},
* {@link org.apache.wicket.markup.html.image.resource.DefaultButtonImageResourceFactory} and
* especially {@link org.apache.wicket.markup.html.image.resource.LocalizedImageResource}.
* <p>
* <i>A Localizer </i> The getLocalizer() method returns an object encapsulating all of the
* functionality required to access localized resources. For many localization problems, even this
* will not be required, as there are convenience methods available to all components:
* {@link org.apache.wicket.Component#getString(String key)} and
* {@link org.apache.wicket.Component#getString(String key, org.apache.wicket.model.IModel model)}.
* <p>
* <i>stringResourceLoaders </i>- A chain of <code>IStringResourceLoader</code> instances that are
* searched in order to obtain string resources used during localization. By default the chain is
* set up to first search for resources against a particular component (e.g. page etc.) and then
* against the application.
* </p>
*
* @author Jonathan Locke
* @author Chris Turner
* @author Eelco Hillenius
* @author Juergen Donnerstag
* @author Johan Compagner
* @author Igor Vaynberg (ivaynberg)
* @author Martijn Dashorst
* @author James Carman
*/
public class ResourceSettings implements IPropertiesFactoryContext
{
/** I18N support */
private Localizer localizer;
/** Map to look up resource factories by name */
private final Map<String, IResourceFactory> nameToResourceFactory = Generics.newHashMap();
/** The package resource guard. */
private IPackageResourceGuard packageResourceGuard = new SecurePackageResourceGuard(
new SecurePackageResourceGuard.SimpleCache(100));
/** The factory to be used for the property files */
private org.apache.wicket.resource.IPropertiesFactory propertiesFactory;
/** Filesystem Path to search for resources */
private List<IResourceFinder> resourceFinders = new ArrayList<IResourceFinder>();
/** Frequency at which files should be polled */
private Duration resourcePollFrequency = null;
/** resource locator for this application */
private IResourceStreamLocator resourceStreamLocator;
/** ModificationWatcher to watch for changes in markup files */
private IModificationWatcher resourceWatcher;
/**
* A cleaner that removes files asynchronously.
* <p>
* Used internally to remove the temporary files created by FileUpload functionality.
*/
private IFileCleaner fileCleaner;
/** Chain of string resource loaders to use */
private final List<IStringResourceLoader> stringResourceLoaders = Generics.newArrayList(6);
/** Flags used to determine how to behave if resources are not found */
private boolean throwExceptionOnMissingResource = true;
/** Determines behavior of string resource loading if string is missing */
private boolean useDefaultOnMissingResource = true;
/** Default cache duration */
private Duration defaultCacheDuration = WebResponse.MAX_CACHE_DURATION;
/** The JavaScript compressor */
private IJavaScriptCompressor javascriptCompressor;
/** The Css compressor */
private ICssCompressor cssCompressor;
/** escape string for '..' within resource keys */
private String parentFolderPlaceholder = "::";
// resource caching strategy
private IResourceCachingStrategy resourceCachingStrategy;
// application these settings are bound to
private final Application application;
private boolean useMinifiedResources = true;
private Comparator<? super RecordedHeaderItem> headerItemComparator = new PriorityFirstComparator(
false);
private boolean encodeJSessionId = false;
/**
* Configures Wicket's default ResourceLoaders.<br>
* For an example in {@code FooApplication} let {@code bar.Foo} extend {@link Component}, this
* results in the following ordering:
* <dl>
* <dt>component specific</dt>
* <dd>
* <ul>
* <li>bar/Foo.properties</li>
* <li>org/apache/wicket/Component.properties</li>
* </ul>
* </dd>
* <dt>package specific</dt>
* <dd>
* <ul>
* <li>bar/package.properties</li>
* <li>package.properties (on Foo's class loader)</li>
* <li>org/apache/wicket/package.properties</li>
* <li>org/apache/package.properties</li>
* <li>org/package.properties</li>
* <li>package.properties (on Component's class loader)</li>
* </ul>
* </dd>
* <dt>application specific</dt>
* <dd>
* <ul>
* <li>FooApplication.properties</li>
* <li>Application.properties</li>
* </ul>
* </dd>
* <dt>validator specific</dt>
* <dt>Initializer specific</dt>
* <dd>
* <ul>
* <li>bar.Foo.properties (Foo implementing IInitializer)</li>
* </ul>
* </dd>
* </dl>
*
* @param application
*/
public ResourceSettings(final Application application)
{
this.application = application;
stringResourceLoaders.add(new ComponentStringResourceLoader());
stringResourceLoaders.add(new PackageStringResourceLoader());
stringResourceLoaders.add(new ClassStringResourceLoader(application.getClass()));
stringResourceLoaders.add(new ValidatorStringResourceLoader());
stringResourceLoaders.add(new InitializerStringResourceLoader(application.getInitializers()));
}
/**
* Adds a resource factory to the list of factories to consult when generating resources
* automatically
*
* @param name
* The name to give to the factory
* @param resourceFactory
* The resource factory to add
* @return {@code this} object for chaining
*/
public ResourceSettings addResourceFactory(final String name, IResourceFactory resourceFactory)
{
nameToResourceFactory.put(name, resourceFactory);
return this;
}
@Override
public Localizer getLocalizer()
{
if (localizer == null)
{
localizer = new Localizer();
}
return localizer;
}
/**
* Gets the {@link org.apache.wicket.markup.html.PackageResourceGuard package resource guard}.
*
* @return The package resource guard
*/
public IPackageResourceGuard getPackageResourceGuard()
{
return packageResourceGuard;
}
/**
* Get the property factory which will be used to load property files
*
* @return PropertiesFactory
*/
public org.apache.wicket.resource.IPropertiesFactory getPropertiesFactory()
{
if (propertiesFactory == null)
{
propertiesFactory = new PropertiesFactory(this);
}
return propertiesFactory;
}
/**
* @param name
* Name of the factory to get
* @return The IResourceFactory with the given name.
*/
public IResourceFactory getResourceFactory(final String name)
{
return nameToResourceFactory.get(name);
}
/**
* Gets the resource finders to use when searching for resources. By default, a finder that
* looks in the classpath root is configured. {@link org.apache.wicket.protocol.http.WebApplication} adds the classpath
* directory META-INF/resources. To configure additional search paths or filesystem paths, add
* to this list.
*
* @return Returns the resourceFinders.
*/
public List<IResourceFinder> getResourceFinders()
{
return resourceFinders;
}
/**
* @return Returns the resourcePollFrequency.
*/
public Duration getResourcePollFrequency()
{
return resourcePollFrequency;
}
@Override
public IResourceStreamLocator getResourceStreamLocator()
{
if (resourceStreamLocator == null)
{
// Create compound resource locator using source path from
// application settings
resourceStreamLocator = new ResourceStreamLocator(getResourceFinders());
resourceStreamLocator = new CachingResourceStreamLocator(resourceStreamLocator);
}
return resourceStreamLocator;
}
@Override
public IModificationWatcher getResourceWatcher(boolean start)
{
if (resourceWatcher == null && start)
{
synchronized (this)
{
if (resourceWatcher == null)
{
final Duration pollFrequency = getResourcePollFrequency();
if (pollFrequency != null)
{
resourceWatcher = new ModificationWatcher(pollFrequency);
}
}
}
}
return resourceWatcher;
}
/**
* Sets the resource watcher
*
* @param watcher
* @return {@code this} object for chaining
*/
public ResourceSettings setResourceWatcher(IModificationWatcher watcher)
{
resourceWatcher = watcher;
return this;
}
/**
* @return the a cleaner which can be used to remove files asynchronously.
*/
public IFileCleaner getFileCleaner()
{
return fileCleaner;
}
/**
* Sets a cleaner that can be used to remove files asynchronously.
* <p>
* Used internally to delete the temporary files created by FileUpload functionality
*
* @param fileUploadCleaner
* the actual cleaner implementation. Can be <code>null</code>
* @return {@code this} object for chaining
*/
public ResourceSettings setFileCleaner(IFileCleaner fileUploadCleaner)
{
fileCleaner = fileUploadCleaner;
return this;
}
/**
* @return mutable list of all available string resource loaders
*/
public List<IStringResourceLoader> getStringResourceLoaders()
{
return stringResourceLoaders;
}
public boolean getThrowExceptionOnMissingResource()
{
return throwExceptionOnMissingResource;
}
/**
* @return Whether to use a default value (if available) when a missing resource is requested
*/
public boolean getUseDefaultOnMissingResource()
{
return useDefaultOnMissingResource;
}
/**
* Sets the localizer which will be used to find property values.
*
* @param localizer
* @since 1.3.0
* @return {@code this} object for chaining
*/
public ResourceSettings setLocalizer(final Localizer localizer)
{
this.localizer = localizer;
return this;
}
/**
* Sets the {@link org.apache.wicket.markup.html.PackageResourceGuard package resource guard}.
*
* @param packageResourceGuard
* The package resource guard
* @return {@code this} object for chaining
*/
public ResourceSettings setPackageResourceGuard(IPackageResourceGuard packageResourceGuard)
{
this.packageResourceGuard = Args.notNull(packageResourceGuard, "packageResourceGuard");
return this;
}
/**
* Set the property factory which will be used to load property files
*
* @param factory
* @return {@code this} object for chaining
*/
public ResourceSettings setPropertiesFactory(org.apache.wicket.resource.IPropertiesFactory factory)
{
propertiesFactory = factory;
return this;
}
/**
* Sets the finders to use when searching for resources. By default, the resources are located
* on the classpath. To add additional search paths, add to the list given by
* {@link #getResourceFinders()}. Use this method if you want to completely exchange the list of
* resource finders.
*
* @param resourceFinders
* The resourceFinders to set
* @return {@code this} object for chaining
*/
public ResourceSettings setResourceFinders(final List<IResourceFinder> resourceFinders)
{
Args.notNull(resourceFinders, "resourceFinders");
this.resourceFinders = resourceFinders;
// Cause resource locator to get recreated
resourceStreamLocator = null;
return this;
}
/**
* Sets the resource polling frequency. This is the duration of time between checks of resource
* modification times. If a resource, such as an HTML file, has changed, it will be reloaded.
* The default is one second in 'development' mode and 'never' in deployment mode.
*
* @param resourcePollFrequency
* Frequency at which to poll resources or <code>null</code> if polling should be
* disabled
* @return {@code this} object for chaining
*/
public ResourceSettings setResourcePollFrequency(final Duration resourcePollFrequency)
{
this.resourcePollFrequency = resourcePollFrequency;
return this;
}
/**
* /**
* Sets the resource stream locator for this application
*
* Consider wrapping <code>resourceStreamLocator</code> in {@link CachingResourceStreamLocator}.
* This way the locator will not be asked more than once for {@link IResourceStream}s which do
* not exist.
* @param resourceStreamLocator
* new resource stream locator
*
* @see #getResourceStreamLocator()
* @return {@code this} object for chaining
*/
public ResourceSettings setResourceStreamLocator(IResourceStreamLocator resourceStreamLocator)
{
this.resourceStreamLocator = resourceStreamLocator;
return this;
}
/**
* @param throwExceptionOnMissingResource
* @return {@code this} object for chaining
*/
public ResourceSettings setThrowExceptionOnMissingResource(final boolean throwExceptionOnMissingResource)
{
this.throwExceptionOnMissingResource = throwExceptionOnMissingResource;
return this;
}
/**
* @param useDefaultOnMissingResource
* Whether to use a default value (if available) when a missing resource is requested
* @return {@code this} object for chaining
*/
public ResourceSettings setUseDefaultOnMissingResource(final boolean useDefaultOnMissingResource)
{
this.useDefaultOnMissingResource = useDefaultOnMissingResource;
return this;
}
/**
* Get the the default cache duration for resources.
* <p/>
*
* @return cache duration (Duration.NONE will be returned if caching is disabled)
*
* @see org.apache.wicket.util.time.Duration#NONE
*/
public final Duration getDefaultCacheDuration()
{
return defaultCacheDuration;
}
/**
* Set the the default cache duration for resources.
* <p/>
* Based on RFC-2616 this should not exceed one year. If you set Duration.NONE caching will be
* disabled.
*
* @param duration
* default cache duration in seconds
*
* @see org.apache.wicket.util.time.Duration#NONE
* @see org.apache.wicket.request.http.WebResponse#MAX_CACHE_DURATION
* @return {@code this} object for chaining
*/
public final ResourceSettings setDefaultCacheDuration(Duration duration)
{
Args.notNull(duration, "duration");
defaultCacheDuration = duration;
return this;
}
/**
* Get the javascript compressor to remove comments and whitespace characters from javascripts
*
* @return whether the comments and whitespace characters will be stripped from resources served
* through {@link org.apache.wicket.request.resource.JavaScriptPackageResource
* JavaScriptPackageResource}. Null is a valid value.
*/
public IJavaScriptCompressor getJavaScriptCompressor()
{
return javascriptCompressor;
}
/**
* Set the javascript compressor implemententation use e.g. by
* {@link org.apache.wicket.request.resource.JavaScriptPackageResource
* JavaScriptPackageResource}. A typical implementation will remove comments and whitespace. But
* a no-op implementation is available as well.
*
* @param compressor
* The implementation to be used
* @return The old value
* @return {@code this} object for chaining
*/
public IJavaScriptCompressor setJavaScriptCompressor(IJavaScriptCompressor compressor)
{
IJavaScriptCompressor old = javascriptCompressor;
javascriptCompressor = compressor;
return old;
}
/**
* Get the CSS compressor to remove comments and whitespace characters from css resources
*
* @return whether the comments and whitespace characters will be stripped from resources served
* through {@link org.apache.wicket.request.resource.CssPackageResource
* CssPackageResource}. Null is a valid value.
*/
public ICssCompressor getCssCompressor()
{
return cssCompressor;
}
/**
* Set the CSS compressor implemententation use e.g. by
* {@link org.apache.wicket.request.resource.CssPackageResource CssPackageResource}. A typical
* implementation will remove comments and whitespace. But a no-op implementation is available
* as well.
*
* @param compressor
* The implementation to be used
* @return The old value
* @return {@code this} object for chaining
*/
public ICssCompressor setCssCompressor(ICssCompressor compressor)
{
ICssCompressor old = cssCompressor;
cssCompressor = compressor;
return old;
}
/**
* Placeholder string for '..' within resource urls (which will be crippled by the browser and
* not work anymore). Note that by default the placeholder string is <code>::</code>. Resources
* are protected by a {@link org.apache.wicket.markup.html.IPackageResourceGuard
* IPackageResourceGuard} implementation such as
* {@link org.apache.wicket.markup.html.PackageResourceGuard} which you may use or extend based
* on your needs.
*
* @return placeholder
*/
public String getParentFolderPlaceholder()
{
return parentFolderPlaceholder;
}
/**
* Placeholder string for '..' within resource urls (which will be crippled by the browser and
* not work anymore). Note that by default the placeholder string is <code>null</code> and thus
* will not allow to access parent folders. That is by purpose and for security reasons (see
* Wicket-1992). In case you really need it, a good value for placeholder would e.g. be "$up$".
* Resources additionally are protected by a
* {@link org.apache.wicket.markup.html.IPackageResourceGuard IPackageResourceGuard}
* implementation such as {@link org.apache.wicket.markup.html.PackageResourceGuard} which you
* may use or extend based on your needs.
*
* @see #getParentFolderPlaceholder()
*
* @param sequence
* character sequence which must not be ambiguous within urls
* @return {@code this} object for chaining
*/
public ResourceSettings setParentFolderPlaceholder(final String sequence)
{
parentFolderPlaceholder = sequence;
return this;
}
/**
* gets the resource caching strategy
*
* @return strategy
*/
public IResourceCachingStrategy getCachingStrategy()
{
if (resourceCachingStrategy == null)
{
final IResourceVersion resourceVersion;
if (application.usesDevelopmentConfig())
{
// development mode:
// use last-modified timestamp of packaged resource for resource caching
// cache the version information for the lifetime of the current http request
resourceVersion = new RequestCycleCachedResourceVersion(
new LastModifiedResourceVersion());
}
else
{
// deployment mode:
// use message digest over resource content for resource caching
// cache the version information for the lifetime of the application
resourceVersion = new CachingResourceVersion(new MessageDigestResourceVersion());
}
// cache resource with a version string in the filename
resourceCachingStrategy = new FilenameWithVersionResourceCachingStrategy(
resourceVersion);
}
return resourceCachingStrategy;
}
/**
* sets the resource caching strategy
*
* @param strategy
* instance of resource caching strategy
*
* @see IResourceCachingStrategy
* @return {@code this} object for chaining
*/
public ResourceSettings setCachingStrategy(IResourceCachingStrategy strategy)
{
if (strategy == null)
{
throw new NullPointerException(
"It is not allowed to set the resource caching strategy to value NULL. " +
"Please use " + NoOpResourceCachingStrategy.class.getName() + " instead.");
}
resourceCachingStrategy = strategy;
return this;
}
/**
* Sets whether to use pre-minified resources when available. Minified resources are detected by
* name. The minified version of {@code x.js} is expected to be called {@code x.min.js}. For css
* files, the same convention is used: {@code x.min.css} is the minified version of
* {@code x.css}. When this is null, minified resources will only be used in deployment
* configuration.
*
* @param useMinifiedResources
* The new value for the setting
* @return {@code this} object for chaining
*/
public ResourceSettings setUseMinifiedResources(boolean useMinifiedResources)
{
this.useMinifiedResources = useMinifiedResources;
return this;
}
/**
* @return Whether pre-minified resources will be used.
*/
public boolean getUseMinifiedResources()
{
return useMinifiedResources;
}
/**
* @return The comparator used to sort header items.
*/
public Comparator<? super RecordedHeaderItem> getHeaderItemComparator()
{
return headerItemComparator;
}
/**
* Sets the comparator used by the {@linkplain org.apache.wicket.markup.head.ResourceAggregator resource aggregator} for
* sorting header items. It should be noted that sorting header items may break resource
* dependencies. This comparator should therefore at least respect dependencies declared by
* resource references. By default, items are sorted using the {@link PriorityFirstComparator}.
*
* @param headerItemComparator
* The comparator used to sort header items, when null, header items will not be
* sorted.
* @return {@code this} object for chaining
*/
public ResourceSettings setHeaderItemComparator(Comparator<? super RecordedHeaderItem> headerItemComparator)
{
this.headerItemComparator = headerItemComparator;
return this;
}
/**
* A flag indicating whether static resources should have <tt>jsessionid</tt> encoded in their
* url.
*
* @return {@code true} if the jsessionid should be encoded in the url for resources
* implementing
* {@link org.apache.wicket.request.resource.caching.IStaticCacheableResource} when the
* cookies are disabled and there is an active http session.
*/
public boolean isEncodeJSessionId()
{
return encodeJSessionId;
}
/**
* Sets a flag indicating whether the jsessionid should be encoded in the url for resources
* implementing {@link org.apache.wicket.request.resource.caching.IStaticCacheableResource} when
* the cookies are disabled and there is an active http session.
*
* @param encodeJSessionId
* {@code true} when the jsessionid should be encoded, {@code false} - otherwise
* @return {@code this} object for chaining
*/
public ResourceSettings setEncodeJSessionId(boolean encodeJSessionId)
{
this.encodeJSessionId = encodeJSessionId;
return this;
}
}
|
dashorst/wicket
|
wicket-core/src/main/java/org/apache/wicket/settings/ResourceSettings.java
|
Java
|
apache-2.0
| 26,459 |
/*
* Copyright (C) 2016 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package OptimizationTests.Devirtualization.InvokeInterfaceIntTryCatchFinally;
class Main {
public static int div(int d) {
return 1 / d;
}
public static int runTest() {
try {
return div(0);
} catch (Exception e) {
// ignore
} finally {
CondVirtBase test = new CondVirtExt();
int result = test.getThingies();
return result;
}
}
public static void main(String[] args) {
int result = runTest();
System.out.println("Result " + result);
}
}
|
android-art-intel/Nougat
|
art-extension/opttests/src/OptimizationTests/Devirtualization/InvokeInterfaceIntTryCatchFinally/Main.java
|
Java
|
apache-2.0
| 1,187 |
/**
*
*/
package org.apache.hadoop.hdfs.server.namenodeFBT.lock;
import org.apache.hadoop.hdfs.server.namenodeFBT.Response;
/**
* @author hanhlh
*
*/
public final class EndLockResponse extends Response {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* EndLockRequest ¤ËÂФ¹¤ë¿·¤·¤¤±þÅú¥ª¥Ö¥¸¥§¥¯¥È¤òÀ¸À®¤·¤Þ¤¹.
* ±þÅú¤òȯÀ¸¤µ¤»¤¿¸¶°ø¤È¤Ê¤ë
* Í׵ᥪ¥Ö¥¸¥§¥¯¥È (EndLockRequest) ¤òÍ¿¤¨¤ëɬÍפ¬¤¢¤ê¤Þ¤¹.
*
* @param request ±þÅú¤Ëµ¯°ø¤¹¤ëÍ׵ᥪ¥Ö¥¸¥§¥¯¥È (EndLockRequest)
*/
public EndLockResponse(EndLockRequest request) {
super(request);
}
}
|
hanhlh/hadoop-0.20.2_FatBTree
|
src/hdfs/org/apache/hadoop/hdfs/server/namenodeFBT/lock/EndLockResponse.java
|
Java
|
apache-2.0
| 646 |
# coding=utf-8
from ..base import BitbucketBase
class BitbucketCloudBase(BitbucketBase):
def __init__(self, url, *args, **kwargs):
"""
Init the rest api wrapper
:param url: string: The base url used for the rest api.
:param *args: list: The fixed arguments for the AtlassianRestApi.
:param **kwargs: dict: The keyword arguments for the AtlassianRestApi.
:return: nothing
"""
expected_type = kwargs.pop("expected_type", None)
super(BitbucketCloudBase, self).__init__(url, *args, **kwargs)
if expected_type is not None and not expected_type == self.get_data("type"):
raise ValueError("Expected type of data is [{}], got [{}].".format(expected_type, self.get_data("type")))
def get_link(self, link):
"""
Get a link from the data.
:param link: string: The link identifier
:return: The requested link or None if it isn't present
"""
links = self.get_data("links")
if links is None or link not in links:
return None
return links[link]["href"]
def _get_paged(self, url, params=None, data=None, flags=None, trailing=None, absolute=False):
"""
Used to get the paged data
:param url: string: The url to retrieve
:param params: dict (default is None): The parameters
:param data: dict (default is None): The data
:param flags: string[] (default is None): The flags
:param trailing: bool (default is None): If True, a trailing slash is added to the url
:param absolute: bool (default is False): If True, the url is used absolute and not relative to the root
:return: A generator object for the data elements
"""
if params is None:
params = {}
while True:
response = super(BitbucketCloudBase, self).get(
url,
trailing=trailing,
params=params,
data=data,
flags=flags,
absolute=absolute,
)
if "values" not in response:
return
for value in response.get("values", []):
yield value
url = response.get("next")
if url is None:
break
# From now on we have absolute URLs
absolute = True
return
|
MattAgile/atlassian-python-api
|
atlassian/bitbucket/cloud/base.py
|
Python
|
apache-2.0
| 2,467 |
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.springframework.messaging.handler.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation which indicates that a method parameter should be bound to a message header.
*
* @author Rossen Stoyanchev
* @since 4.0
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Header {
/**
* The name of the request header to bind to.
*/
String value() default "";
/**
* Whether the header is required.
* <p>Default is {@code true}, leading to an exception if the header missing. Switch this
* to {@code false} if you prefer a {@code null} in case of the header missing.
*/
boolean required() default true;
/**
* The default value to use as a fallback. Supplying a default value implicitly
* sets {@link #required} to {@code false}.
*/
String defaultValue() default ValueConstants.DEFAULT_NONE;
}
|
qobel/esoguproject
|
spring-framework/spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/Header.java
|
Java
|
apache-2.0
| 1,673 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
exports.getMatchedParams = getMatchedParams;
exports.getQueryParams = getQueryParams;
exports.createRoute = createRoute;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var parametersPattern = /(:[^\/]+)/g;
// Some utility functions. Exported just to be able to test them easily
function getMatchedParams(route, path) {
var matches = path.match(route.matcher);
if (!matches) {
return false;
}
return route.params.reduce(function (acc, param, idx) {
acc[param] = decodeURIComponent(matches[idx + 1]);
return acc;
}, {});
};
function getQueryParams(query) {
return query.split('&').filter(function (p) {
return p.length;
}).reduce(function (acc, part) {
var _part$split = part.split('=');
var _part$split2 = _slicedToArray(_part$split, 2);
var key = _part$split2[0];
var value = _part$split2[1];
acc[decodeURIComponent(key)] = decodeURIComponent(value);
return acc;
}, {});
};
function createRoute(name, path, handler) {
var matcher = new RegExp(path.replace(parametersPattern, '([^\/]+)') + '$');
var params = (path.match(parametersPattern) || []).map(function (x) {
return x.substring(1);
});
return { name: name, path: path, handler: handler, matcher: matcher, params: params };
};
var findRouteParams = function findRouteParams(routes, path) {
var params = void 0;
var route = routes.find(function (r) {
return params = getMatchedParams(r, path);
});
return { route: route, params: params };
};
var parseUrl = function parseUrl(url) {
var _url$split = url.split('?');
var _url$split2 = _slicedToArray(_url$split, 2);
var path = _url$split2[0];
var queryString = _url$split2[1];
return { path: path, queryString: queryString };
};
var stripPrefix = function stripPrefix(url, prefix) {
return url.replace(new RegExp('^' + prefix), '');
};
// The actual Router as the default export of the module
var Router = function () {
function Router() {
_classCallCheck(this, Router);
this.routes = [];
this.prefix = '';
}
// Adds a route with an _optional_ name, a path and a handler function
_createClass(Router, [{
key: 'add',
value: function add(name, path, handler) {
if (arguments.length == 2) {
this.add.apply(this, [''].concat(Array.prototype.slice.call(arguments)));
} else {
this.routes.push(createRoute(name, path, handler));
}
return this;
}
}, {
key: 'setPrefix',
value: function setPrefix(prefix) {
this.prefix = prefix;
return this;
}
}, {
key: 'dispatch',
value: function dispatch(url) {
var _parseUrl = parseUrl(stripPrefix(url, this.prefix));
var path = _parseUrl.path;
var queryString = _parseUrl.queryString;
var query = getQueryParams(queryString || '');
var _findRouteParams = findRouteParams(this.routes, path);
var route = _findRouteParams.route;
var params = _findRouteParams.params;
if (route) {
route.handler({ params: params, query: query });
return route;
}
return false;
}
}, {
key: 'getCurrentRoute',
value: function getCurrentRoute(url) {
var _parseUrl2 = parseUrl(stripPrefix(url, this.prefix));
var path = _parseUrl2.path;
var queryString = _parseUrl2.queryString;
var rp = findRouteParams(this.routes, path);
return rp && rp.route;
}
}, {
key: 'formatUrl',
value: function formatUrl(routeName) {
var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var query = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var route = this.routes.find(function (r) {
return r.name === routeName;
});
if (!route) {
return '';
}
var queryString = Object.keys(query).map(function (k) {
return [k, query[k]];
}).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2);
var k = _ref2[0];
var v = _ref2[1];
return encodeURIComponent(k) + '=' + encodeURIComponent(v);
}).join('&');
var path = this.prefix + route.path.replace(parametersPattern, function (match) {
return params[match.substring(1)];
});
return queryString.length ? path + '?' + queryString : path;
}
}]);
return Router;
}();
exports.default = Router;
;
|
jmhdez/minimal-router
|
lib/Router.js
|
JavaScript
|
apache-2.0
| 5,579 |
package Entity;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by liangchenzhou on 25/08/16.
*/
public class SpeciesKingdom implements Parcelable {
private String kingdom;
private String scientificName;
public SpeciesKingdom() {
}
public SpeciesKingdom(String kingdom, String scientificName) {
this.kingdom = kingdom;
this.scientificName = scientificName;
}
public String getKingdom() {
return kingdom;
}
public void setKingdom(String kingdom) {
this.kingdom = kingdom;
}
public String getScientificName() {
return scientificName;
}
public void setScientificName(String scientificName) {
this.scientificName = scientificName;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(this.kingdom);
parcel.writeString(this.scientificName);
}
public static final Parcelable.Creator<SpeciesKingdom> CREATOR = new Creator<SpeciesKingdom>() {
@Override
public SpeciesKingdom createFromParcel(Parcel source) {
return new SpeciesKingdom(source.readString(), source.readString());
}
@Override
public SpeciesKingdom[] newArray(int size) {
return new SpeciesKingdom[size];
}
};
}
|
lawrencezcc/Moneco-V6
|
app/src/main/java/Entity/SpeciesKingdom.java
|
Java
|
apache-2.0
| 1,421 |
/*
* Copyright 2017 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 stroom.pipeline.xslt;
import stroom.docref.DocRef;
import stroom.docstore.api.DocumentResourceHelper;
import stroom.event.logging.rs.api.AutoLogged;
import stroom.pipeline.shared.XsltDoc;
import stroom.pipeline.shared.XsltResource;
import stroom.util.shared.EntityServiceException;
import javax.inject.Inject;
import javax.inject.Provider;
@AutoLogged
class XsltResourceImpl implements XsltResource {
private final Provider<XsltStore> xsltStoreProvider;
private final Provider<DocumentResourceHelper> documentResourceHelperProvider;
@Inject
XsltResourceImpl(final Provider<XsltStore> xsltStoreProvider,
final Provider<DocumentResourceHelper> documentResourceHelperProvider) {
this.xsltStoreProvider = xsltStoreProvider;
this.documentResourceHelperProvider = documentResourceHelperProvider;
}
@Override
public XsltDoc fetch(final String uuid) {
return documentResourceHelperProvider.get().read(xsltStoreProvider.get(), getDocRef(uuid));
}
@Override
public XsltDoc update(final String uuid, final XsltDoc doc) {
if (doc.getUuid() == null || !doc.getUuid().equals(uuid)) {
throw new EntityServiceException("The document UUID must match the update UUID");
}
return documentResourceHelperProvider.get().update(xsltStoreProvider.get(), doc);
}
private DocRef getDocRef(final String uuid) {
return DocRef.builder()
.uuid(uuid)
.type(XsltDoc.DOCUMENT_TYPE)
.build();
}
}
|
gchq/stroom
|
stroom-pipeline/src/main/java/stroom/pipeline/xslt/XsltResourceImpl.java
|
Java
|
apache-2.0
| 2,168 |
package org.mariotaku.menucomponent.internal.menu;
import java.lang.reflect.Method;
import java.util.Collection;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
public class MenuUtils {
public static Menu createMenu(final Context context) {
return new MenuImpl(context, null, null);
}
public static Menu createMenu(final Context context, final Collection<MenuItem> items) {
return new MenuImpl(context, null, items);
}
public static Menu createMenu(final Context context, final MenuAdapter adapter) {
return new MenuImpl(context, adapter, null);
}
public static Menu createMenu(final Context context, final MenuAdapter adapter, final Collection<MenuItem> items) {
return new MenuImpl(context, adapter, items);
}
@SuppressLint("InlinedApi")
public static int getShowAsActionFlags(final MenuItem item) {
if (item == null) throw new NullPointerException();
if (item instanceof MenuItemImpl) return ((MenuItemImpl) item).getShowAsActionFlags();
try {
final Method m = item.getClass().getMethod("getShowAsAction");
return (Integer) m.invoke(item);
} catch (final Exception e) {
return MenuItem.SHOW_AS_ACTION_NEVER;
}
}
}
|
xiedantibu/Android-MenuComponent
|
library/src/org/mariotaku/menucomponent/internal/menu/MenuUtils.java
|
Java
|
apache-2.0
| 1,243 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::ARM::MobileEngagement
module Models
#
# Defines values for PushModes
#
module PushModes
RealTime = "real-time"
OneShot = "one-shot"
Manual = "manual"
end
end
end
|
devigned/azure-sdk-for-ruby
|
management/azure_mgmt_mobile_engagement/lib/generated/azure_mgmt_mobile_engagement/models/push_modes.rb
|
Ruby
|
apache-2.0
| 389 |
#include "types.hpp"
namespace compiler
{
}
|
iamOgunyinka/substance-lang
|
src/types.cpp
|
C++
|
apache-2.0
| 45 |
// Code generated by go-swagger; DO NOT EDIT.
package repositories
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
strfmt "github.com/go-openapi/strfmt"
)
// NewGetRepositoryTreeParams creates a new GetRepositoryTreeParams object
// no default values defined in spec.
func NewGetRepositoryTreeParams() GetRepositoryTreeParams {
return GetRepositoryTreeParams{}
}
// GetRepositoryTreeParams contains all the bound params for the get repository tree operation
// typically these are obtained from a http.Request
//
// swagger:parameters getRepositoryTree
type GetRepositoryTreeParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*The repository's name
Required: true
In: path
*/
Name string
/*The owner's username
Required: true
In: path
*/
Owner string
/*The path for the tree
In: query
*/
Path *string
/*The ref for the tree
In: query
*/
Ref *string
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewGetRepositoryTreeParams() beforehand.
func (o *GetRepositoryTreeParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
qs := runtime.Values(r.URL.Query())
rName, rhkName, _ := route.Params.GetOK("name")
if err := o.bindName(rName, rhkName, route.Formats); err != nil {
res = append(res, err)
}
rOwner, rhkOwner, _ := route.Params.GetOK("owner")
if err := o.bindOwner(rOwner, rhkOwner, route.Formats); err != nil {
res = append(res, err)
}
qPath, qhkPath, _ := qs.GetOK("path")
if err := o.bindPath(qPath, qhkPath, route.Formats); err != nil {
res = append(res, err)
}
qRef, qhkRef, _ := qs.GetOK("ref")
if err := o.bindRef(qRef, qhkRef, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindName binds and validates parameter Name from path.
func (o *GetRepositoryTreeParams) bindName(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.Name = raw
return nil
}
// bindOwner binds and validates parameter Owner from path.
func (o *GetRepositoryTreeParams) bindOwner(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.Owner = raw
return nil
}
// bindPath binds and validates parameter Path from query.
func (o *GetRepositoryTreeParams) bindPath(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: false
// AllowEmptyValue: false
if raw == "" { // empty values pass all other validations
return nil
}
o.Path = &raw
return nil
}
// bindRef binds and validates parameter Ref from query.
func (o *GetRepositoryTreeParams) bindRef(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: false
// AllowEmptyValue: false
if raw == "" { // empty values pass all other validations
return nil
}
o.Ref = &raw
return nil
}
|
gitpods/gitpods
|
pkg/api/v1/restapi/operations/repositories/get_repository_tree_parameters.go
|
GO
|
apache-2.0
| 3,756 |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
requires = [
'cdo',
'bokeh',
'ocgis',
'pandas',
'nose',
]
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: Atmospheric Science',
]
setup(name='flyingpigeon',
version='0.2.0',
description='Processes for climate data, indices and extrem events',
long_description=README + '\n\n' + CHANGES,
classifiers=classifiers,
author='Nils Hempelmann',
author_email='nils.hempelmann@ipsl.jussieu.fr',
url='http://www.lsce.ipsl.fr/',
license = "http://www.apache.org/licenses/LICENSE-2.0",
keywords='wps flyingpigeon pywps malleefowl ipsl birdhouse conda anaconda',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
test_suite='nose.collector',
install_requires=requires,
entry_points = {
'console_scripts': [
]}
,
)
|
sradanov/flyingpigeon
|
setup.py
|
Python
|
apache-2.0
| 1,385 |
/**
* 预存费用
*/
AcctFeeGrid = Ext.extend(Ext.ux.Grid, {
border : false,
acctFeeStore : null,
region : 'center',
pageSize : 10,
constructor : function() {
this.acctFeeStore = new Ext.data.JsonStore({
url:Constant.ROOT_PATH+ "/commons/x/QueryCust!queryAcctPayFee.action",
totalProperty:'totalProperty',
root:'records',
fields : ['acct_type_text', 'acct_type', 'fee_text','is_logoff','is_doc','is_doc_text',
'fee_type', 'fee_type_text', {name : 'real_pay',type : 'float'},
'create_time','acct_date','device_code','invoice_mode','invoice_book_id','finance_status',
'invoice_code', 'invoice_id', 'pay_type_text','begin_date','prod_invalid_date',
'pay_type', 'status_text', 'status', 'dept_id','dept_name',
'user_id','user_name', 'user_type_text','fee_sn','optr_id','optr_name',
'OPERATE','busi_code','busi_name','create_done_code','data_right',
'busi_optr_id','busi_optr_name','prod_sn','invoice_fee',"doc_type","doc_type_text","invoice_mode_text","allow_done_code",'count_text']
});
this.acctFeeStore.on("load",this.doOperate);
var lc = langUtils.main("pay.payfee.columns");
var cm = new Ext.ux.grid.LockingColumnModel({
columns : [
{header:lc[0],dataIndex:'create_done_code',width:80},
{header:lc[1],dataIndex:'busi_name', width:150,renderer:App.qtipValue},
{header:lc[2],dataIndex:'acct_type_text',width:105,renderer:App.qtipValue},
{header:lc[3],dataIndex:'fee_text',width:150,renderer:App.qtipValue},
{header:lc[4],dataIndex:'user_type_text',width:70},
{header:lc[5],dataIndex:'user_name',width:130,renderer:App.qtipValue},
{header:lc[6],dataIndex:'device_code',width:130,renderer:App.qtipValue},
{header:lc[7],dataIndex:'status_text',width:70,renderer:Ext.util.Format.statusShow},
{header:lc[8],dataIndex:'real_pay',width:60,renderer:Ext.util.Format.formatFee},
{header:lc[9],dataIndex:'begin_date',width:125,renderer:Ext.util.Format.dateFormat},
{header:lc[10],dataIndex:'prod_invalid_date',width:125,renderer:Ext.util.Format.dateFormat},
{header:lc[11],dataIndex:'is_doc_text',width:75,renderer:Ext.util.Format.statusShow},
{header:lc[12],dataIndex:'pay_type_text',width:75, renderer:App.qtipValue},
{header:lc[13],dataIndex:'create_time',width:125},
{header:lc[14],dataIndex:'acct_date',width:125},
{header:lc[15],dataIndex:'optr_name',width:90, renderer:App.qtipValue},
{header:lc[16],dataIndex:'dept_name',width:100, renderer:App.qtipValue},
{header:lc[17],dataIndex:'invoice_id',width:80, renderer:App.qtipValue},
// {header:lc[18],dataIndex:'invoice_mode_text',width:80},
{header:lc[19],dataIndex:'doc_type_text',width:90, renderer:App.qtipValue},
{header:lc[20],dataIndex:'busi_optr_name',width:100, renderer:App.qtipValue}
]
});
var pageTbar = new Ext.PagingToolbar({store: this.acctFeeStore ,pageSize : this.pageSize});
AcctFeeGrid.superclass.constructor.call(this, {
id:'P_ACCT',
title : langUtils.main("pay.payfee._title"),
loadMask : true,
store : this.acctFeeStore,
border : false,
bbar: pageTbar,
disableSelection:true,
view: new Ext.ux.grid.ColumnLockBufferView(),
sm : new Ext.grid.RowSelectionModel(),
cm : cm,
tools:[{id:'search',qtip:'查询',cls:'tip-target',scope:this,handler:function(){
var comp = this.tools.search;
if(this.acctFeeStore.getCount()>0){
if(win)win.close();
win = FilterWindow.addComp(this,[
{text:'智能卡号',field:'device_code',type:'textfield'},
{text:'状态',field:'status',showField:'status_text',
data:[
{'text':'所有','value':''},
{'text':'已支付','value':'PAY'},
{'text':'失效','value':'INVALID'}
]
},
{text:'受理日期',field:'create_time',type:'datefield'},
{text:'受理人',field:'optr_name',type:'textfield'},
{text:'发票号',field:'invoice_id',type:'textfield'}
],700,null,true,"queryFeeInfo");
if(win){
win.setPosition(comp.getX()-win.width, comp.getY()-50);//弹出框右对齐
win.show();
}
}else{
Alert('请先查询数据!');
}
}
}]
});
},
initEvents :function(){
this.on("afterrender",function(){
this.swapViews();
},this,{delay:10});
AcctFeeGrid.superclass.initEvents.call(this);
},
doOperate:function(){
//不是当前登录人的不能进行“冲正”操作(去掉不符合条件行的“冲正”操作按钮)
this.each(function(record){
if(record.get('optr_name') != App.getData().optr['optr_name']){
record.set('OPERATE','F');
}
});
this.commitChanges();
},
remoteRefresh : function() {
this.refresh();
},
localRefresh : function() {
unitRecords = this.getSelectionModel().getSelections();
for (var i in unitRecords) {
this.acctFeeStore.remove(unitRecords[i]);
}
},
refresh:function(){
this.acctFeeStore.baseParams = {
residentCustId: App.getData().custFullInfo.cust.cust_id,
custStatus : App.data.custFullInfo.cust.status
};
// this.acctFeeStore.baseParams['residentCustId'] = App.getData().custFullInfo.cust.cust_id;
// this.acctFeeStore.baseParams['custStatus'] = App.data.custFullInfo.cust.status;
// this.acctFeeStore.load({params:{start: 0,limit: this.pageSize}});
this.reloadCurrentPage();
}
});
/**
* 业务费用
*/
BusiFeeGrid = Ext.extend(Ext.ux.Grid, {
border : false,
busiFeeStore : null,
region : 'center',
pageSize : 10,
constructor : function() {
this.busiFeeStore = new Ext.data.JsonStore({
url : Constant.ROOT_PATH+ "/commons/x/QueryCust!queryBusiPayFee.action",
totalProperty:'totalProperty',
root:'records',
fields : ['create_done_code','fee_text', 'device_type', 'device_type_text',
'device_code', {name : 'should_pay',type : 'int'},'is_doc','is_doc_text',
'pay_type_text', 'pay_type', 'status_text','dept_name','dept_id',
'status', 'invoice_code', 'invoice_id','invoice_mode', 'optr_id','optr_name',
{name : 'real_pay',type : 'int'},'fee_sn','create_time','acct_date','deposit',
'data_right','finance_status','invoice_book_id','is_busi_fee',
'busi_optr_id','busi_optr_name','invoice_fee',"doc_type","doc_type_text",
"invoice_mode_text",'buy_num','device_model','device_model_name', 'count_text']
});
var lc = langUtils.main("pay.busifee.columns");
var cm = new Ext.ux.grid.LockingColumnModel({
columns : [
{header:lc[0],dataIndex:'create_done_code',width:80},
{header:lc[1],dataIndex:'fee_text',width:110, renderer:App.qtipValue},
{header:lc[2],dataIndex:'device_type_text',width:80},
{header:lc[16],dataIndex:'device_model_name',width:120, renderer:App.qtipValue},
{header:lc[3],dataIndex:'device_code',width:130, renderer:App.qtipValue},
{header:lc[4],dataIndex:'status_text',width:70,renderer:Ext.util.Format.statusShow},
{header:lc[5],dataIndex:'is_doc_text',width:80,renderer:Ext.util.Format.statusShow},
{header:lc[6],dataIndex:'should_pay',width:60,renderer:Ext.util.Format.formatFee},
{header:lc[7],dataIndex:'real_pay',width:60,renderer:Ext.util.Format.formatFee},
{header:lc[17],dataIndex:'count_text',width:120,renderer:App.qtipValue},
{header:lc[15],dataIndex:'buy_num',width:80},
{header:lc[8],dataIndex:'pay_type_text',width:90, renderer:App.qtipValue},
{header:lc[9],dataIndex:'create_time',width:125},
{header:lc[19],dataIndex:'acct_date',width:125},
{header:lc[10],dataIndex:'optr_name',width:90, renderer:App.qtipValue},
{header:lc[11],dataIndex:'dept_name',width:100, renderer:App.qtipValue},
{header:lc[12],dataIndex:'invoice_id',width:90, renderer:App.qtipValue},
// {header:lc[13],dataIndex:'invoice_mode_text',width:80},
{header:lc[14],dataIndex:'doc_type_text',width:90, renderer:App.qtipValue},
{header:lc[18],dataIndex:'busi_optr_name',width:100, renderer:App.qtipValue}
]
});
BusiFeeGrid.superclass.constructor.call(this, {
id:'P_BUSI',
title : langUtils.main("pay.busifee._title"),
loadMask : true,
store : this.busiFeeStore,
border : false,
bbar: new Ext.PagingToolbar({store: this.busiFeeStore ,pageSize : this.pageSize}),
sm : new Ext.grid.RowSelectionModel(),
view: new Ext.ux.grid.ColumnLockBufferView(),
cm : cm,
listeners:{
scope:this,
delay:10,
rowdblclick: this.doDblClickRecord,
afterrender: this.swapViews
},
tools:[{id:'search',qtip:'查询',cls:'tip-target',scope:this,handler:function(){
var comp = this.tools.search;
if(this.busiFeeStore.getCount()>0){
if(win)win.close();
win = FilterWindow.addComp(this,[
{text:'设备类型',field:'device_type',showField:'device_type_text',
data:[
{'text':'设备类型','value':''},
{'text':'机顶盒','value':'STB'},
{'text':'智能卡','value':'CARD'},
{'text':'MODEM','value':'MODEM'}
]
},
{text:'设备编号',field:'device_code',type:'textfield'},
{text:'受理日期',field:'create_time',type:'datefield'},
{text:'状态',field:'status',showField:'status_text',
data:[
{'text':'所有','value':''},
{'text':'已支付','value':'PAY'},
{'text':'失效','value':'INVALID'}
]
},
{text:'受理人',field:'optr_name',type:'textfield'},
{text:'发票号',field:'invoice_id',type:'textfield'}
],800,null,true,"queryFeeInfo");
if(win){
win.setPosition(comp.getX()-win.width, comp.getY()-50);//弹出框右对齐
win.show();
}
}else{
Alert('请先查询数据!');
}
}
}]
});
},
doDblClickRecord : function(grid, rowIndex, e) {
var record = grid.getStore().getAt(rowIndex);
},
remoteRefresh : function() {
this.refresh();
},
refresh:function(){
/*Ext.Ajax.request({
url : Constant.ROOT_PATH+ "/commons/x/QueryCust!queryBusiPayFee.action",
scope:this,
params:{
residentCustId:App.getData().custFullInfo.cust.cust_id,
custStatus : App.data.custFullInfo.cust.status
},
success:function(res,opt){
var data = Ext.decode(res.responseText);
//PagingMemoryProxy() 一次性读取数据
this.busiFeeStore.proxy = new Ext.data.PagingMemoryProxy(data),
//本地分页
this.busiFeeStore.load({params:{start:0,limit:this.pageSize}});
}
});*/
// this.busiFeeStore.baseParams['residentCustId'] = App.getData().custFullInfo.cust.cust_id;
this.busiFeeStore.baseParams = {
residentCustId: App.getData().custFullInfo.cust.cust_id
};
// this.busiFeeStore.load({params:{start: 0,limit: this.pageSize}});
this.reloadCurrentPage();
},
localRefresh : function() {
unitRecords = this.getSelectionModel().getSelections();
for (var i in unitRecords) {
this.busiFeeStore.remove(unitRecords[i]);
}
}
});
/**
* 订单金额明细
*/
CfeePayWindow = Ext.extend(Ext.Window, {
feeStore:null,
constructor: function(){
this.feeStore = new Ext.data.JsonStore({
url : Constant.ROOT_PATH+ "/commons/x/QueryCust!queryFeePayDetail.action",
fields: ["real_pay","fee_text","invoice_id","create_done_code"]
})
var lc = langUtils.main("pay.feePayDetail.columns");
var columns = [
{header: lc[0], width: 80,sortable:true, dataIndex: 'create_done_code',renderer:App.qtipValue},
{header: lc[1],sortable:true, dataIndex: 'fee_text',renderer:App.qtipValue},
{header: lc[2], width: 70, sortable:true, dataIndex: 'real_pay',renderer:Ext.util.Format.formatFee},
{header: lc[3], width: 80,sortable:true, dataIndex: 'invoice_id',renderer:App.qtipValue}
];
return CfeePayWindow.superclass.constructor.call(this, {
layout:"fit",
title: langUtils.main("pay.feePayDetail._title"),
width: 600,
height: 300,
resizable: false,
maximizable: false,
closeAction: 'hide',
minimizable: false,
items: [{
xtype: 'grid',
stripeRows: true,
border: false,
store: this.feeStore,
columns: columns,
viewConfig:{forceFit:true},
stateful: true
}]
});
},
show: function(sn){
this.feeStore.baseParams = {
paySn: sn
};
this.feeStore.load();
return CfeePayWindow.superclass.show.call(this);
}
});
FeePayGrid = Ext.extend(Ext.ux.Grid, {
feePayStore : null,
pageSize : 20,
cfeePayWindow:null,
feePayData: [],
constructor : function() {
this.feePayStore = new Ext.data.JsonStore({
url : Constant.ROOT_PATH+ "/commons/x/QueryCust!queryFeePay.action",
totalProperty:'totalProperty',
root:'records',
fields : ['pay_sn','reverse_done_code', 'pay_type', 'pay_type_text',
'done_code', {name : 'usd',type : 'int'},'receipt_id','is_valid_text',
'is_valid', 'payer', 'acct_date','dept_name','dept_id',
'invoice_mode', 'invoice_mode_text', 'remark',{name : 'exchange',type : 'int'},
{name : 'cos',type : 'int'}, 'optr_id','optr_name',
{name : 'khr',type : 'int'},'create_time','data_right']
});
var lc = langUtils.main("pay.detail.columns");
var cm = new Ext.ux.grid.LockingColumnModel({
columns : [
{header:lc[0],dataIndex:'pay_sn',width:85,renderer:function(value,metaData,record){
that = this;
if(value != ''){
return '<div style="text-decoration:underline;font-weight:bold" onclick="Ext.getCmp(\'P_FEE_PAY\').doTransferFeeShow();" ext:qtitle="" ext:qtip="' + value + '">' + value +'</div>';
}else{
return '<div ext:qtitle="" ext:qtip="' + value + '">' + value +'</div>';
}
}},
{header:lc[1],dataIndex:'usd',width:50,renderer:Ext.util.Format.formatFee},
{header:lc[5],dataIndex:'is_valid_text',width:70,renderer:Ext.util.Format.statusShow},
{header:lc[2],dataIndex:'khr',width:50,renderer:Ext.util.Format.formatFee},
{header:lc[3],dataIndex:'exchange',width:70},
{header:lc[4],dataIndex:'cos',width:100,renderer:Ext.util.Format.formatFee},
{header:lc[6],dataIndex:'pay_type_text',width:100},
{header:lc[7],dataIndex:'payer',width:70},
{header:lc[8],dataIndex:'done_code',width:80},
{header:lc[9],dataIndex:'receipt_id',width:100},
// {header:lc[10],dataIndex:'invoice_mode_text',width:80},
{header:lc[11],dataIndex:'create_time',width:125},
{header:lc[12],dataIndex:'optr_name',width:100},
{header:lc[13],dataIndex:'dept_name',width:100}
]
});
FeePayGrid.superclass.constructor.call(this, {
id:'P_FEE_PAY',
title : langUtils.main("pay.detail._title"),
region:"east",
width:"30%",
split:true,
loadMask : true,
store : this.feePayStore,
// border : false,
bbar: new Ext.PagingToolbar({store: this.feePayStore ,pageSize : this.pageSize}),
sm : new Ext.grid.RowSelectionModel(),
view: new Ext.ux.grid.ColumnLockBufferView(),
cm : cm,
listeners:{
scope:this,
delay:10,
rowdblclick: this.doDblClickRecord,
afterrender: this.swapViews
},
tools:[{id:'search',qtip:'查询',cls:'tip-target',scope:this,handler:function(){
var comp = this.tools.search;
if(this.feePayStore.getCount()>0){
if(win)win.close();
win = FilterWindow.addComp(this,[
{text:'状态',field:'status',showField:'is_valid_text',
data:[
{'text':'所有','value':''},
{'text':'有效','value':'T'},
{'text':'失效','value':'F'}
]
},
{text:'受理日期',field:'create_time',type:'datefield'},
{text:'受理人',field:'optr_name',type:'textfield'},
{text:'发票号',field:'invoice_id',type:'textfield'}
],580,null,true,"queryFeeInfo");
if(win){
win.setPosition(comp.getX()-win.width, comp.getY()-50);//弹出框右对齐
win.show();
}
}else{
Alert('请先查询数据!');
}
}
}]
});
},
doDblClickRecord : function(grid, rowIndex, e) {
var record = grid.getStore().getAt(rowIndex);
},
remoteRefresh : function() {
this.refresh();
},
refresh:function(){
this.feePayStore.baseParams = {
residentCustId: App.getData().custFullInfo.cust.cust_id
};
// this.busiFeeStore.load({params:{start: 0,limit: this.pageSize}});
this.reloadCurrentPage();
},
localRefresh : function() {
unitRecords = this.getSelectionModel().getSelections();
for (var i in unitRecords) {
this.feePayStore.remove(unitRecords[i]);
}
},
doTransferFeeShow:function(){
if(!App.getApp().getCustId()){
Alert('请查询客户之后再做操作.');
return false;
}
var recs = this.selModel.getSelections();
if(!recs || recs.length !=1){
Alert('请选择且仅选择一条记录!');
return false;
}
var rec = recs[0];
if(!this.cfeePayWindow){
this.cfeePayWindow = new CfeePayWindow();
}
this.cfeePayWindow.show(rec.get('pay_sn'));
}
});
/**
*/
PayfeePanel = Ext.extend(BaseInfoPanel, {
// 面板属性定义
acctFeeGrid : null,
busiFeeGrid : null,
feePayGrid : null,
// other property
mask : null,
constructor : function() {
// 子面板实例化
this.acctFeeGrid = new AcctFeeGrid();
this.busiFeeGrid = new BusiFeeGrid();
this.feePayGrid = new FeePayGrid();
PayfeePanel.superclass.constructor.call(this, {
layout:"border",
border:false,
items:[{
region:"center",
layout:"anchor",
// border: false,
items : [{
layout : 'fit',
border : false,
anchor : "100% 60%",
bodyStyle: 'border-bottom-width: 1px;',
items : [this.acctFeeGrid]
}, {
layout : 'fit',
border : false,
anchor : "100% 40%",
items : [this.busiFeeGrid]
}]
},this.feePayGrid
// {
// region:"west",
// split:true,
// width:"30%",
// border: false,
// items:[this.feePayGrid]
// }
]
});
},
refresh : function() {
this.acctFeeGrid.remoteRefresh();
this.busiFeeGrid.remoteRefresh();
this.feePayGrid.remoteRefresh();
}
});
Ext.reg("payfeepanel", PayfeePanel);
|
leopardoooo/cambodia
|
boss-core/src/main/webapp/pages/index/center/PayfeePanel.js
|
JavaScript
|
apache-2.0
| 18,342 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
namespace WcfChatServer
{
interface IWcfChatClient
{
[OperationContract(IsOneWay = true)]
void onMessageReceived(string username, string message);
[OperationContract(IsOneWay = true)]
void onServerInfoReceived(int statusCode, string message);
}
}
|
jatwigg/wcf-messaging-service
|
WcfChatServer/Interface1.cs
|
C#
|
apache-2.0
| 439 |
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// todo: should have a way to auto-register these (instead of manually maintaining a list)
export default [
'version',
'setting',
'home',
'historyItem',
'space',
'spaces',
'source',
'sources',
'dataset',
'fullDataset',
'datasetUI',
'datasetContext',
'physicalDataset',
'datasetConfig',
'file',
'fileFormat',
'folder',
'jobDetails',
'tableData',
'previewTable',
'user',
'datasetAccelerationSettings',
'provision'
];
|
dremio/dremio-oss
|
dac/ui/src/reducers/resources/entityTypes.js
|
JavaScript
|
apache-2.0
| 1,073 |
/**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.interestrate;
import java.util.List;
import java.util.Map;
import com.opengamma.analytics.financial.interestrate.future.derivative.BondFuture;
import com.opengamma.analytics.financial.interestrate.future.method.BondFutureHullWhiteMethod;
import com.opengamma.util.tuple.DoublesPair;
/**
* Present value curve sensitivity calculator for interest rate instruments using Hull-White (extended Vasicek) one factor model.
*/
public final class PresentValueCurveSensitivityHullWhiteCalculator extends PresentValueCurveSensitivityCalculator {
/**
* The instance of the calculator.
*/
private static final PresentValueCurveSensitivityHullWhiteCalculator INSTANCE = new PresentValueCurveSensitivityHullWhiteCalculator();
/**
* Return the instance of the calculator.
* @return The calculator.
*/
public static PresentValueCurveSensitivityHullWhiteCalculator getInstance() {
return INSTANCE;
}
/**
* Private constructor.
*/
private PresentValueCurveSensitivityHullWhiteCalculator() {
}
/**
* The methods.
*/
private static final BondFutureHullWhiteMethod METHOD_HW = BondFutureHullWhiteMethod.getInstance();
@Override
public Map<String, List<DoublesPair>> visitBondFuture(final BondFuture bondFuture, final YieldCurveBundle curves) {
return METHOD_HW.presentValueCurveSensitivity(bondFuture, curves).getSensitivities();
}
}
|
charles-cooper/idylfin
|
src/com/opengamma/analytics/financial/interestrate/PresentValueCurveSensitivityHullWhiteCalculator.java
|
Java
|
apache-2.0
| 1,565 |
# Copyright (c) OpenMMLab. All rights reserved.
import itertools
import numpy as np
import torch
from .general_data import GeneralData
class InstanceData(GeneralData):
"""Data structure for instance-level annnotations or predictions.
Subclass of :class:`GeneralData`. All value in `data_fields`
should have the same length. This design refer to
https://github.com/facebookresearch/detectron2/blob/master/detectron2/structures/instances.py # noqa E501
Examples:
>>> from mmdet.core import InstanceData
>>> import numpy as np
>>> img_meta = dict(img_shape=(800, 1196, 3), pad_shape=(800, 1216, 3))
>>> results = InstanceData(img_meta)
>>> img_shape in results
True
>>> results.det_labels = torch.LongTensor([0, 1, 2, 3])
>>> results["det_scores"] = torch.Tensor([0.01, 0.7, 0.6, 0.3])
>>> results["det_masks"] = np.ndarray(4, 2, 2)
>>> len(results)
4
>>> print(resutls)
<InstanceData(
META INFORMATION
pad_shape: (800, 1216, 3)
img_shape: (800, 1196, 3)
PREDICTIONS
shape of det_labels: torch.Size([4])
shape of det_masks: (4, 2, 2)
shape of det_scores: torch.Size([4])
) at 0x7fe26b5ca990>
>>> sorted_results = results[results.det_scores.sort().indices]
>>> sorted_results.det_scores
tensor([0.0100, 0.3000, 0.6000, 0.7000])
>>> sorted_results.det_labels
tensor([0, 3, 2, 1])
>>> print(results[results.scores > 0.5])
<InstanceData(
META INFORMATION
pad_shape: (800, 1216, 3)
img_shape: (800, 1196, 3)
PREDICTIONS
shape of det_labels: torch.Size([2])
shape of det_masks: (2, 2, 2)
shape of det_scores: torch.Size([2])
) at 0x7fe26b6d7790>
>>> results[results.det_scores > 0.5].det_labels
tensor([1, 2])
>>> results[results.det_scores > 0.5].det_scores
tensor([0.7000, 0.6000])
"""
def __setattr__(self, name, value):
if name in ('_meta_info_fields', '_data_fields'):
if not hasattr(self, name):
super().__setattr__(name, value)
else:
raise AttributeError(
f'{name} has been used as a '
f'private attribute, which is immutable. ')
else:
assert isinstance(value, (torch.Tensor, np.ndarray, list)), \
f'Can set {type(value)}, only support' \
f' {(torch.Tensor, np.ndarray, list)}'
if self._data_fields:
assert len(value) == len(self), f'the length of ' \
f'values {len(value)} is ' \
f'not consistent with' \
f' the length ' \
f'of this :obj:`InstanceData` ' \
f'{len(self)} '
super().__setattr__(name, value)
def __getitem__(self, item):
"""
Args:
item (str, obj:`slice`,
obj`torch.LongTensor`, obj:`torch.BoolTensor`):
get the corresponding values according to item.
Returns:
obj:`InstanceData`: Corresponding values.
"""
assert len(self), ' This is a empty instance'
assert isinstance(
item, (str, slice, int, torch.LongTensor, torch.BoolTensor))
if isinstance(item, str):
return getattr(self, item)
if type(item) == int:
if item >= len(self) or item < -len(self):
raise IndexError(f'Index {item} out of range!')
else:
# keep the dimension
item = slice(item, None, len(self))
new_data = self.new()
if isinstance(item, (torch.Tensor)):
assert item.dim() == 1, 'Only support to get the' \
' values along the first dimension.'
if isinstance(item, torch.BoolTensor):
assert len(item) == len(self), f'The shape of the' \
f' input(BoolTensor)) ' \
f'{len(item)} ' \
f' does not match the shape ' \
f'of the indexed tensor ' \
f'in results_filed ' \
f'{len(self)} at ' \
f'first dimension. '
for k, v in self.items():
if isinstance(v, torch.Tensor):
new_data[k] = v[item]
elif isinstance(v, np.ndarray):
new_data[k] = v[item.cpu().numpy()]
elif isinstance(v, list):
r_list = []
# convert to indexes from boolTensor
if isinstance(item, torch.BoolTensor):
indexes = torch.nonzero(item).view(-1)
else:
indexes = item
for index in indexes:
r_list.append(v[index])
new_data[k] = r_list
else:
# item is a slice
for k, v in self.items():
new_data[k] = v[item]
return new_data
@staticmethod
def cat(instances_list):
"""Concat the predictions of all :obj:`InstanceData` in the list.
Args:
instances_list (list[:obj:`InstanceData`]): A list
of :obj:`InstanceData`.
Returns:
obj:`InstanceData`
"""
assert all(
isinstance(results, InstanceData) for results in instances_list)
assert len(instances_list) > 0
if len(instances_list) == 1:
return instances_list[0]
new_data = instances_list[0].new()
for k in instances_list[0]._data_fields:
values = [results[k] for results in instances_list]
v0 = values[0]
if isinstance(v0, torch.Tensor):
values = torch.cat(values, dim=0)
elif isinstance(v0, np.ndarray):
values = np.concatenate(values, axis=0)
elif isinstance(v0, list):
values = list(itertools.chain(*values))
else:
raise ValueError(
f'Can not concat the {k} which is a {type(v0)}')
new_data[k] = values
return new_data
def __len__(self):
if len(self._data_fields):
for v in self.values():
return len(v)
else:
raise AssertionError('This is an empty `InstanceData`.')
|
open-mmlab/mmdetection
|
mmdet/core/data_structures/instance_data.py
|
Python
|
apache-2.0
| 6,926 |
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Util.Automaton;
using NUnit.Framework;
using RandomizedTesting.Generators;
using System;
using System.Collections.Generic;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Search
{
/*
* 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.
*/
using AttributeSource = Lucene.Net.Util.AttributeSource;
using Automaton = Lucene.Net.Util.Automaton.Automaton;
using AutomatonTestUtil = Lucene.Net.Util.Automaton.AutomatonTestUtil;
using BytesRef = Lucene.Net.Util.BytesRef;
using CharacterRunAutomaton = Lucene.Net.Util.Automaton.CharacterRunAutomaton;
using CharsRef = Lucene.Net.Util.CharsRef;
using Codec = Lucene.Net.Codecs.Codec;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using FilteredTermsEnum = Lucene.Net.Index.FilteredTermsEnum;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockTokenizer = Lucene.Net.Analysis.MockTokenizer;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using RegExp = Lucene.Net.Util.Automaton.RegExp;
using Term = Lucene.Net.Index.Term;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using TestUtil = Lucene.Net.Util.TestUtil;
using UnicodeUtil = Lucene.Net.Util.UnicodeUtil;
/// <summary>
/// Create an index with random unicode terms
/// Generates random regexps, and validates against a simple impl.
/// </summary>
[TestFixture]
public class TestRegexpRandom2 : LuceneTestCase
{
protected internal IndexSearcher searcher1;
protected internal IndexSearcher searcher2;
private IndexReader reader;
private Directory dir;
protected internal string fieldName;
[SetUp]
public override void SetUp()
{
base.SetUp();
dir = NewDirectory();
fieldName = Random.NextBoolean() ? "field" : ""; // sometimes use an empty string as field name
RandomIndexWriter writer = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.KEYWORD, false)).SetMaxBufferedDocs(TestUtil.NextInt32(Random, 50, 1000)));
Document doc = new Document();
Field field = NewStringField(fieldName, "", Field.Store.NO);
doc.Add(field);
List<string> terms = new List<string>();
int num = AtLeast(200);
for (int i = 0; i < num; i++)
{
string s = TestUtil.RandomUnicodeString(Random);
field.SetStringValue(s);
terms.Add(s);
writer.AddDocument(doc);
}
if (Verbose)
{
// utf16 order
terms.Sort();
Console.WriteLine("UTF16 order:");
foreach (string s in terms)
{
Console.WriteLine(" " + UnicodeUtil.ToHexString(s));
}
}
reader = writer.GetReader();
searcher1 = NewSearcher(reader);
searcher2 = NewSearcher(reader);
writer.Dispose();
}
[TearDown]
public override void TearDown()
{
reader.Dispose();
dir.Dispose();
base.TearDown();
}
/// <summary>
/// a stupid regexp query that just blasts thru the terms </summary>
private class DumbRegexpQuery : MultiTermQuery
{
private readonly Automaton automaton;
internal DumbRegexpQuery(Term term, RegExpSyntax flags)
: base(term.Field)
{
RegExp re = new RegExp(term.Text, flags);
automaton = re.ToAutomaton();
}
protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
{
return new SimpleAutomatonTermsEnum(this, terms.GetEnumerator());
}
private sealed class SimpleAutomatonTermsEnum : FilteredTermsEnum
{
private readonly TestRegexpRandom2.DumbRegexpQuery outerInstance;
private CharacterRunAutomaton runAutomaton;
private readonly CharsRef utf16 = new CharsRef(10);
internal SimpleAutomatonTermsEnum(TestRegexpRandom2.DumbRegexpQuery outerInstance, TermsEnum tenum)
: base(tenum)
{
this.outerInstance = outerInstance;
runAutomaton = new CharacterRunAutomaton(outerInstance.automaton);
SetInitialSeekTerm(new BytesRef(""));
}
protected override AcceptStatus Accept(BytesRef term)
{
UnicodeUtil.UTF8toUTF16(term.Bytes, term.Offset, term.Length, utf16);
return runAutomaton.Run(utf16.Chars, 0, utf16.Length) ? AcceptStatus.YES : AcceptStatus.NO;
}
}
public override string ToString(string field)
{
return field.ToString() + automaton.ToString();
}
}
/// <summary>
/// test a bunch of random regular expressions </summary>
[Test]
public virtual void TestRegexps()
{
// we generate aweful regexps: good for testing.
// but for preflex codec, the test can be very slow, so use less iterations.
int num = Codec.Default.Name.Equals("Lucene3x", StringComparison.Ordinal) ? 100 * RandomMultiplier : AtLeast(1000);
for (int i = 0; i < num; i++)
{
string reg = AutomatonTestUtil.RandomRegexp(Random);
if (Verbose)
{
Console.WriteLine("TEST: regexp=" + reg);
}
AssertSame(reg);
}
}
/// <summary>
/// check that the # of hits is the same as from a very
/// simple regexpquery implementation.
/// </summary>
protected internal virtual void AssertSame(string regexp)
{
RegexpQuery smart = new RegexpQuery(new Term(fieldName, regexp), RegExpSyntax.NONE);
DumbRegexpQuery dumb = new DumbRegexpQuery(new Term(fieldName, regexp), RegExpSyntax.NONE);
TopDocs smartDocs = searcher1.Search(smart, 25);
TopDocs dumbDocs = searcher2.Search(dumb, 25);
CheckHits.CheckEqual(smart, smartDocs.ScoreDocs, dumbDocs.ScoreDocs);
}
}
}
|
NightOwl888/lucenenet
|
src/Lucene.Net.Tests/Search/TestRegexpRandom2.cs
|
C#
|
apache-2.0
| 7,611 |
#include <QtGui/QApplication>
#include "GameUI.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GameUI w(QString("XO4"), QSize(256, 256));
w.show();
return a.exec();
}
|
Dovgalyuk/AIBattle
|
XO4/Visualizer.cpp
|
C++
|
apache-2.0
| 193 |
'use strict'
// ** Constants
const DEFAULT_HOST = 'localhost';
const DEFAULT_PORT = 8080;
// ** Dependencies
const WebSocket = require('ws');
// ** Libraries
const Service = require('../../lib/Service');
// ** Platform
const logger = require('nodus-framework').logging.createLogger();
function logEvents() {
var socket = new WebSocket('ws://localhost:3333/');
socket.on('open', function open() {
console.log('connected');
socket.send(Date.now().toString(), {mask: true});
});
socket.on('close', function close() {
console.log('disconnected');
});
socket.on('message', function message(data, flags) {
console.log('Roundtrip time: ' + (Date.now() - parseInt(data)) + 'ms', flags);
setTimeout(function timeout() {
socket.send(Date.now().toString(), {mask: true});
}, 500);
});
return socket;
}
// ** Exports
module.exports = logEvents;
|
bradserbu/nodus-server
|
examples/console/console.js
|
JavaScript
|
apache-2.0
| 935 |
/**
@file Connection_uLimeSDREntry.cpp
@author Lime Microsystems
@brief Implementation of uLimeSDR board connection.
*/
#include "ConnectionFT601.h"
#include "Logger.h"
using namespace lime;
#ifdef __unix__
void ConnectionFT601Entry::handle_libusb_events()
{
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 250000;
while(mProcessUSBEvents.load() == true)
{
int r = libusb_handle_events_timeout_completed(ctx, &tv, NULL);
if(r != 0) lime::error("error libusb_handle_events %s", libusb_strerror(libusb_error(r)));
}
}
#endif // __UNIX__
//! make a static-initialized entry in the registry
void __loadConnectionFT601Entry(void) //TODO fixme replace with LoadLibrary/dlopen
{
static ConnectionFT601Entry FTDIEntry;
}
ConnectionFT601Entry::ConnectionFT601Entry(void):
ConnectionRegistryEntry("FT601")
{
#ifndef __unix__
//m_pDriver = new CDriverInterface();
#else
int r = libusb_init(&ctx); //initialize the library for the session we just declared
if(r < 0)
lime::error("Init Error %i", r); //there was an error
libusb_set_debug(ctx, 3); //set verbosity level to 3, as suggested in the documentation
mProcessUSBEvents.store(true);
mUSBProcessingThread = std::thread(&ConnectionFT601Entry::handle_libusb_events, this);
#endif
}
ConnectionFT601Entry::~ConnectionFT601Entry(void)
{
#ifndef __unix__
//delete m_pDriver;
#else
mProcessUSBEvents.store(false);
mUSBProcessingThread.join();
libusb_exit(ctx);
#endif
}
std::vector<ConnectionHandle> ConnectionFT601Entry::enumerate(const ConnectionHandle &hint)
{
std::vector<ConnectionHandle> handles;
#ifndef __unix__
FT_STATUS ftStatus=FT_OK;
static DWORD numDevs = 0;
ftStatus = FT_CreateDeviceInfoList(&numDevs);
if (!FT_FAILED(ftStatus) && numDevs > 0)
{
DWORD Flags = 0;
char SerialNumber[16] = { 0 };
char Description[32] = { 0 };
for (DWORD i = 0; i < numDevs; i++)
{
ftStatus = FT_GetDeviceInfoDetail(i, &Flags, nullptr, nullptr, nullptr, SerialNumber, Description, nullptr);
if (!FT_FAILED(ftStatus))
{
ConnectionHandle handle;
handle.media = Flags & FT_FLAGS_SUPERSPEED ? "USB 3" : Flags & FT_FLAGS_HISPEED ? "USB 2" : "USB";
handle.name = Description;
handle.index = i;
handle.serial = SerialNumber;
handles.push_back(handle);
}
}
}
#else
libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices
int usbDeviceCount = libusb_get_device_list(ctx, &devs);
if (usbDeviceCount < 0) {
lime::error("failed to get libusb device list: %s", libusb_strerror(libusb_error(usbDeviceCount)));
return handles;
}
libusb_device_descriptor desc;
for(int i=0; i<usbDeviceCount; ++i)
{
int r = libusb_get_device_descriptor(devs[i], &desc);
if(r<0)
lime::error("failed to get device description");
int pid = desc.idProduct;
int vid = desc.idVendor;
if( vid == 0x0403)
{
if(pid == 0x601F)
{
libusb_device_handle *tempDev_handle(nullptr);
if(libusb_open(devs[i], &tempDev_handle) != 0 || tempDev_handle == nullptr)
continue;
ConnectionHandle handle;
//check operating speed
int speed = libusb_get_device_speed(devs[i]);
if(speed == LIBUSB_SPEED_HIGH)
handle.media = "USB 2.0";
else if(speed == LIBUSB_SPEED_SUPER)
handle.media = "USB 3.0";
else
handle.media = "USB";
//read device name
char data[255];
memset(data, 0, 255);
int st = libusb_get_string_descriptor_ascii(tempDev_handle, LIBUSB_CLASS_COMM, (unsigned char*)data, 255);
if(st < 0)
lime::error("Error getting usb descriptor");
else
handle.name = std::string(data, size_t(st));
handle.addr = std::to_string(int(pid))+":"+std::to_string(int(vid));
if (desc.iSerialNumber > 0)
{
r = libusb_get_string_descriptor_ascii(tempDev_handle,desc.iSerialNumber,(unsigned char*)data, sizeof(data));
if(r<0)
lime::error("failed to get serial number");
else
handle.serial = std::string(data, size_t(r));
}
libusb_close(tempDev_handle);
//add handle conditionally, filter by serial number
if (hint.serial.empty() or hint.serial == handle.serial)
{
handles.push_back(handle);
}
}
}
}
libusb_free_device_list(devs, 1);
#endif
return handles;
}
IConnection *ConnectionFT601Entry::make(const ConnectionHandle &handle)
{
#ifndef __unix__
return new ConnectionFT601(mFTHandle, handle);
#else
return new ConnectionFT601(ctx, handle);
#endif
}
|
romeojulietthotel/LimeSuite
|
src/ConnectionFTDI/ConnectionFT601Entry.cpp
|
C++
|
apache-2.0
| 5,428 |
from ajenti.api import *
from ajenti.plugins import *
info = PluginInfo(
title='Resource Manager',
icon='link',
dependencies=[
],
)
def init():
import server
|
lupyuen/RaspberryPiImage
|
usr/share/pyshared/ajenti/plugins/resources/__init__.py
|
Python
|
apache-2.0
| 182 |
import Ember from 'ember';
/**
* @module ember-osf
* @submodule mixins
*/
/**
* Controller mixin that implements common actions performed on nodes.
* @class NodeActionsMixin
* @extends Ember.Mixin
*/
export default Ember.Mixin.create({
/**
* The node to perform these actions on. If not specified, defaults to the model hook.
* @property node
* @type DS.Model
*/
node: null,
model: null,
_node: Ember.computed.or('node', 'model'),
/**
* Helper method that affiliates an institution with a node.
*
* @method _affiliateNode
* @private
* @param {DS.Model} node Node record
* @param {Object} institution Institution record
* @return {Promise} Returns a promise that resolves to the updated node with the newly created institution relationship
*/
_affiliateNode(node, institution) {
node.get('affiliatedInstitutions').pushObject(institution);
return node.save();
},
actions: {
/**
* Update a node
*
* @method updateNode
* @param {String} title New title of the node
* @param {String} description New Description of the node
* @param {String} category New node category
* @param {Boolean} isPublic Should this node be publicly-visible?
* @return {Promise} Returns a promise that resolves to the updated node
*/
updateNode(title, description, category, isPublic) {
var node = this.get('_node');
if (title) {
node.set('title', title);
}
if (category) {
node.set('category', category);
}
if (description) {
node.set('description', description);
}
if (isPublic !== null) {
node.set('public', isPublic);
}
return node.save();
},
/**
* Delete a node
*
* @method deleteNode
* @return {Promise} Returns a promise that resolves after the deletion of the node.
*/
deleteNode() {
var node = this.get('_node');
return node.destroyRecord();
},
/**
* Affiliate a node with an institution
*
* @method affiliateNode
* @param {String} institutionId ID of the institutution to be affiliated
* @return {Promise} Returns a promise that resolves to the updated node
* with the newly affiliated institution relationship
*/
affiliateNode(institutionId) {
var node = this.get('_node');
return this.store.findRecord('institution', institutionId)
.then(institution => this._affiliateNode(node, institution));
},
/**
* Unaffiliate a node with an institution
*
* @method unaffiliateNode
* @param {Object} institution Institution relationship to be removed from node
* @return {Promise} Returns a promise that resolves to the updated node
* with the affiliated institution relationship removed.
*/
unaffiliateNode(institution) {
var node = this.get('_node');
node.get('affiliatedInstitutions').removeObject(institution);
return node.save();
},
/**
* Add a contributor to a node
*
* @method addContributor
* @param {String} userId ID of user that will be a contributor on the node
* @param {String} permission User permission level. One of "read", "write", or "admin". Default: "write".
* @param {Boolean} isBibliographic Whether user will be included in citations for the node. "default: true"
* @param {Boolean} sendEmail Whether user will receive an email when added. "default: true"
* @return {Promise} Returns a promise that resolves to the newly created contributor object.
*/
addContributor(userId, permission, isBibliographic, sendEmail) { // jshint ignore:line
return this.get('_node').addContributor(...arguments);
},
/**
* Bulk add contributors to a node
*
* @method addContributors
* @param {Array} contributors Array of objects containing contributor permission, bibliographic, and userId keys
* @param {Boolean} sendEmail Whether user will receive an email when added. "default: true"
* @return {Promise} Returns a promise that resolves to an array of added contributors
*/
addContributors(contributors, sendEmail) { // jshint ignore:line
return this.get('_node').addContributors(...arguments);
},
/**
* Remove a contributor from a node
*
* @method removeContributor
* @param {Object} contributor Contributor relationship that will be removed from node
* @return {Promise} Returns a promise that will resolve upon contributor deletion.
* User itself will not be removed.
*/
removeContributor(contributor) {
var node = this.get('_node');
return node.removeContributor(contributor);
},
/**
* Update contributors of a node. Makes a bulk request to the APIv2.
*
* @method updateContributors
* @param {Contributor[]} contributors Contributor relationships on the node.
* @param {Object} permissionsChanges Dictionary mapping contributor ids to desired permissions.
* @param {Object} bibliographicChanges Dictionary mapping contributor ids to desired bibliographic statuses
* @return {Promise} Returns a promise that resolves to the updated node
* with edited contributor relationships.
*/
updateContributors(contributors, permissionsChanges, bibliographicChanges) { // jshint ignore:line
return this.get('_node').updateContributors(...arguments);
},
/**
* Update contributors of a node. Makes a bulk request to the APIv2.
*
* @method updateContributor
* @param {Contributor} contributor relationship on the node.
* @param {string} permissions desired permissions.
* @param {boolean} bibliographic desired bibliographic statuses
* @return {Promise} Returns a promise that resolves to the updated node
* with edited contributor relationships.
*/
updateContributor(contributor, permissions, bibliographic) { // jshint ignore:line
return this.get('_node').updateContributor(...arguments);
},
/**
* Reorder contributors on a node, and manually updates store.
*
* @method reorderContributors
* @param {Object} contributor Contributor record to be modified
* @param {Integer} newIndex Contributor's new position in the list
* @param {Array} contributors New contributor list in correct order
* @return {Promise} Returns a promise that resolves to the updated contributor.
*/
reorderContributors(contributor, newIndex, contributors) {
contributor.set('index', newIndex);
return contributor.save().then(() => {
contributors.forEach((contrib, index) => {
if (contrib.id !== contributor.id) {
var payload = contrib.serialize();
payload.data.attributes = {
permission: contrib.get('permission'),
bibliographic: contrib.get('bibliographic'),
index: index
};
payload.data.id = contrib.get('id');
this.store.pushPayload(payload);
}
});
});
},
/**
* Add a child (component) to a node.
*
* @method addChild
* @param {String} title Title for the child
* @param {String} description Description for the child
* @param {String} category Category for the child
* @return {Promise} Returns a promise that resolves to the newly created child node.
*/
addChild(title, description, category) {
return this.get('_node').addChild(title, description, category);
},
/**
* Add a node link (pointer) to another node
*
* @method addNodeLink
* @param {String} targetNodeId ID of the node for which you wish to create a pointer
* @return {Promise} Returns a promise that resolves to model for the newly created NodeLink
*/
addNodeLink(targetNodeId) {
var node = this.get('_node');
var nodeLink = this.store.createRecord('node-link', {
target: targetNodeId
});
node.get('nodeLinks').pushObject(nodeLink);
return node.save().then(() => nodeLink);
},
/**
* Remove a node link (pointer) to another node
*
* @method removeNodeLink
* @param {Object} nodeLink nodeLink record to be destroyed.
* @return {Promise} Returns a promise that resolves after the node link has been removed. This does not delete
* the target node itself.
*/
removeNodeLink(nodeLink) {
return nodeLink.destroyRecord();
}
}
});
|
pattisdr/ember-osf
|
addon/mixins/node-actions.js
|
JavaScript
|
apache-2.0
| 9,519 |
package act.app.event;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import act.event.ActEventListener;
public interface SysEventListener<EVENT_TYPE extends SysEvent> extends ActEventListener<EVENT_TYPE> {
}
|
actframework/actframework
|
src/main/java/act/app/event/SysEventListener.java
|
Java
|
apache-2.0
| 816 |
/*
* Copyright 2012 hbz NRW (http://www.hbz-nrw.de/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package de.nrw.hbz.regal.sync.ingest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import models.ObjectType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import archive.fedora.XmlUtils;
import de.nrw.hbz.regal.sync.extern.DigitalEntity;
import de.nrw.hbz.regal.sync.extern.DigitalEntityBuilderInterface;
import de.nrw.hbz.regal.sync.extern.DigitalEntityRelation;
import de.nrw.hbz.regal.sync.extern.Md5Checksum;
import de.nrw.hbz.regal.sync.extern.RelatedDigitalEntity;
import de.nrw.hbz.regal.sync.extern.StreamType;
/**
* @author Jan Schnasse schnasse@hbz-nrw.de
*
*/
public class EdowebDigitalEntityBuilder implements
DigitalEntityBuilderInterface {
final static Logger logger = LoggerFactory
.getLogger(EdowebDigitalEntityBuilder.class);
Map<String, DigitalEntity> filedIds2DigitalEntity = new HashMap<String, DigitalEntity>();
Map<String, String> groupIds2FileIds = new HashMap<String, String>();
Map<String, List<String>> idmap = new HashMap<String, List<String>>();
@Override
public DigitalEntity build(String location, String pid) {
DigitalEntity dtlDe = buildSimpleBean(location, pid);
if (dtlDe.getStream(StreamType.STRUCT_MAP) != null) {
logger.debug(pid + " is a mets object");
dtlDe = prepareMetsStructure(dtlDe);
dtlDe = addSiblings(dtlDe);
dtlDe = addChildren(dtlDe);
} else {
dtlDe = addSiblings(dtlDe);
dtlDe = addDigitoolChildren(dtlDe);
dtlDe = addChildren(dtlDe);
}
dtlDe = removeEmptyVolumes(dtlDe);
return dtlDe;
}
private DigitalEntity removeEmptyVolumes(final DigitalEntity entity) {
DigitalEntity dtlDe = entity;
List<RelatedDigitalEntity> result = new Vector<RelatedDigitalEntity>();
List<RelatedDigitalEntity> related = entity.getRelated();
for (RelatedDigitalEntity d : related) {
if (DigitalEntityRelation.part_of.toString().equals(d.relation)) {
if (ObjectType.volume.toString()
.equals(d.entity.getUsageType())) {
if (d.entity.getRelated().isEmpty())
continue;
}
}
result.add(d);
}
dtlDe.setRelated(result);
return dtlDe;
}
DigitalEntity buildSimpleBean(String location, String pid) {
DigitalEntity dtlDe = new DigitalEntity(location, pid);
dtlDe.setXml(new File(dtlDe.getLocation() + File.separator + pid
+ ".xml"));
Element root = getXmlRepresentation(dtlDe);
dtlDe.setLabel(getLabel(root));
loadMetadataStreams(dtlDe, root);
setType(dtlDe);
dtlDe.setImportedFrom("http://klio.hbz-nrw.de:1801/webclient/DeliveryManager?pid="
+ pid + "&custom_att_2=default_viewer");
dtlDe.setCreatedBy("digitool");
try {
setCatalogId(dtlDe);
logger.debug("p2a: " + pid + "," + dtlDe.getLegacyId());
} catch (CatalogIdNotFoundException e) {
logger.debug(pid + "has no catalog id");
}
loadDataStream(dtlDe, root);
linkToParent(dtlDe);
return dtlDe;
}
/**
* Tries to find the catalog id (aleph)
*
* @param dtlDe
* the digital entity
*/
void setCatalogId(DigitalEntity dtlDe) {
try {
Element root = XmlUtils.getDocument(dtlDe
.getStream(StreamType.MARC).getFile());
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
xpath.setNamespaceContext(new MarcNamespaceContext());
XPathExpression expr = xpath.compile("//controlfield[@tag='001']");
Object result = expr.evaluate(root, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
if (nodes.getLength() != 1) {
throw new CatalogIdNotFoundException("Found "
+ nodes.getLength() + " ids");
}
String id = nodes.item(0).getTextContent();
dtlDe.addIdentifier(id);
dtlDe.setLegacyId(id);
// logger.debug(dtlDe.getPid() + " add id " + id);
} catch (Exception e) {
throw new CatalogIdNotFoundException(e);
}
}
private void setType(DigitalEntity dtlBean) {
Element root = XmlUtils.getDocument(dtlBean.getStream(
StreamType.CONTROL).getFile());
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
try {
XPathExpression expr = xpath.compile("//partition_c");
Object result = expr.evaluate(root, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
if (nodes.getLength() != 1) {
throw new TypeNotFoundException("Found " + nodes.getLength()
+ " types");
}
dtlBean.setType(nodes.item(0).getTextContent());
// logger.debug(dtlBean.getPid() + " setType to: " +
// dtlBean.getType());
} catch (XPathExpressionException e) {
throw new XPathException(e);
}
}
private DigitalEntity prepareMetsStructure(final DigitalEntity entity) {
DigitalEntity dtlDe = entity;
dtlDe = createTree(entity);
mapGroupIdsToFileIds(entity);
return dtlDe;
}
private void mapGroupIdsToFileIds(DigitalEntity entity) {
try {
Element root = XmlUtils.getDocument(entity.getStream(
StreamType.FILE_SEC).getFile());
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
NodeList volumes = (NodeList) xpath.evaluate("/*/*/*/*/*", root,
XPathConstants.NODESET);
for (int i = 0; i < volumes.getLength(); i++) {
Element item = (Element) volumes.item(i);
String groupId = item.getAttribute("GROUPID");
String fileId = item.getAttribute("ID");
// logger.debug(groupId + " to " + fileId);
groupIds2FileIds.put(groupId, fileId);
}
} catch (XPathExpressionException e) {
logger.warn("", e);
} catch (Exception e) {
logger.debug("", e);
}
}
// private String normalizeLabel(final String volumeLabel) {
//
// String[] parts = volumeLabel.split("\\s|-");
// String camelCaseString = "";
// for (String part : parts) {
// camelCaseString = camelCaseString + toProperCase(part);
// }
// return camelCaseString.replace(":", "-").replace("/", "-");
// }
//
// String toProperCase(String s) {
// return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
// }
private DigitalEntity createTree(final DigitalEntity entity) {
DigitalEntity dtlDe = entity;
try {
Element root = XmlUtils.getDocument(entity.getStream(
StreamType.STRUCT_MAP).getFile());
List<Element> firstLevel = XmlUtils.getElements("/*/*/*/*/*", root,
null);
logger.debug("create volumes for: " + entity.getPid());
for (Element firstLevelElement : firstLevel) {
DigitalEntity v = createDigitalEntity(ObjectType.volume,
firstLevelElement.getAttribute("LABEL"),
dtlDe.getPid(), dtlDe.getLocation());
v.setOrder(firstLevelElement.getAttribute("ORDER"));
dtlDe.addRelated(v, DigitalEntityRelation.part_of.toString());
logger.debug("Create volume " + v.getPid());
List<Element> issues = XmlUtils.getElements("./div",
firstLevelElement, null);
if (issues == null || issues.isEmpty()) {
v.setUsageType(ObjectType.rootElement.toString());
mapFileIdToDigitalEntity(v, firstLevelElement);
} else {
for (Element issue : issues) {
DigitalEntity i = createDigitalEntity(
ObjectType.rootElement,
issue.getAttribute("LABEL"), v.getPid(),
dtlDe.getLocation());
i.setOrder(firstLevelElement.getAttribute("ORDER"));
logger.debug("Create issue " + i.getPid());
v.addRelated(i,
DigitalEntityRelation.part_of.toString());
mapFileIdToDigitalEntity(i, issue);
}
}
}
} catch (XPathException e) {
logger.warn(entity.getPid() + " no volumes found.");
} catch (Exception e) {
logger.debug("", e);
}
return dtlDe;
}
private void mapFileIdToDigitalEntity(DigitalEntity de, Element root) {
final String regex = ".//fptr";
List<Element> files = XmlUtils.getElements(regex, root, null);
for (Element f : files) {
String fileId = f.getAttribute("FILEID");
logger.debug("Key: " + fileId + " Value: " + de.getPid());
filedIds2DigitalEntity.put(fileId, de);
}
}
private DigitalEntity createDigitalEntity(ObjectType type, String label,
String parentPid, String location) {
String prefix = parentPid;
String pid = prefix + "-" + getId(prefix);
DigitalEntity entity = new DigitalEntity(location + File.separator
+ pid, pid);
entity.setLabel(label);
entity.setParentPid(parentPid);
entity.setUsageType(type.toString());
return entity;
}
private String getId(String prefix) {
List<String> ids = null;
if (idmap.containsKey(prefix)) {
ids = idmap.get(prefix);
} else {
ids = new ArrayList<String>();
}
if (ids.size() >= Integer.MAX_VALUE) {
throw new java.lang.ArrayIndexOutOfBoundsException(
"We have serious problem here!");
}
String id = Integer.toString(ids.size());
ids.add(id);
idmap.put(prefix, ids);
return id;
}
private void loadDataStream(DigitalEntity dtlDe, Element root) {
Node streamRef = root.getElementsByTagName("stream_ref").item(0);
String filename = ((Element) streamRef)
.getElementsByTagName("file_name").item(0).getTextContent();
File file = new File(dtlDe.getLocation() + File.separator
+ dtlDe.getPid() + File.separator + filename);
String mime = ((Element) streamRef).getElementsByTagName("mime_type")
.item(0).getTextContent();
String fileId = ((Element) streamRef).getElementsByTagName("file_id")
.item(0).getTextContent();
if (!file.exists()) {
logger.error("The file " + filename
+ " found in DTL Xml does not exist.");
return;
}
logger.debug("found data stream " + file + "," + mime + ","
+ StreamType.DATA + "," + fileId);
dtlDe.setLabel(root.getElementsByTagName("label").item(0)
.getTextContent());
dtlDe.addStream(file, mime, StreamType.DATA, fileId, getMd5(file));
}
private void loadMetadataStreams(DigitalEntity dtlDe, Element root) {
setXmlStream(dtlDe, root.getElementsByTagName("control").item(0),
StreamType.CONTROL);
dtlDe.setUsageType(root.getElementsByTagName("usage_type").item(0)
.getTextContent());
NodeList list = root.getElementsByTagName("md");
for (int i = 0; i < list.getLength(); i++) {
Node item = list.item(i);
String type = getItemType((Element) item);
if (type.compareTo("dc") == 0) {
setXmlStream(dtlDe, item, StreamType.DC);
} else if (type.compareTo("preservation_md") == 0) {
setXmlStream(dtlDe, item, StreamType.PREMIS);
} else if (type.compareTo("text_md") == 0) {
setXmlStream(dtlDe, item, StreamType.TEXT);
} else if (type.compareTo("rights_md") == 0) {
setXmlStream(dtlDe, item, StreamType.RIGHTS);
} else if (type.compareTo("jhove") == 0) {
setXmlStream(dtlDe, item, StreamType.JHOVE);
} else if (type.compareTo("changehistory_md") == 0) {
setXmlStream(dtlDe, item, StreamType.HIST);
} else if (type.compareTo("marc") == 0) {
setMarcStream(dtlDe, item, StreamType.MARC);
} else if (type.compareTo("metsHdr") == 0) {
setXmlStream(dtlDe, item, StreamType.METS_HDR);
} else if (type.compareTo("structMap") == 0) {
setXmlStream(dtlDe, item, StreamType.STRUCT_MAP);
} else if (type.compareTo("fileSec") == 0) {
setXmlStream(dtlDe, item, StreamType.FILE_SEC);
}
}
}
@SuppressWarnings("deprecation")
private void setXmlStream(DigitalEntity dtlDe, Node item, StreamType type) {
try {
File file = new File(dtlDe.getLocation() + File.separator + "."
+ dtlDe.getPid() + "_" + type.toString() + ".xml");
File stream = XmlUtils.stringToFile(file,
XmlUtils.nodeToString(item));
String md5Hash = getMd5(stream);
dtlDe.addStream(stream, "application/xml", type, null, md5Hash);
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("deprecation")
private void setMarcStream(DigitalEntity dtlDe, Node item, StreamType type) {
try {
File file = new File(dtlDe.getLocation() + File.separator + "."
+ dtlDe.getPid() + "_" + type.toString() + ".xml");
File stream = XmlUtils.stringToFile(file, getMarc(item));
String md5Hash = getMd5(stream);
dtlDe.addStream(stream, "application/xml", type, null, md5Hash);
} catch (Exception e) {
e.printStackTrace();
}
}
private String getMd5(File stream) {
Md5Checksum md5 = new Md5Checksum();
return md5.getMd5Checksum(stream);
}
private String getMarc(Node item) {
Element marc = (Element) ((Element) item)
.getElementsByTagName("record").item(0);
marc.setAttribute("xmlns", "http://www.loc.gov/MARC21/slim");
String xmlStr = XmlUtils.nodeToString(marc);
xmlStr = xmlStr.replaceAll("nam 2200000 u 4500",
"00000 a2200000 4500");
return xmlStr;
}
private String getItemType(Element root) {
return root.getElementsByTagName("type").item(0).getTextContent();
}
private String getLabel(Element root) {
List<Element> list = XmlUtils.getElements(
"//datafield[@tag='245']/subfield[@code='a']", root, null);
if (list != null && !list.isEmpty()) {
return list.get(0).getTextContent();
} else {
return root.getElementsByTagName("label").item(0).getTextContent();
}
}
private Element getXmlRepresentation(final DigitalEntity dtlDe) {
File digitalEntityFile = new File(dtlDe.getLocation() + File.separator
+ dtlDe.getPid() + ".xml");
return XmlUtils.getDocument(digitalEntityFile);
}
private DigitalEntity addSiblings(final DigitalEntity entity) {
DigitalEntity dtlDe = entity;
Element root;
try {
root = XmlUtils.getDocument(entity.getXml());
NodeList list = root.getElementsByTagName("relation");
for (int i = 0; i < list.getLength(); i++) {
Node item = list.item(i);
String relPid = ((Element) item).getElementsByTagName("pid")
.item(0).getTextContent();
String usageType = ((Element) item)
.getElementsByTagName("usage_type").item(0)
.getTextContent();
String type = ((Element) item).getElementsByTagName("type")
.item(0).getTextContent();
if (type.compareTo(DigitalEntityRelation.manifestation
.toString()) == 0) {
DigitalEntity b = buildSimpleBean(entity.getLocation(),
relPid);
logger.debug("Add sibling " + b.getPid() + " to "
+ entity.getPid() + " utilizing relation "
+ usageType);
dtlDe.addRelated(b, usageType);
}
}
} catch (Exception e) {
logger.warn("", e);
}
return dtlDe;
}
private DigitalEntity addChildren(final DigitalEntity entity) {
DigitalEntity dtlDe = entity;
try {
Element root = XmlUtils.getDocument(entity.getXml());
NodeList list = root.getElementsByTagName("relation");
for (int i = 0; i < list.getLength(); i++) {
Node item = list.item(i);
String relPid = ((Element) item).getElementsByTagName("pid")
.item(0).getTextContent();
String usageType = ((Element) item)
.getElementsByTagName("usage_type").item(0)
.getTextContent();
String type = ((Element) item).getElementsByTagName("type")
.item(0).getTextContent();
String mimeType = ((Element) item)
.getElementsByTagName("mime_type").item(0)
.getTextContent();
if (type.compareTo(DigitalEntityRelation.include.toString()) == 0
&& mimeType.equals("application/pdf")
&& (usageType.compareTo(DigitalEntityRelation.ARCHIVE
.toString()) != 0)) {
try {
DigitalEntity b = build(entity.getLocation(), relPid);
b.setUsageType(usageType);
addToTree(dtlDe, b);
} catch (Exception e) {
e.printStackTrace();
}
} else if (type.compareTo(DigitalEntityRelation.include
.toString()) == 0
&& mimeType.equals("application/zip")
&& (usageType.compareTo(DigitalEntityRelation.VIEW
.toString()) != 0)) {
try {
DigitalEntity b = build(entity.getLocation(), relPid);
b.setUsageType(usageType);
addToTree(dtlDe, b);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
logger.warn("", e);
}
return dtlDe;
}
private DigitalEntity addDigitoolChildren(final DigitalEntity entity) {
DigitalEntity dtlDe = entity;
try {
Element root = XmlUtils.getDocument(entity.getXml());
NodeList list = root.getElementsByTagName("relation");
for (int i = 0; i < list.getLength(); i++) {
Node item = list.item(i);
String relPid = ((Element) item).getElementsByTagName("pid")
.item(0).getTextContent();
String usageType = ((Element) item)
.getElementsByTagName("usage_type").item(0)
.getTextContent();
String type = ((Element) item).getElementsByTagName("type")
.item(0).getTextContent();
String mimeType = ((Element) item)
.getElementsByTagName("mime_type").item(0)
.getTextContent();
if (type.compareTo(DigitalEntityRelation.include.toString()) == 0
&& mimeType.equals("application/pdf")
&& (usageType.compareTo(DigitalEntityRelation.ARCHIVE
.toString()) != 0)) {
try {
DigitalEntity b = build(entity.getLocation(), relPid);
// logger.debug(b.getPid() + " is child of "
// + dtlDe.getPid());
b.setUsageType(usageType);
dtlDe.setIsParent(true);
b.setParentPid(dtlDe.getPid());
dtlDe.addRelated(b,
DigitalEntityRelation.part_of.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
logger.warn("", e);
}
return dtlDe;
}
private void linkToParent(DigitalEntity dtlDe) {
try {
Element root = XmlUtils.getDocument(dtlDe.getXml());
NodeList list = root.getElementsByTagName("relation");
for (int i = 0; i < list.getLength(); i++) {
Node item = list.item(i);
String relPid = ((Element) item).getElementsByTagName("pid")
.item(0).getTextContent();
String type = ((Element) item).getElementsByTagName("type")
.item(0).getTextContent();
if (type.compareTo(DigitalEntityRelation.part_of.toString()) == 0) {
dtlDe.setIsParent(false);
dtlDe.setParentPid(relPid);
}
}
} catch (Exception e) {
logger.warn("", e);
}
}
private void addToTree(DigitalEntity dtlDe, DigitalEntity related) {
DigitalEntity parent = findParent(dtlDe, related);
if (parent == null) {
logger.info(related.getPid() + " is not longer part of tree.");
return;
}
parent.setIsParent(true);
related.setParentPid(parent.getPid());
parent.addRelated(related, DigitalEntityRelation.part_of.toString());
logger.debug(related.getPid() + " is child of " + parent.getPid());
}
private DigitalEntity findParent(DigitalEntity dtlDe, DigitalEntity related) {
if (!(related.getUsageType().compareTo("VIEW") == 0)
&& !(related.getUsageType().compareTo("VIEW_MAIN") == 0)) {
System.out.println("Related of wrong type: " + related.getPid());
return dtlDe;
}
String groupId = related.getStream(StreamType.DATA).getFileId();
String fileId = groupIds2FileIds.get(groupId);
DigitalEntity parent = this.filedIds2DigitalEntity.get(fileId);
if (parent != null) {
related.setUsageType(ObjectType.file.toString());
}
return parent;
}
@SuppressWarnings("javadoc")
public class MarcNamespaceContext implements NamespaceContext {
public String getNamespaceURI(String prefix) {
if (prefix == null)
throw new NullPointerException("Null prefix");
else if ("marc".equals(prefix))
return "http://www.loc.gov/MARC21/slim";
else if ("xml".equals(prefix))
return XMLConstants.XML_NS_URI;
return XMLConstants.NULL_NS_URI;
}
// This method isn't necessary for XPath processing.
public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}
// This method isn't necessary for XPath processing either.
@SuppressWarnings("rawtypes")
public Iterator getPrefixes(String uri) {
throw new UnsupportedOperationException();
}
}
@SuppressWarnings({ "javadoc", "serial" })
public class TypeNotFoundException extends RuntimeException {
public TypeNotFoundException(String message) {
super(message);
}
}
@SuppressWarnings({ "javadoc", "serial" })
public class CatalogIdNotFoundException extends RuntimeException {
public CatalogIdNotFoundException(String message) {
super(message);
}
public CatalogIdNotFoundException(Throwable cause) {
super(cause);
}
}
@SuppressWarnings({ "javadoc", "serial" })
public class XPathException extends RuntimeException {
public XPathException(Throwable cause) {
super(cause);
}
public XPathException(String message, Throwable cause) {
super(message, cause);
}
}
}
|
edoweb/regal-import
|
edoweb-sync/src/main/java/de/nrw/hbz/regal/sync/ingest/EdowebDigitalEntityBuilder.java
|
Java
|
apache-2.0
| 21,427 |
/*
* Copyright 2015 Raffael Herzog
*
* 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 ch.raffael.guards;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specifies that this method does not change the state of the object in any ways.
*
* It's the same as `@Contract(pure=true)` using IDEA annotations.
*
* @author <a href="mailto:herzog@raffael.ch">Raffael Herzog</a>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Pure {
}
|
Abnaxos/guards
|
annotations/src/main/java/ch/raffael/guards/Pure.java
|
Java
|
apache-2.0
| 1,167 |
package fr.ebiz.computer_database.model;
import javax.persistence.*;
/**
* Created by ebiz on 31/05/17.
*/
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String role;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
|
ckeita/training-java
|
computer-database/core/src/main/java/fr/ebiz/computer_database/model/Role.java
|
Java
|
apache-2.0
| 457 |
package com.hs.mail.smtp.processor.hook;
import java.util.StringTokenizer;
import org.junit.AfterClass;
import org.junit.Test;
public class DNSRBLHandlerTest {
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void test() {
String ipAddress = "1.2.3.4";
StringBuffer sb = new StringBuffer();
StringTokenizer st = new StringTokenizer(ipAddress, " .", false);
while (st.hasMoreTokens()) {
sb.insert(0, st.nextToken() + ".");
}
String reversedOctets = sb.toString();
System.out.println(reversedOctets);
}
}
|
svn2github/hwmail-mirror
|
hedwig-server/src/test/java/com/hs/mail/smtp/processor/hook/DNSRBLHandlerTest.java
|
Java
|
apache-2.0
| 640 |
module Rtree
class BoundingBox < Struct.new(:top_left, :bottom_right)
def self.from_points(points)
x0 = points.min { |a,b| a.x <=> b.x }.x
y0 = points.min { |a,b| a.y <=> b.y }.y
x1 = points.max { |a,b| a.x <=> b.x }.x
y1 = points.max { |a,b| a.y <=> b.y }.y
BoundingBox.new(Point.new(x0, y0), Point.new(x1, y1))
end
def self.merged_bound_box(shapes)
self.minimum_bounding_rectangle(shapes.map { |s| s.bounding_box })
end
def self.minimum_bounding_rectangle(bounding_boxes)
x0 = bounding_boxes.min { |a,b| a.top_left.x <=> b.top_left.x }.top_left.x
y0 = bounding_boxes.min { |a,b| a.top_left.y <=> b.top_left.y }.top_left.y
x1 = bounding_boxes.max { |a,b| a.bottom_right.x <=> b.bottom_right.x }.bottom_right.x
y1 = bounding_boxes.max { |a,b| a.bottom_right.y <=> b.bottom_right.y }.bottom_right.y
BoundingBox.new(Point.new(x0, y0), Point.new(x1, y1))
end
def overlap(other_bounding_box)
x0, y0 = self.top_left.x, self.top_left.y
x1, y1 = self.bottom_right.x, self.bottom_right.y
x2, y2 = other_bounding_box.top_left.x, other_bounding_box.top_left.y
x3, y3 = other_bounding_box.bottom_right.x, other_bounding_box.bottom_right.y
half_w0, half_h0 = (x1-x0)/2, (y1-y0)/2
half_w1, half_h1 = (x3-x2)/2, (y3-y2)/2
within_x = ((x1+x0)/2 - (x3+x2)/2).abs <= half_w0 + half_w1
within_y = ((y1+y0)/2 - (y3+y2)/2).abs <= half_h0 + half_h1
within_x && within_y
end
end
end
|
newmana/rtree
|
lib/rtree/bounding_box.rb
|
Ruby
|
apache-2.0
| 1,520 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Tokens;
namespace Muscularity.Web.Infrastructure
{
public class JwtTokenServiceOptions
{
public TimeSpan TimeToLive { get; set; }
public string Issuer { get; set; }
public string Audience { get; set; }
public SecurityKey SigningKey { get; set; }
}
}
|
jbload/Muscularity
|
Muscularity.Web/Infrastructure/JwtTokenServiceOptions.cs
|
C#
|
apache-2.0
| 444 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.greengrassv2.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.greengrassv2.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* EffectiveDeploymentMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class EffectiveDeploymentMarshaller {
private static final MarshallingInfo<String> DEPLOYMENTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deploymentId").build();
private static final MarshallingInfo<String> DEPLOYMENTNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deploymentName").build();
private static final MarshallingInfo<String> IOTJOBID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("iotJobId").build();
private static final MarshallingInfo<String> IOTJOBARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("iotJobArn").build();
private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("description").build();
private static final MarshallingInfo<String> TARGETARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("targetArn").build();
private static final MarshallingInfo<String> COREDEVICEEXECUTIONSTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("coreDeviceExecutionStatus").build();
private static final MarshallingInfo<String> REASON_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("reason").build();
private static final MarshallingInfo<java.util.Date> CREATIONTIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("creationTimestamp").timestampFormat("unixTimestamp").build();
private static final MarshallingInfo<java.util.Date> MODIFIEDTIMESTAMP_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("modifiedTimestamp").timestampFormat("unixTimestamp").build();
private static final EffectiveDeploymentMarshaller instance = new EffectiveDeploymentMarshaller();
public static EffectiveDeploymentMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(EffectiveDeployment effectiveDeployment, ProtocolMarshaller protocolMarshaller) {
if (effectiveDeployment == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(effectiveDeployment.getDeploymentId(), DEPLOYMENTID_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getDeploymentName(), DEPLOYMENTNAME_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getIotJobId(), IOTJOBID_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getIotJobArn(), IOTJOBARN_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getTargetArn(), TARGETARN_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getCoreDeviceExecutionStatus(), COREDEVICEEXECUTIONSTATUS_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getReason(), REASON_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getCreationTimestamp(), CREATIONTIMESTAMP_BINDING);
protocolMarshaller.marshall(effectiveDeployment.getModifiedTimestamp(), MODIFIEDTIMESTAMP_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-greengrassv2/src/main/java/com/amazonaws/services/greengrassv2/model/transform/EffectiveDeploymentMarshaller.java
|
Java
|
apache-2.0
| 5,040 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.mediatailor.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/mediatailor-2018-04-23/ListTagsForResource" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListTagsForResourceResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
* </p>
*/
private java.util.Map<String, String> tags;
/**
* <p>
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
* </p>
*
* @return A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
*/
public java.util.Map<String, String> getTags() {
return tags;
}
/**
* <p>
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
* </p>
*
* @param tags
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
*/
public void setTags(java.util.Map<String, String> tags) {
this.tags = tags;
}
/**
* <p>
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
* </p>
*
* @param tags
* A comma-separated list of tag key:value pairs. For example: { "Key1": "Value1", "Key2": "Value2" }
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListTagsForResourceResult withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
}
public ListTagsForResourceResult addTagsEntry(String key, String value) {
if (null == this.tags) {
this.tags = new java.util.HashMap<String, String>();
}
if (this.tags.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.tags.put(key, value);
return this;
}
/**
* Removes all the entries added into Tags.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListTagsForResourceResult clearTagsEntries() {
this.tags = null;
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getTags() != null)
sb.append("Tags: ").append(getTags());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListTagsForResourceResult == false)
return false;
ListTagsForResourceResult other = (ListTagsForResourceResult) obj;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
return hashCode;
}
@Override
public ListTagsForResourceResult clone() {
try {
return (ListTagsForResourceResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
jentfoo/aws-sdk-java
|
aws-java-sdk-mediatailor/src/main/java/com/amazonaws/services/mediatailor/model/ListTagsForResourceResult.java
|
Java
|
apache-2.0
| 4,860 |
/*
* 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.carbondata.processing.loading.sort.unsafe.holder;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Comparator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.carbondata.common.logging.LogService;
import org.apache.carbondata.common.logging.LogServiceFactory;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.datastore.impl.FileFactory;
import org.apache.carbondata.core.util.CarbonProperties;
import org.apache.carbondata.core.util.CarbonUtil;
import org.apache.carbondata.processing.loading.row.IntermediateSortTempRow;
import org.apache.carbondata.processing.loading.sort.SortStepRowHandler;
import org.apache.carbondata.processing.sort.exception.CarbonSortKeyAndGroupByException;
import org.apache.carbondata.processing.sort.sortdata.IntermediateSortTempRowComparator;
import org.apache.carbondata.processing.sort.sortdata.SortParameters;
import org.apache.carbondata.processing.sort.sortdata.TableFieldStat;
public class UnsafeSortTempFileChunkHolder implements SortTempChunkHolder {
/**
* LOGGER
*/
private static final LogService LOGGER =
LogServiceFactory.getLogService(UnsafeSortTempFileChunkHolder.class.getName());
/**
* temp file
*/
private File tempFile;
/**
* read stream
*/
private DataInputStream stream;
/**
* entry count
*/
private int entryCount;
/**
* return row
*/
private IntermediateSortTempRow returnRow;
private int readBufferSize;
private String compressorName;
private IntermediateSortTempRow[] currentBuffer;
private IntermediateSortTempRow[] backupBuffer;
private boolean isBackupFilled;
private boolean prefetch;
private int bufferSize;
private int bufferRowCounter;
private ExecutorService executorService;
private Future<Void> submit;
private int prefetchRecordsProceesed;
/**
* totalRecordFetch
*/
private int totalRecordFetch;
private int numberOfObjectRead;
private TableFieldStat tableFieldStat;
private SortStepRowHandler sortStepRowHandler;
private Comparator<IntermediateSortTempRow> comparator;
/**
* Constructor to initialize
*/
public UnsafeSortTempFileChunkHolder(File tempFile, SortParameters parameters) {
// set temp file
this.tempFile = tempFile;
this.readBufferSize = parameters.getBufferSize();
this.compressorName = parameters.getSortTempCompressorName();
this.tableFieldStat = new TableFieldStat(parameters);
this.sortStepRowHandler = new SortStepRowHandler(tableFieldStat);
this.executorService = Executors.newFixedThreadPool(1);
comparator = new IntermediateSortTempRowComparator(parameters.getNoDictionarySortColumn());
initialize();
}
/**
* This method will be used to initialize
*
* @throws CarbonSortKeyAndGroupByException problem while initializing
*/
public void initialize() {
prefetch = Boolean.parseBoolean(CarbonProperties.getInstance()
.getProperty(CarbonCommonConstants.CARBON_MERGE_SORT_PREFETCH,
CarbonCommonConstants.CARBON_MERGE_SORT_PREFETCH_DEFAULT));
bufferSize = Integer.parseInt(CarbonProperties.getInstance()
.getProperty(CarbonCommonConstants.CARBON_PREFETCH_BUFFERSIZE,
CarbonCommonConstants.CARBON_PREFETCH_BUFFERSIZE_DEFAULT));
initialise();
}
private void initialise() {
try {
stream = FileFactory.getDataInputStream(tempFile.getPath(), FileFactory.FileType.LOCAL,
readBufferSize, compressorName);
this.entryCount = stream.readInt();
LOGGER.info("Processing unsafe mode file rows with size : " + entryCount);
if (prefetch) {
new DataFetcher(false).call();
totalRecordFetch += currentBuffer.length;
if (totalRecordFetch < this.entryCount) {
submit = executorService.submit(new DataFetcher(true));
}
}
} catch (FileNotFoundException e) {
LOGGER.error(e);
throw new RuntimeException(tempFile + " No Found", e);
} catch (IOException e) {
LOGGER.error(e);
throw new RuntimeException(tempFile + " No Found", e);
} catch (Exception e) {
LOGGER.error(e);
throw new RuntimeException(tempFile + " Problem while reading", e);
}
}
/**
* This method will be used to read new row from file
*
* @throws CarbonSortKeyAndGroupByException problem while reading
*/
@Override
public void readRow() throws CarbonSortKeyAndGroupByException {
if (prefetch) {
fillDataForPrefetch();
} else {
try {
this.returnRow = sortStepRowHandler.readIntermediateSortTempRowFromInputStream(stream);
this.numberOfObjectRead++;
} catch (IOException e) {
throw new CarbonSortKeyAndGroupByException("Problems while reading row", e);
}
}
}
private void fillDataForPrefetch() {
if (bufferRowCounter >= bufferSize) {
if (isBackupFilled) {
bufferRowCounter = 0;
currentBuffer = backupBuffer;
totalRecordFetch += currentBuffer.length;
isBackupFilled = false;
if (totalRecordFetch < this.entryCount) {
submit = executorService.submit(new DataFetcher(true));
}
} else {
try {
submit.get();
} catch (Exception e) {
LOGGER.error(e);
}
bufferRowCounter = 0;
currentBuffer = backupBuffer;
isBackupFilled = false;
totalRecordFetch += currentBuffer.length;
if (totalRecordFetch < this.entryCount) {
submit = executorService.submit(new DataFetcher(true));
}
}
}
prefetchRecordsProceesed++;
returnRow = currentBuffer[bufferRowCounter++];
}
/**
* get a batch of row, this interface is used in reading compressed sort temp files
*
* @param expected expected number in a batch
* @return a batch of row
* @throws IOException if error occurs while reading from stream
*/
private IntermediateSortTempRow[] readBatchedRowFromStream(int expected)
throws IOException {
IntermediateSortTempRow[] holders = new IntermediateSortTempRow[expected];
for (int i = 0; i < expected; i++) {
IntermediateSortTempRow holder
= sortStepRowHandler.readIntermediateSortTempRowFromInputStream(stream);
holders[i] = holder;
}
this.numberOfObjectRead += expected;
return holders;
}
/**
* below method will be used to get the row
*
* @return row
*/
public IntermediateSortTempRow getRow() {
return this.returnRow;
}
/**
* below method will be used to check whether any more records are present
* in file or not
*
* @return more row present in file
*/
public boolean hasNext() {
if (prefetch) {
return this.prefetchRecordsProceesed < this.entryCount;
}
return this.numberOfObjectRead < this.entryCount;
}
/**
* Below method will be used to close streams
*/
public void close() {
CarbonUtil.closeStreams(stream);
if (null != executorService && !executorService.isShutdown()) {
executorService.shutdownNow();
}
}
/**
* This method will number of entries
*
* @return entryCount
*/
public int numberOfRows() {
return entryCount;
}
@Override public int compareTo(SortTempChunkHolder other) {
return comparator.compare(returnRow, other.getRow());
}
@Override public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof UnsafeSortTempFileChunkHolder)) {
return false;
}
UnsafeSortTempFileChunkHolder o = (UnsafeSortTempFileChunkHolder) obj;
return this == o;
}
@Override public int hashCode() {
int hash = 0;
hash += tableFieldStat.hashCode();
hash += tempFile.hashCode();
return hash;
}
private final class DataFetcher implements Callable<Void> {
private boolean isBackUpFilling;
private int numberOfRecords;
private DataFetcher(boolean backUp) {
isBackUpFilling = backUp;
calculateNumberOfRecordsToBeFetched();
}
private void calculateNumberOfRecordsToBeFetched() {
int numberOfRecordsLeftToBeRead = entryCount - totalRecordFetch;
numberOfRecords =
bufferSize < numberOfRecordsLeftToBeRead ? bufferSize : numberOfRecordsLeftToBeRead;
}
@Override public Void call() throws Exception {
try {
if (isBackUpFilling) {
backupBuffer = prefetchRecordsFromFile(numberOfRecords);
isBackupFilled = true;
} else {
currentBuffer = prefetchRecordsFromFile(numberOfRecords);
}
} catch (Exception e) {
LOGGER.error(e);
}
return null;
}
}
/**
* This method will read the records from sort temp file and keep it in a buffer
*
* @param numberOfRecords number of records to be read
* @return batch of intermediate sort temp row
* @throws IOException if error occurs reading records from file
*/
private IntermediateSortTempRow[] prefetchRecordsFromFile(int numberOfRecords)
throws IOException {
return readBatchedRowFromStream(numberOfRecords);
}
}
|
jatin9896/incubator-carbondata
|
processing/src/main/java/org/apache/carbondata/processing/loading/sort/unsafe/holder/UnsafeSortTempFileChunkHolder.java
|
Java
|
apache-2.0
| 10,153 |
package service
import (
"context"
"sync"
artmdl "go-common/app/interface/openplatform/article/model"
accmdl "go-common/app/service/main/account/model"
"go-common/app/service/main/feed/dao"
"go-common/library/log"
"go-common/library/sync/errgroup"
)
const _upsArtBulkSize = 50
// attenUpArticles get new articles of attention uppers.
func (s *Service) attenUpArticles(c context.Context, minTotalCount int, mid int64, ip string) (res map[int64][]*artmdl.Meta, err error) {
var mids []int64
arg := &accmdl.ArgMid{Mid: mid}
if mids, err = s.accRPC.Attentions3(c, arg); err != nil {
dao.PromError("关注rpc接口:Attentions", "s.accRPC.Attentions(%d) error(%v)", mid, err)
return
}
if len(mids) == 0 {
return
}
count := minTotalCount/len(mids) + s.c.Feed.MinUpCnt
return s.upsArticle(c, count, ip, mids...)
}
func (s *Service) upsArticle(c context.Context, count int, ip string, mids ...int64) (res map[int64][]*artmdl.Meta, err error) {
dao.MissedCount.Add("upArt", int64(len(mids)))
var (
group *errgroup.Group
errCtx context.Context
midsLen, i int
mutex = sync.Mutex{}
)
res = make(map[int64][]*artmdl.Meta)
group, errCtx = errgroup.WithContext(c)
midsLen = len(mids)
for ; i < midsLen; i += _upsArtBulkSize {
var partMids []int64
if i+_upsArcBulkSize > midsLen {
partMids = mids[i:]
} else {
partMids = mids[i : i+_upsArtBulkSize]
}
group.Go(func() (err error) {
var tmpRes map[int64][]*artmdl.Meta
arg := &artmdl.ArgUpsArts{Mids: partMids, Pn: 1, Ps: count, RealIP: ip}
if tmpRes, err = s.artRPC.UpsArtMetas(errCtx, arg); err != nil {
log.Error("s.artRPC.UpsArtMetas(%+v) error(%v)", arg, err)
err = nil
return
}
mutex.Lock()
for mid, arcs := range tmpRes {
for _, arc := range arcs {
if arc.AttrVal(artmdl.AttrBitNoDistribute) {
continue
}
res[mid] = append(res[mid], arc)
}
}
mutex.Unlock()
return
})
}
group.Wait()
return
}
func (s *Service) articles(c context.Context, ip string, aids ...int64) (res map[int64]*artmdl.Meta, err error) {
var (
mutex = sync.Mutex{}
bulkSize = s.c.Feed.BulkSize
)
res = make(map[int64]*artmdl.Meta, len(aids))
group, errCtx := errgroup.WithContext(c)
aidsLen := len(aids)
for i := 0; i < aidsLen; i += bulkSize {
var partAids []int64
if i+bulkSize < aidsLen {
partAids = aids[i : i+bulkSize]
} else {
partAids = aids[i:aidsLen]
}
group.Go(func() error {
var (
tmpRes map[int64]*artmdl.Meta
artErr error
arg *artmdl.ArgAids
)
arg = &artmdl.ArgAids{Aids: partAids, RealIP: ip}
if tmpRes, artErr = s.artRPC.ArticleMetas(errCtx, arg); artErr != nil {
log.Error("s.artRPC.ArticleMetas() error(%v)", artErr)
return nil
}
mutex.Lock()
for aid, arc := range tmpRes {
if arc.AttrVal(artmdl.AttrBitNoDistribute) {
continue
}
res[aid] = arc
}
mutex.Unlock()
return nil
})
}
group.Wait()
return
}
|
LQJJ/demo
|
126-go-common-master/app/service/main/feed/service/article.go
|
GO
|
apache-2.0
| 2,972 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.redshiftdataapi.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.redshiftdataapi.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* BatchExecuteStatementResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BatchExecuteStatementResultJsonUnmarshaller implements Unmarshaller<BatchExecuteStatementResult, JsonUnmarshallerContext> {
public BatchExecuteStatementResult unmarshall(JsonUnmarshallerContext context) throws Exception {
BatchExecuteStatementResult batchExecuteStatementResult = new BatchExecuteStatementResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return batchExecuteStatementResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("ClusterIdentifier", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setClusterIdentifier(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("CreatedAt", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setCreatedAt(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
}
if (context.testExpression("Database", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setDatabase(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("DbUser", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setDbUser(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Id", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("SecretArn", targetDepth)) {
context.nextToken();
batchExecuteStatementResult.setSecretArn(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return batchExecuteStatementResult;
}
private static BatchExecuteStatementResultJsonUnmarshaller instance;
public static BatchExecuteStatementResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new BatchExecuteStatementResultJsonUnmarshaller();
return instance;
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-redshiftdataapi/src/main/java/com/amazonaws/services/redshiftdataapi/model/transform/BatchExecuteStatementResultJsonUnmarshaller.java
|
Java
|
apache-2.0
| 4,194 |
//
// Bitmap.hpp
// GaLiong
//
// Created by Liong on ??/??/??.
//
#include "Include/Bmp.hpp"
_L_BEGIN
namespace Media
{
// Public
Bmp::Bmp(Image& instance)
{
}
Bmp::~Bmp()
{
}
bool Bmp::InitHeader()
{
FileHeader f;
InfoHeader i;
stream.read((char *)&f, sizeof(FileHeader));
if (f.Type != 0x4D42)
return false;
stream.read((char *)&i, sizeof(InfoHeader));
if (i.BitCount != 24)
return false;
size = { i.Width, i.Height };
length = i.Width * i.Height * 3;
stream.seekg(f.OffBits, stream.beg);
return true;
}
Buffer Bmp::ReadData(BufferLength length)
{
Buffer data = new Byte[length]; // NEED TO BE DELETED.
stream.read((char *)data, length);
return data;
}
TextureRef Bmp::ToTexture(wchar_t *path, Flag option)
{
Log << L"Bmp: Try loading " << path << L"...";
if (stream.is_open())
stream.close();
stream.open(path, stream.in | stream.binary | stream._Nocreate);
TextureRef ref;
Size size;
BufferLength dataLength;
if (InitHeader(size, dataLength))
{
Buffer data = ReadData(dataLength);
if (!data)
return TextureRef();
ref = TextureManager.NewTexture(dataLength, data, size, Texture::PixelFormat::BGR, Texture::ByteSize::UByte);
if ((option & FileReadOption::NoGenerate) == FileReadOption::None)
ref.lock()->Generate();
}
else
{
Log.Log((L"Bmp: Failed in loading " + wstring(path) + L"!").c_str(), Logger::WarningLevel::Warn);
return TextureRef();
}
if ((option & FileReadOption::NoClose) == FileReadOption::None)
stream.close();
Log << L"Bmp: Succeeded!";
return ref;
}
// Derived from [LiongFramework::Media::Image]
Buffer Bmp::GetChunk(Point position, Size size)
{
return _Bitmap::GetChunk(position, size);
}
BufferLength Bmp::GetInterpretedLength(PixelType pixelType)
{
return _Bitmap.GetInterpretedLength(pixelType);
}
Byte* Bmp::GetPixel(Point position)
{
return _Bitmap.GetPixel(position);
}
Size Bmp::GetSize()
{
return _Bitmap.GetSize();
}
bool Bmp::IsEmpty()
{
return _Bitmap.IsEmpty();
}
Buffer Bmp::Interpret(PixelType pixelType)
{
return _Bitmap.Interpret(pixelType);
}
}
_L_END
|
PENGUINLIONG/GaLiong
|
GaLiong/Bmp.cpp
|
C++
|
apache-2.0
| 2,500 |
package coreaf.ui.pages;
public class HomePage {
}
|
AKSahu/WebAutomationFrameworks
|
SeleniumUIAutoTest/src/coreaf/ui/pages/HomePage.java
|
Java
|
apache-2.0
| 53 |
package com.wjc.slience.mymap.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
import com.wjc.slience.mymap.R;
import com.wjc.slience.mymap.common.ActivityCollector;
import com.wjc.slience.mymap.common.LogUtil;
import com.wjc.slience.mymap.db.MyMapDB;
import com.wjc.slience.mymap.model.Way;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
/**
* 日志信息页面显示
*/
public class MsgActivity extends Activity {
TextView msg;
String msgTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msg);
//ActivityCollector.getInstance().addActivity(this);
msg = (TextView) findViewById(R.id.msg);
msgTxt = LogUtil.getInstance().readTheTrip();
msg.setText(msgTxt);
}
@Override
protected void onResume() {
super.onResume();
msgTxt = LogUtil.getInstance().readTheTrip();
msg.setText(msgTxt);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent(MsgActivity.this,ChooseActivity.class);
startActivity(intent);
finish();
}
return super.onKeyDown(keyCode, event);
}
}
|
root0301/MyMap
|
app/src/main/java/com/wjc/slience/mymap/activity/MsgActivity.java
|
Java
|
apache-2.0
| 1,450 |
/**
*
*/
package com.sivalabs.demo.security;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import com.sivalabs.demo.entities.Role;
import com.sivalabs.demo.entities.User;
/**
* @author Siva
*
*/
public class AuthenticatedUser extends org.springframework.security.core.userdetails.User
{
private static final long serialVersionUID = 1L;
private User user;
public AuthenticatedUser(User user)
{
super(user.getEmail(), user.getPassword(), getAuthorities(user));
this.user = user;
}
public User getUser()
{
return user;
}
private static Collection<? extends GrantedAuthority> getAuthorities(User user)
{
Set<String> roleAndPermissions = new HashSet<>();
List<Role> roles = user.getRoles();
for (Role role : roles)
{
roleAndPermissions.add(role.getName());
}
String[] roleNames = new String[roleAndPermissions.size()];
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(roleAndPermissions.toArray(roleNames));
return authorities;
}
}
|
sivaprasadreddy/springboot-learn-by-example
|
chapter-13/springboot-thymeleaf-security-demo/src/main/java/com/sivalabs/demo/security/AuthenticatedUser.java
|
Java
|
apache-2.0
| 1,192 |
/*
* 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.kafka.common.utils;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
/**
* This classes exposes low-level methods for reading/writing from byte streams or buffers.
*/
public final class ByteUtils {
private ByteUtils() {}
/**
* Read an unsigned integer from the given position without modifying the buffers position
*
* @param buffer the buffer to read from
* @param index the index from which to read the integer
* @return The integer read, as a long to avoid signedness
*/
public static long readUnsignedInt(ByteBuffer buffer, int index) {
return buffer.getInt(index) & 0xffffffffL;
}
/**
* Read an unsigned integer stored in little-endian format from the {@link InputStream}.
*
* @param in The stream to read from
* @return The integer read (MUST BE TREATED WITH SPECIAL CARE TO AVOID SIGNEDNESS)
*/
public static int readUnsignedIntLE(InputStream in) throws IOException {
return in.read()
| (in.read() << 8)
| (in.read() << 16)
| (in.read() << 24);
}
/**
* Read an unsigned integer stored in little-endian format from a byte array
* at a given offset.
*
* @param buffer The byte array to read from
* @param offset The position in buffer to read from
* @return The integer read (MUST BE TREATED WITH SPECIAL CARE TO AVOID SIGNEDNESS)
*/
public static int readUnsignedIntLE(byte[] buffer, int offset) {
return (buffer[offset] << 0 & 0xff)
| ((buffer[offset + 1] & 0xff) << 8)
| ((buffer[offset + 2] & 0xff) << 16)
| ((buffer[offset + 3] & 0xff) << 24);
}
/**
* Write the given long value as a 4 byte unsigned integer. Overflow is ignored.
*
* @param buffer The buffer to write to
* @param index The position in the buffer at which to begin writing
* @param value The value to write
*/
public static void writeUnsignedInt(ByteBuffer buffer, int index, long value) {
buffer.putInt(index, (int) (value & 0xffffffffL));
}
/**
* Write the given long value as a 4 byte unsigned integer. Overflow is ignored.
*
* @param buffer The buffer to write to
* @param value The value to write
*/
public static void writeUnsignedInt(ByteBuffer buffer, long value) {
buffer.putInt((int) (value & 0xffffffffL));
}
/**
* Write an unsigned integer in little-endian format to the {@link OutputStream}.
*
* @param out The stream to write to
* @param value The value to write
*/
public static void writeUnsignedIntLE(OutputStream out, int value) throws IOException {
out.write(value);
out.write(value >>> 8);
out.write(value >>> 16);
out.write(value >>> 24);
}
/**
* Write an unsigned integer in little-endian format to a byte array
* at a given offset.
*
* @param buffer The byte array to write to
* @param offset The position in buffer to write to
* @param value The value to write
*/
public static void writeUnsignedIntLE(byte[] buffer, int offset, int value) {
buffer[offset] = (byte) value;
buffer[offset + 1] = (byte) (value >>> 8);
buffer[offset + 2] = (byte) (value >>> 16);
buffer[offset + 3] = (byte) (value >>> 24);
}
/**
* Read an integer stored in variable-length format using zig-zag decoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>.
*
* @param buffer The buffer to read from
* @return The integer read
*
* @throws IllegalArgumentException if variable-length value does not terminate after 5 bytes have been read
*/
public static int readVarint(ByteBuffer buffer) {
int value = 0;
int i = 0;
int b;
while (((b = buffer.get()) & 0x80) != 0) {
value |= (b & 0x7f) << i;
i += 7;
if (i > 28)
throw illegalVarintException(value);
}
value |= b << i;
return (value >>> 1) ^ -(value & 1);
}
/**
* Read an integer stored in variable-length format using zig-zag decoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>.
*
* @param in The input to read from
* @return The integer read
*
* @throws IllegalArgumentException if variable-length value does not terminate after 5 bytes have been read
* @throws IOException if {@link DataInput} throws {@link IOException}
*/
public static int readVarint(DataInput in) throws IOException {
int value = 0;
int i = 0;
int b;
while (((b = in.readByte()) & 0x80) != 0) {
value |= (b & 0x7f) << i;
i += 7;
if (i > 28)
throw illegalVarintException(value);
}
value |= b << i;
return (value >>> 1) ^ -(value & 1);
}
/**
* Read a long stored in variable-length format using zig-zag decoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>.
*
* @param in The input to read from
* @return The long value read
*
* @throws IllegalArgumentException if variable-length value does not terminate after 10 bytes have been read
* @throws IOException if {@link DataInput} throws {@link IOException}
*/
public static long readVarlong(DataInput in) throws IOException {
long value = 0L;
int i = 0;
long b;
while (((b = in.readByte()) & 0x80) != 0) {
value |= (b & 0x7f) << i;
i += 7;
if (i > 63)
throw illegalVarlongException(value);
}
value |= b << i;
return (value >>> 1) ^ -(value & 1);
}
/**
* Read a long stored in variable-length format using zig-zag decoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>.
*
* @param buffer The buffer to read from
* @return The long value read
*
* @throws IllegalArgumentException if variable-length value does not terminate after 10 bytes have been read
*/
public static long readVarlong(ByteBuffer buffer) {
long value = 0L;
int i = 0;
long b;
while (((b = buffer.get()) & 0x80) != 0) {
value |= (b & 0x7f) << i;
i += 7;
if (i > 63)
throw illegalVarlongException(value);
}
value |= b << i;
return (value >>> 1) ^ -(value & 1);
}
/**
* Write the given integer following the variable-length zig-zag encoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>
* into the output.
*
* @param value The value to write
* @param out The output to write to
*/
public static void writeVarint(int value, DataOutput out) throws IOException {
int v = (value << 1) ^ (value >> 31);
while ((v & 0xffffff80) != 0L) {
out.writeByte((v & 0x7f) | 0x80);
v >>>= 7;
}
out.writeByte((byte) v);
}
/**
* Write the given integer following the variable-length zig-zag encoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>
* into the buffer.
*
* @param value The value to write
* @param buffer The output to write to
*/
public static void writeVarint(int value, ByteBuffer buffer) {
int v = (value << 1) ^ (value >> 31);
while ((v & 0xffffff80) != 0L) {
byte b = (byte) ((v & 0x7f) | 0x80);
buffer.put(b);
v >>>= 7;
}
buffer.put((byte) v);
}
/**
* Write the given integer following the variable-length zig-zag encoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>
* into the output.
*
* @param value The value to write
* @param out The output to write to
*/
public static void writeVarlong(long value, DataOutput out) throws IOException {
long v = (value << 1) ^ (value >> 63);
while ((v & 0xffffffffffffff80L) != 0L) {
out.writeByte(((int) v & 0x7f) | 0x80);
v >>>= 7;
}
out.writeByte((byte) v);
}
/**
* Write the given integer following the variable-length zig-zag encoding from
* <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html"> Google Protocol Buffers</a>
* into the buffer.
*
* @param value The value to write
* @param buffer The buffer to write to
*/
public static void writeVarlong(long value, ByteBuffer buffer) {
long v = (value << 1) ^ (value >> 63);
while ((v & 0xffffffffffffff80L) != 0L) {
byte b = (byte) ((v & 0x7f) | 0x80);
buffer.put(b);
v >>>= 7;
}
buffer.put((byte) v);
}
/**
* Number of bytes needed to encode an integer in variable-length format.
*
* @param value The signed value
*/
public static int sizeOfVarint(int value) {
int v = (value << 1) ^ (value >> 31);
int bytes = 1;
while ((v & 0xffffff80) != 0L) {
bytes += 1;
v >>>= 7;
}
return bytes;
}
/**
* Number of bytes needed to encode a long in variable-length format.
*
* @param value The signed value
*/
public static int sizeOfVarlong(long value) {
long v = (value << 1) ^ (value >> 63);
int bytes = 1;
while ((v & 0xffffffffffffff80L) != 0L) {
bytes += 1;
v >>>= 7;
}
return bytes;
}
private static IllegalArgumentException illegalVarintException(int value) {
throw new IllegalArgumentException("Varint is too long, the most significant bit in the 5th byte is set, " +
"converted value: " + Integer.toHexString(value));
}
private static IllegalArgumentException illegalVarlongException(long value) {
throw new IllegalArgumentException("Varlong is too long, most significant bit in the 10th byte is set, " +
"converted value: " + Long.toHexString(value));
}
}
|
ijuma/kafka
|
clients/src/main/java/org/apache/kafka/common/utils/ByteUtils.java
|
Java
|
apache-2.0
| 11,546 |
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.siddhi.core.query.output.ratelimit.snapshot;
import org.wso2.siddhi.core.config.ExecutionPlanContext;
import org.wso2.siddhi.core.event.ComplexEvent;
import org.wso2.siddhi.core.event.ComplexEventChunk;
import org.wso2.siddhi.core.event.stream.StreamEventPool;
import org.wso2.siddhi.core.util.Scheduler;
import org.wso2.siddhi.core.util.parser.SchedulerParser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
/**
* Parent implementation for per event periodic snapshot rate limiting. Multiple implementations of this will be
* there to represent different queries. Snapshot rate limiting will only emit current events representing the
* snapshot period.
*/
public class PerSnapshotOutputRateLimiter extends SnapshotOutputRateLimiter {
private final Long value;
private String id;
private ScheduledExecutorService scheduledExecutorService;
private ComplexEventChunk<ComplexEvent> eventChunk = new ComplexEventChunk<ComplexEvent>(false);
private ComplexEvent lastEvent;
private Scheduler scheduler;
private long scheduledTime;
private String queryName;
public PerSnapshotOutputRateLimiter(String id, Long value, ScheduledExecutorService scheduledExecutorService,
WrappedSnapshotOutputRateLimiter wrappedSnapshotOutputRateLimiter,
ExecutionPlanContext executionPlanContext, String queryName) {
super(wrappedSnapshotOutputRateLimiter, executionPlanContext);
this.queryName = queryName;
this.id = id;
this.value = value;
this.scheduledExecutorService = scheduledExecutorService;
}
@Override
public void process(ComplexEventChunk complexEventChunk) {
List<ComplexEventChunk<ComplexEvent>> outputEventChunks = new ArrayList<ComplexEventChunk<ComplexEvent>>();
complexEventChunk.reset();
synchronized (this) {
while (complexEventChunk.hasNext()) {
ComplexEvent event = complexEventChunk.next();
if (event.getType() == ComplexEvent.Type.TIMER) {
tryFlushEvents(outputEventChunks, event);
} else if (event.getType() == ComplexEvent.Type.CURRENT) {
complexEventChunk.remove();
tryFlushEvents(outputEventChunks, event);
lastEvent = event;
} else {
tryFlushEvents(outputEventChunks, event);
}
}
}
for (ComplexEventChunk eventChunk : outputEventChunks) {
sendToCallBacks(eventChunk);
}
}
private void tryFlushEvents(List<ComplexEventChunk<ComplexEvent>> outputEventChunks, ComplexEvent event) {
if (event.getTimestamp() >= scheduledTime) {
ComplexEventChunk<ComplexEvent> outputEventChunk = new ComplexEventChunk<ComplexEvent>(false);
if (lastEvent != null) {
outputEventChunk.add(cloneComplexEvent(lastEvent));
}
outputEventChunks.add(outputEventChunk);
scheduledTime += value;
scheduler.notifyAt(scheduledTime);
}
}
@Override
public SnapshotOutputRateLimiter clone(String key, WrappedSnapshotOutputRateLimiter
wrappedSnapshotOutputRateLimiter) {
return new PerSnapshotOutputRateLimiter(id + key, value, scheduledExecutorService,
wrappedSnapshotOutputRateLimiter, executionPlanContext, queryName);
}
@Override
public void start() {
scheduler = SchedulerParser.parse(scheduledExecutorService, this, executionPlanContext);
scheduler.setStreamEventPool(new StreamEventPool(0, 0, 0, 5));
scheduler.init(lockWrapper, queryName);
long currentTime = System.currentTimeMillis();
scheduledTime = currentTime + value;
scheduler.notifyAt(scheduledTime);
}
@Override
public void stop() {
//Nothing to stop
}
@Override
public Map<String, Object> currentState() {
Map<String, Object> state = new HashMap<>();
state.put("EventChunk", eventChunk.getFirst());
return state;
}
@Override
public void restoreState(Map<String, Object> state) {
eventChunk.clear();
eventChunk.add((ComplexEvent) state.get("EventList"));
}
}
|
lgobinath/siddhi
|
modules/siddhi-core/src/main/java/org/wso2/siddhi/core/query/output/ratelimit/snapshot/PerSnapshotOutputRateLimiter.java
|
Java
|
apache-2.0
| 5,177 |
/* Copyright 2016-2019, SINTEF Ocean.
* 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 "cppfmu/cppfmu_cs.hpp"
#include <stdexcept>
namespace cppfmu
{
// =============================================================================
// SlaveInstance
// =============================================================================
void SlaveInstance::SetupExperiment(
FMIBoolean /*toleranceDefined*/,
FMIReal /*tolerance*/,
FMIReal /*tStart*/,
FMIBoolean /*stopTimeDefined*/,
FMIReal /*tStop*/)
{
// Do nothing
}
void SlaveInstance::EnterInitializationMode()
{
// Do nothing
}
void SlaveInstance::ExitInitializationMode()
{
// Do nothing
}
void SlaveInstance::Terminate()
{
// Do nothing
}
void SlaveInstance::Reset()
{
// Do nothing
}
void SlaveInstance::SetReal(
const FMIValueReference /*vr*/[],
std::size_t nvr,
const FMIReal /*value*/[])
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
void SlaveInstance::SetInteger(
const FMIValueReference /*vr*/[],
std::size_t nvr,
const FMIInteger /*value*/[])
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
void SlaveInstance::SetBoolean(
const FMIValueReference /*vr*/[],
std::size_t nvr,
const FMIBoolean /*value*/[])
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
void SlaveInstance::SetString(
const FMIValueReference /*vr*/[],
std::size_t nvr,
const FMIString /*value*/[])
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
void SlaveInstance::GetReal(
const FMIValueReference /*vr*/[],
std::size_t nvr,
FMIReal /*value*/[]) const
{
if (nvr != 0) {
throw std::logic_error("Attempted to get nonexistent variable");
}
}
void SlaveInstance::GetInteger(
const FMIValueReference /*vr*/[],
std::size_t nvr,
FMIInteger /*value*/[]) const
{
if (nvr != 0) {
throw std::logic_error("Attempted to get nonexistent variable");
}
}
void SlaveInstance::GetBoolean(
const FMIValueReference /*vr*/[],
std::size_t nvr,
FMIBoolean /*value*/[]) const
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
void SlaveInstance::GetString(
const FMIValueReference /*vr*/[],
std::size_t nvr,
FMIString /*value*/[]) const
{
if (nvr != 0) {
throw std::logic_error("Attempted to set nonexistent variable");
}
}
SlaveInstance::~SlaveInstance() CPPFMU_NOEXCEPT
{
// Do nothing
}
} // namespace cppfmu
|
idaholab/raven
|
framework/contrib/PythonFMU/pythonfmu/pythonfmu-export/cpp/cppfmu_cs.cpp
|
C++
|
apache-2.0
| 2,874 |
package org.baade.eel.core.player;
import org.baade.eel.core.ILifecycle;
import org.baade.eel.core.message.IMessage;
import org.baade.eel.core.processor.IProcessor;
public interface IPlayer extends ILifecycle {
public void send(IMessage message);
public IProcessor getProcessor();
}
|
baade-org/eel
|
eel-core/src/main/java/org/baade/eel/core/player/IPlayer.java
|
Java
|
apache-2.0
| 290 |
/*
* Copyright 2019 Qameta Software OÜ
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.qameta.allure.testdata;
/**
* @author sskorol (Sergey Korol)
*/
public class DummyCard {
private final String number;
public DummyCard(final String number) {
this.number = number;
}
public String getNumber() {
return number;
}
@Override
public String toString() {
return "DummyCard{" +
"number='" + number + '\'' +
'}';
}
}
|
allure-framework/allure-java
|
allure-java-commons/src/test/java/io/qameta/allure/testdata/DummyCard.java
|
Java
|
apache-2.0
| 1,043 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Microsoft.AspNetCore.Mvc.RazorPages
{
/// <summary>
/// Provides methods to create a Razor page.
/// </summary>
public interface IPageActivatorProvider
{
/// <summary>
/// Creates a Razor page activator.
/// </summary>
/// <param name="descriptor">The <see cref="CompiledPageActionDescriptor"/>.</param>
/// <returns>The delegate used to activate the page.</returns>
Func<PageContext, ViewContext, object> CreateActivator(CompiledPageActionDescriptor descriptor);
/// <summary>
/// Releases a Razor page.
/// </summary>
/// <param name="descriptor">The <see cref="CompiledPageActionDescriptor"/>.</param>
/// <returns>The delegate used to dispose the activated page.</returns>
Action<PageContext, ViewContext, object>? CreateReleaser(CompiledPageActionDescriptor descriptor);
/// <summary>
/// Releases a Razor page asynchronously.
/// </summary>
/// <param name="descriptor">The <see cref="CompiledPageActionDescriptor"/>.</param>
/// <returns>The delegate used to dispose the activated page asynchronously.</returns>
Func<PageContext, ViewContext, object, ValueTask>? CreateAsyncReleaser(CompiledPageActionDescriptor descriptor)
{
var releaser = CreateReleaser(descriptor);
if (releaser is null)
{
return null;
}
return (context, viewContext, page) =>
{
releaser(context, viewContext, page);
return default;
};
}
}
}
|
aspnet/AspNetCore
|
src/Mvc/Mvc.RazorPages/src/IPageActivatorProvider.cs
|
C#
|
apache-2.0
| 1,873 |
/*
* 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 "sql_test_suite_fixture.h"
#include "test_utils.h"
using namespace ignite_test;
namespace ignite
{
SqlTestSuiteFixture::SqlTestSuiteFixture():
testCache(0),
env(NULL),
dbc(NULL),
stmt(NULL)
{
grid = StartNode("queries-test.xml");
testCache = grid.GetCache<int64_t, TestType>("cache");
// Allocate an environment handle
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
BOOST_REQUIRE(env != NULL);
// We want ODBC 3 support
SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, reinterpret_cast<void*>(SQL_OV_ODBC3), 0);
// Allocate a connection handle
SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
BOOST_REQUIRE(dbc != NULL);
// Connect string
SQLCHAR connectStr[] = "DRIVER={Apache Ignite};ADDRESS=127.0.0.1:11110;CACHE=cache";
SQLCHAR outstr[ODBC_BUFFER_SIZE];
SQLSMALLINT outstrlen;
// Connecting to ODBC server.
SQLRETURN ret = SQLDriverConnect(dbc, NULL, connectStr, static_cast<SQLSMALLINT>(sizeof(connectStr)),
outstr, sizeof(outstr), &outstrlen, SQL_DRIVER_COMPLETE);
if (!SQL_SUCCEEDED(ret))
{
Ignition::StopAll(true);
BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_DBC, dbc));
}
// Allocate a statement handle
SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt);
BOOST_REQUIRE(stmt != NULL);
}
SqlTestSuiteFixture::~SqlTestSuiteFixture()
{
// Releasing statement handle.
SQLFreeHandle(SQL_HANDLE_STMT, stmt);
// Disconneting from the server.
SQLDisconnect(dbc);
// Releasing allocated handles.
SQLFreeHandle(SQL_HANDLE_DBC, dbc);
SQLFreeHandle(SQL_HANDLE_ENV, env);
ignite::Ignition::StopAll(true);
}
void SqlTestSuiteFixture::CheckSingleResult0(const char* request,
SQLSMALLINT type, void* column, SQLLEN bufSize, SQLLEN* resSize) const
{
SQLRETURN ret;
ret = SQLBindCol(stmt, 1, type, column, bufSize, resSize);
if (!SQL_SUCCEEDED(ret))
BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
ret = SQLExecDirect(stmt, reinterpret_cast<SQLCHAR*>(const_cast<char*>(request)), SQL_NTS);
if (!SQL_SUCCEEDED(ret))
BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
ret = SQLFetch(stmt);
if (!SQL_SUCCEEDED(ret))
BOOST_FAIL(GetOdbcErrorMessage(SQL_HANDLE_STMT, stmt));
ret = SQLFetch(stmt);
BOOST_CHECK(ret == SQL_NO_DATA);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<std::string>(const char* request, const std::string& expected)
{
SQLCHAR res[ODBC_BUFFER_SIZE] = { 0 };
SQLLEN resLen = 0;
CheckSingleResult0(request, SQL_C_CHAR, res, ODBC_BUFFER_SIZE, &resLen);
std::string actual;
if (resLen > 0)
actual.assign(reinterpret_cast<char*>(res), static_cast<size_t>(resLen));
BOOST_CHECK_EQUAL(actual, expected);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int64_t>(const char* request, const int64_t& expected)
{
CheckSingleResultNum0<int64_t>(request, expected, SQL_C_SBIGINT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int32_t>(const char* request, const int32_t& expected)
{
CheckSingleResultNum0<int32_t>(request, expected, SQL_C_SLONG);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int16_t>(const char* request, const int16_t& expected)
{
CheckSingleResultNum0<int16_t>(request, expected, SQL_C_SSHORT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int8_t>(const char* request, const int8_t& expected)
{
CheckSingleResultNum0<int8_t>(request, expected, SQL_C_STINYINT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<float>(const char* request, const float& expected)
{
SQLREAL res = 0;
CheckSingleResult0(request, SQL_C_FLOAT, &res, 0, 0);
BOOST_CHECK_CLOSE(static_cast<float>(res), expected, 1E-6f);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<double>(const char* request, const double& expected)
{
SQLDOUBLE res = 0;
CheckSingleResult0(request, SQL_C_DOUBLE, &res, 0, 0);
BOOST_CHECK_CLOSE(static_cast<double>(res), expected, 1E-6);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<bool>(const char* request, const bool& expected)
{
SQLCHAR res = 0;
CheckSingleResult0(request, SQL_C_BIT, &res, 0, 0);
BOOST_CHECK_EQUAL((res != 0), expected);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<ignite::Guid>(const char* request, const ignite::Guid& expected)
{
SQLGUID res;
memset(&res, 0, sizeof(res));
CheckSingleResult0(request, SQL_C_GUID, &res, 0, 0);
BOOST_CHECK_EQUAL(res.Data1, expected.GetMostSignificantBits() & 0xFFFFFFFF00000000ULL >> 32);
BOOST_CHECK_EQUAL(res.Data2, expected.GetMostSignificantBits() & 0x00000000FFFF0000ULL >> 16);
BOOST_CHECK_EQUAL(res.Data3, expected.GetMostSignificantBits() & 0x000000000000FFFFULL);
for (int i = 0; i < sizeof(res.Data4); ++i)
BOOST_CHECK_EQUAL(res.Data4[i], (expected.GetLeastSignificantBits() & (0xFFULL << (8 * i))) >> (8 * i));
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<std::string>(const char* request)
{
SQLCHAR res[ODBC_BUFFER_SIZE] = { 0 };
SQLLEN resLen = 0;
CheckSingleResult0(request, SQL_C_CHAR, res, ODBC_BUFFER_SIZE, &resLen);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int64_t>(const char* request)
{
CheckSingleResultNum0<int64_t>(request, SQL_C_SBIGINT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int32_t>(const char* request)
{
CheckSingleResultNum0<int32_t>(request, SQL_C_SLONG);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int16_t>(const char* request)
{
CheckSingleResultNum0<int16_t>(request, SQL_C_SSHORT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<int8_t>(const char* request)
{
CheckSingleResultNum0<int8_t>(request, SQL_C_STINYINT);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<float>(const char* request)
{
SQLREAL res = 0;
CheckSingleResult0(request, SQL_C_FLOAT, &res, 0, 0);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<double>(const char* request)
{
SQLDOUBLE res = 0;
CheckSingleResult0(request, SQL_C_DOUBLE, &res, 0, 0);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Date>(const char* request)
{
SQL_DATE_STRUCT res;
CheckSingleResult0(request, SQL_C_DATE, &res, 0, 0);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Timestamp>(const char* request)
{
SQL_TIMESTAMP_STRUCT res;
CheckSingleResult0(request, SQL_C_TIMESTAMP, &res, 0, 0);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Time>(const char* request)
{
SQL_TIME_STRUCT res;
CheckSingleResult0(request, SQL_C_TIME, &res, 0, 0);
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<std::vector<int8_t> >(const char* request, const std::vector<int8_t>& expected)
{
SQLCHAR res[ODBC_BUFFER_SIZE] = { 0 };
SQLLEN resLen = 0;
CheckSingleResult0(request, SQL_C_BINARY, res, ODBC_BUFFER_SIZE, &resLen);
BOOST_REQUIRE_EQUAL(resLen, expected.size());
if (resLen > 0)
{
std::vector<int8_t> actual(res, res + resLen);
BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end());
}
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<ignite::common::Decimal>(const char* request, const ignite::common::Decimal& expected)
{
SQLCHAR res[ODBC_BUFFER_SIZE] = { 0 };
SQLLEN resLen = 0;
CheckSingleResult0(request, SQL_C_CHAR, res, ODBC_BUFFER_SIZE, &resLen);
ignite::common::Decimal actual(std::string(res, res + resLen));
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Date>(const char* request, const Date& expected)
{
SQL_DATE_STRUCT res;
CheckSingleResult0(request, SQL_C_DATE, &res, 0, 0);
using ignite::impl::binary::BinaryUtils;
Date actual = common::MakeDateGmt(res.year, res.month, res.day);
BOOST_REQUIRE_EQUAL(actual.GetSeconds(), expected.GetSeconds());
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Timestamp>(const char* request, const Timestamp& expected)
{
SQL_TIMESTAMP_STRUCT res;
CheckSingleResult0(request, SQL_C_TIMESTAMP, &res, 0, 0);
using ignite::impl::binary::BinaryUtils;
Timestamp actual = common::MakeTimestampGmt(res.year, res.month, res.day, res.hour, res.minute, res.second, res.fraction);
BOOST_REQUIRE_EQUAL(actual.GetSeconds(), expected.GetSeconds());
BOOST_REQUIRE_EQUAL(actual.GetSecondFraction(), expected.GetSecondFraction());
}
template<>
void SqlTestSuiteFixture::CheckSingleResult<Time>(const char* request, const Time& expected)
{
SQL_TIME_STRUCT res;
CheckSingleResult0(request, SQL_C_TIME, &res, 0, 0);
using ignite::impl::binary::BinaryUtils;
Time actual = common::MakeTimeGmt(res.hour, res.minute, res.second);
BOOST_REQUIRE_EQUAL(actual.GetSeconds(), expected.GetSeconds());
}
}
|
nivanov/ignite
|
modules/platforms/cpp/odbc-test/src/sql_test_suite_fixture.cpp
|
C++
|
apache-2.0
| 10,627 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2021 the original author or authors.
*/
package org.assertj.core.api.date;
import static org.mockito.Mockito.verify;
import java.time.Instant;
import java.util.Date;
import org.assertj.core.api.DateAssert;
/**
* Tests for {@link DateAssert#isBetween(Date, Date)}, {@link DateAssert#isBetween(String, String)} and
* {@link DateAssert#isBetween(Instant, Instant)}.
*
* @author Joel Costigliola
*/
class DateAssert_isBetween_Test extends AbstractDateAssertWithDateArg_Test {
@Override
protected DateAssert assertionInvocationWithDateArg() {
return assertions.isBetween(otherDate, otherDate);
}
@Override
protected DateAssert assertionInvocationWithStringArg(String dateAsString) {
return assertions.isBetween(dateAsString, dateAsString);
}
@Override
protected DateAssert assertionInvocationWithInstantArg() {
return assertions.isBetween(otherDate.toInstant(), otherDate.toInstant());
}
@Override
protected void verifyAssertionInvocation(Date date) {
verify(dates).assertIsBetween(getInfo(assertions), getActual(assertions), date, date, true, false);
}
}
|
hazendaz/assertj-core
|
src/test/java/org/assertj/core/api/date/DateAssert_isBetween_Test.java
|
Java
|
apache-2.0
| 1,673 |
package com.android.base.app.dagger;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import javax.inject.Qualifier;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Qualifier
@Documented
@Retention(RUNTIME)
public @interface ContextType {
String ACTIVITY = "Activity";
String CONTEXT = "Context";
String APPLICATION = "Application";
String value() default APPLICATION;
}
|
Ztiany/AndroidBase
|
lib_base/src/main/java/com/android/base/app/dagger/ContextType.java
|
Java
|
apache-2.0
| 438 |
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
import {customElement, observe, property} from '@polymer/decorators';
import {html, PolymerElement} from '@polymer/polymer';
import * as d3Typed from 'd3';
import {DarkModeMixin} from '../../../components/polymer/dark_mode_mixin';
import {LegacyElementMixin} from '../../../components/polymer/legacy_element_mixin';
// Copied from `tf-histogram-dashboard/histogramCore`; TODO(wchargin):
// resolve dependency structure.
export type VzHistogram = {
wall_time: number; // in seconds
step: number;
bins: D3HistogramBin[];
};
export type D3HistogramBin = {
x: number;
dx: number;
y: number;
};
// TypeScript can't deal with d3's style of overloading and
// polymorphism, and constantly fails to select the correct overload.
// This module was converted from working non-TypeScript code, so we
// grandfather it in untyped.
const d3: any = d3Typed;
export interface VzHistogramTimeseries extends HTMLElement {
setSeriesData(series: string, data: VzHistogram[]): void;
redraw(): void;
}
@customElement('vz-histogram-timeseries')
class _VzHistogramTimeseries
extends LegacyElementMixin(DarkModeMixin(PolymerElement))
implements VzHistogramTimeseries
{
static readonly template = html`
<div id="tooltip"><span></span></div>
<svg id="svg">
<g>
<g class="axis x"></g>
<g class="axis y"></g>
<g class="axis y slice"></g>
<g class="stage">
<rect class="background"></rect>
</g>
<g class="x-axis-hover"></g>
<g class="y-axis-hover"></g>
<g class="y-slice-axis-hover"></g>
</g>
</svg>
<style>
:host {
color: #aaa;
display: flex;
flex-direction: column;
flex-grow: 1;
flex-shrink: 1;
position: relative;
--vz-histogram-timeseries-hover-bg-color: #fff;
--vz-histogram-timeseries-outline-color: #fff;
--vz-histogram-timeseries-hover-outline-color: #000;
}
:host(.dark-mode) {
--vz-histogram-timeseries-hover-bg-color: var(
--primary-background-color
);
--vz-histogram-timeseries-outline-color: var(--paper-grey-600);
--vz-histogram-timeseries-hover-outline-color: #fff;
}
svg {
font-family: roboto, sans-serif;
overflow: visible;
display: block;
width: 100%;
flex-grow: 1;
flex-shrink: 1;
}
text {
fill: currentColor;
}
#tooltip {
position: absolute;
display: block;
opacity: 0;
font-weight: bold;
font-size: 11px;
}
.background {
fill-opacity: 0;
fill: red;
}
.histogram {
pointer-events: none;
}
.hover {
font-size: 9px;
dominant-baseline: middle;
opacity: 0;
}
.hover circle {
stroke: white;
stroke-opacity: 0.5;
stroke-width: 1px;
}
.hover text {
fill: black;
opacity: 0;
}
.hover.hover-closest circle {
fill: var(--vz-histogram-timeseries-hover-outline-color) !important;
}
.hover.hover-closest text {
opacity: 1;
}
.baseline {
stroke: black;
stroke-opacity: 0.1;
}
.outline {
fill: none;
stroke: var(--vz-histogram-timeseries-outline-color);
stroke-opacity: 0.5;
}
.outline.outline-hover {
stroke: var(--vz-histogram-timeseries-hover-outline-color) !important;
stroke-opacity: 1;
}
.x-axis-hover,
.y-axis-hover,
.y-slice-axis-hover {
pointer-events: none;
}
.x-axis-hover .label,
.y-axis-hover .label,
.y-slice-axis-hover .label {
opacity: 0;
font-weight: bold;
font-size: 11px;
text-anchor: end;
}
.x-axis-hover text {
text-anchor: middle;
}
.y-axis-hover text,
.y-slice-axis-hover text {
text-anchor: start;
}
.x-axis-hover line,
.y-axis-hover line,
.y-slice-axis-hover line {
stroke: currentColor;
}
.x-axis-hover rect,
.y-axis-hover rect,
.y-slice-axis-hover rect {
fill: var(--vz-histogram-timeseries-hover-bg-color);
}
#tooltip,
.x-axis-hover text,
.y-axis-hover text,
.y-slice-axis-hover text {
color: var(--vz-histogram-timeseries-hover-outline-color);
}
.axis {
font-size: 11px;
}
.axis path.domain {
fill: none;
}
.axis .tick line {
stroke: #ddd;
}
.axis.slice {
opacity: 0;
}
.axis.slice .tick line {
stroke-dasharray: 2;
}
.small .axis text {
display: none;
}
.small .axis .tick:first-of-type text {
display: block;
}
.small .axis .tick:last-of-type text {
display: block;
}
.medium .axis text {
display: none;
}
.medium .axis .tick:nth-child(2n + 1) text {
display: block;
}
.large .axis text {
display: none;
}
.large .axis .tick:nth-child(2n + 1) text {
display: block;
}
</style>
`;
@property({type: String})
mode: string = 'offset';
@property({type: String})
timeProperty: string = 'step';
@property({type: String})
bins: string = 'bins';
@property({type: String})
x: string = 'x';
@property({type: String})
dx: string = 'dx';
@property({type: String})
y: string = 'y';
@property({type: Object})
colorScale = d3.scaleOrdinal(d3.schemeCategory10);
@property({type: Number})
modeTransitionDuration: number = 500;
@property({type: Boolean})
_attached: boolean;
@property({type: String})
_name: string = null;
@property({type: Array})
_data: VzHistogram[] = null;
ready() {
super.ready();
// Polymer's way of scoping styles on nodes that d3 created
this.scopeSubtree(this.$.svg, true);
}
override attached() {
this._attached = true;
}
override detached() {
this._attached = false;
}
setSeriesData(name, data) {
this._name = name;
this._data = data;
this.redraw();
}
@observe('timeProperty', 'colorScale', '_attached')
_redrawOnChange() {
this.redraw();
}
/**
* Redraws the chart. This is only called if the chart is attached to the
* screen and if the chart has data.
*/
redraw() {
this._draw(0);
}
@observe('mode')
_modeRedraw() {
this._draw(this.modeTransitionDuration);
}
_draw(duration) {
if (!this._attached || !this._data) {
return;
}
//
// Data verification
//
if (duration === undefined)
throw new Error('vz-histogram-timeseries _draw needs duration');
if (this._data.length <= 0) throw new Error('Not enough steps in the data');
if (!this._data[0].hasOwnProperty(this.bins))
throw new Error("No bins property of '" + this.bins + "' in data");
if (this._data[0][this.bins].length <= 0)
throw new Error('Must have at least one bin in bins in data');
if (!this._data[0][this.bins][0].hasOwnProperty(this.x))
throw new Error("No x property '" + this.x + "' on bins data");
if (!this._data[0][this.bins][0].hasOwnProperty(this.dx))
throw new Error("No dx property '" + this.dx + "' on bins data");
if (!this._data[0][this.bins][0].hasOwnProperty(this.y))
throw new Error("No y property '" + this.y + "' on bins data");
//
// Initialization
//
var timeProp = this.timeProperty;
var xProp = this.x;
var binsProp = this.bins;
var dxProp = this.dx;
var yProp = this.y;
var data = this._data;
var name = this._name;
var mode = this.mode;
var color = d3.hcl(this.colorScale(name));
var tooltip = d3.select(this.$.tooltip);
var xAccessor = function (d) {
return d[xProp];
};
var yAccessor = function (d) {
return d[yProp];
};
var dxAccessor = function (d) {
return d[dxProp];
};
var xRightAccessor = function (d) {
return d[xProp] + d[dxProp];
};
var timeAccessor = function (d) {
return d[timeProp];
};
if (timeProp === 'relative') {
timeAccessor = function (d) {
return d.wall_time - data[0].wall_time;
};
}
var brect = this.$.svg.getBoundingClientRect();
var outerWidth = brect.width,
outerHeight = brect.height;
var sliceHeight,
margin = {top: 5, right: 60, bottom: 20, left: 24};
if (mode === 'offset') {
sliceHeight = outerHeight / 2.5;
margin.top = sliceHeight + 5;
} else {
sliceHeight = outerHeight - margin.top - margin.bottom;
}
var width = outerWidth - margin.left - margin.right,
height = outerHeight - margin.top - margin.bottom;
var leftMin = d3.min(data, xAccessor),
rightMax = d3.max(data, xRightAccessor);
//
// Text formatters
//
var format = d3.format('.3n');
var yAxisFormat = d3.format('.0f');
if (timeProp === 'wall_time') {
yAxisFormat = d3.timeFormat('%m/%d %X');
} else if (timeProp === 'relative') {
yAxisFormat = function (d: number) {
return d3.format('.1r')(d / 3.6e6) + 'h'; // Convert to hours.
};
}
//
// Calculate the extents
//
var xExtents = data.map(function (d, i) {
return [
d3.min(d[binsProp], xAccessor),
d3.max(d[binsProp], xRightAccessor),
];
});
var yExtents = data.map(function (d) {
return d3.extent(d[binsProp], yAccessor);
});
//
// Scales and axis
//
var outlineCanvasSize = 500;
var extent = d3.extent(data, timeAccessor);
var yScale = (timeProp === 'wall_time' ? d3.scaleTime() : d3.scaleLinear())
.domain(extent)
.range([0, mode === 'offset' ? height : 0]);
var ySliceScale = d3
.scaleLinear()
.domain([
0,
d3.max(data, function (d, i) {
return yExtents[i][1];
}),
])
.range([sliceHeight, 0]);
var yLineScale = d3
.scaleLinear()
.domain(ySliceScale.domain())
.range([outlineCanvasSize, 0]);
var xScale = d3
.scaleLinear()
.domain([
d3.min(data, function (d, i) {
return xExtents[i][0];
}),
d3.max(data, function (d, i) {
return xExtents[i][1];
}),
])
.nice()
.range([0, width]);
var xLineScale = d3
.scaleLinear()
.domain(xScale.domain())
.range([0, outlineCanvasSize]);
const fillColor = d3
.scaleLinear()
.domain(d3.extent(data, timeAccessor))
.range([color.brighter(), color.darker()])
.interpolate(d3.interpolateHcl);
var xAxis = d3.axisBottom(xScale).ticks(Math.max(2, width / 20));
var yAxis = d3
.axisRight(yScale)
.ticks(Math.max(2, height / 15))
.tickFormat(yAxisFormat);
var ySliceAxis = d3
.axisRight(ySliceScale)
.ticks(Math.max(2, height / 15))
.tickSize(width + 5)
.tickFormat(format);
var xBinCentroid = function (d) {
return d[xProp] + d[dxProp] / 2;
};
var linePath = d3
.line()
.x(function (d) {
return xLineScale(xBinCentroid(d));
})
.y(function (d) {
return yLineScale(d[yProp]);
});
var path = function (d) {
// Draw a line from 0 to the first point and from the last point to 0.
return (
'M' +
xLineScale(xBinCentroid(d[0])) +
',' +
yLineScale(0) +
'L' +
linePath(d).slice(1) +
'L' +
xLineScale(xBinCentroid(d[d.length - 1])) +
',' +
yLineScale(0)
);
};
//
// Render
//
var svgNode = this.$.svg;
var svg = d3.select(svgNode);
var svgTransition = svg.transition().duration(duration);
var g = svg
.select('g')
.classed('small', function () {
return width > 0 && width <= 150;
})
.classed('medium', function () {
return width > 150 && width <= 300;
})
.classed('large', function () {
return width > 300;
});
var gTransition = svgTransition
.select('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var bisect = d3.bisector(xRightAccessor).left;
var stage = g
.select('.stage')
.on('mouseover', function () {
hoverUpdate.style('opacity', 1);
xAxisHoverUpdate.style('opacity', 1);
yAxisHoverUpdate.style('opacity', 1);
ySliceAxisHoverUpdate.style('opacity', 1);
tooltip.style('opacity', 1);
})
.on('mouseout', function () {
hoverUpdate.style('opacity', 0);
xAxisHoverUpdate.style('opacity', 0);
yAxisHoverUpdate.style('opacity', 0);
ySliceAxisHoverUpdate.style('opacity', 0);
hoverUpdate.classed('hover-closest', false);
outlineUpdate.classed('outline-hover', false);
tooltip.style('opacity', 0);
})
.on('mousemove', onMouseMove);
var background = stage
.select('.background')
.attr('transform', 'translate(' + -margin.left + ',' + -margin.top + ')')
.attr('width', outerWidth)
.attr('height', outerHeight);
var histogram = stage.selectAll('.histogram').data(data),
histogramExit = histogram.exit().remove(),
histogramEnter = histogram.enter().append('g').attr('class', 'histogram'),
histogramUpdate = histogramEnter.merge(histogram).sort(function (a, b) {
return timeAccessor(a) - timeAccessor(b);
}),
histogramTransition = gTransition
.selectAll('.histogram')
.attr('transform', function (d) {
return (
'translate(0, ' +
(mode === 'offset' ? yScale(timeAccessor(d)) - sliceHeight : 0) +
')'
);
});
var baselineEnter = histogramEnter.append('line').attr('class', 'baseline'),
baselineUpdate = histogramTransition
.select('.baseline')
.style('stroke-opacity', function (d) {
return mode === 'offset' ? 0.1 : 0;
})
.attr('y1', sliceHeight)
.attr('y2', sliceHeight)
.attr('x2', width);
var outlineEnter = histogramEnter.append('path').attr('class', 'outline'),
outlineUpdate = histogramUpdate
.select('.outline')
.attr('vector-effect', 'non-scaling-stroke')
.attr('d', function (d) {
return path(d[binsProp]);
})
.style('stroke-width', 1),
outlineTransition = histogramTransition
.select('.outline')
.attr(
'transform',
'scale(' +
width / outlineCanvasSize +
', ' +
sliceHeight / outlineCanvasSize +
')'
)
.style('stroke', function (d) {
return mode === 'offset' ? '' : fillColor(timeAccessor(d));
})
.style('fill-opacity', function (d) {
return mode === 'offset' ? 1 : 0;
})
.style('fill', function (d) {
return fillColor(timeAccessor(d));
});
var hoverEnter = histogramEnter.append('g').attr('class', 'hover');
var hoverUpdate = histogramUpdate
.select('.hover')
.style('fill', function (d) {
return fillColor(timeAccessor(d));
});
hoverEnter.append('circle').attr('r', 2);
hoverEnter.append('text').style('display', 'none').attr('dx', 4);
var xAxisHover = g.select('.x-axis-hover').selectAll('.label').data(['x']),
xAxisHoverEnter = xAxisHover.enter().append('g').attr('class', 'label'),
xAxisHoverUpdate = xAxisHover.merge(xAxisHoverEnter);
xAxisHoverEnter
.append('rect')
.attr('x', -20)
.attr('y', 6)
.attr('width', 40)
.attr('height', 14);
xAxisHoverEnter
.append('line')
.attr('x1', 0)
.attr('x2', 0)
.attr('y1', 0)
.attr('y2', 6);
xAxisHoverEnter.append('text').attr('dy', 18);
var yAxisHover = g.select('.y-axis-hover').selectAll('.label').data(['y']),
yAxisHoverEnter = yAxisHover.enter().append('g').attr('class', 'label'),
yAxisHoverUpdate = yAxisHover.merge(yAxisHoverEnter);
yAxisHoverEnter
.append('rect')
.attr('x', 8)
.attr('y', -6)
.attr('width', 40)
.attr('height', 14);
yAxisHoverEnter
.append('line')
.attr('x1', 0)
.attr('x2', 6)
.attr('y1', 0)
.attr('y2', 0);
yAxisHoverEnter.append('text').attr('dx', 8).attr('dy', 4);
var ySliceAxisHover = g
.select('.y-slice-axis-hover')
.selectAll('.label')
.data(['y']),
ySliceAxisHoverEnter = ySliceAxisHover
.enter()
.append('g')
.attr('class', 'label'),
ySliceAxisHoverUpdate = ySliceAxisHover.merge(ySliceAxisHoverEnter);
ySliceAxisHoverEnter
.append('rect')
.attr('x', 8)
.attr('y', -6)
.attr('width', 40)
.attr('height', 14);
ySliceAxisHoverEnter
.append('line')
.attr('x1', 0)
.attr('x2', 6)
.attr('y1', 0)
.attr('y2', 0);
ySliceAxisHoverEnter.append('text').attr('dx', 8).attr('dy', 4);
gTransition
.select('.y.axis.slice')
.style('opacity', mode === 'offset' ? 0 : 1)
.attr(
'transform',
'translate(0, ' + (mode === 'offset' ? -sliceHeight : 0) + ')'
)
.call(ySliceAxis);
gTransition
.select('.x.axis')
.attr('transform', 'translate(0, ' + height + ')')
.call(xAxis);
gTransition
.select('.y.axis')
.style('opacity', mode === 'offset' ? 1 : 0)
.attr(
'transform',
'translate(' + width + ', ' + (mode === 'offset' ? 0 : height) + ')'
)
.call(yAxis);
gTransition.selectAll('.tick text').attr('fill', '#aaa');
gTransition.selectAll('.axis path.domain').attr('stroke', 'none');
function onMouseMove() {
var m = d3.mouse(this),
v = xScale.invert(m[0]),
t = yScale.invert(m[1]);
function hoverXIndex(d) {
return Math.min(d[binsProp].length - 1, bisect(d[binsProp], v));
}
var closestSliceData;
var closestSliceDistance = Infinity;
var lastSliceData;
hoverUpdate.attr('transform', function (d, i) {
var index = hoverXIndex(d);
lastSliceData = d;
var x = xScale(
d[binsProp][index][xProp] + d[binsProp][index][dxProp] / 2
);
var y = ySliceScale(d[binsProp][index][yProp]);
var globalY =
mode === 'offset' ? yScale(timeAccessor(d)) - (sliceHeight - y) : y;
var dist = Math.abs(m[1] - globalY);
if (dist < closestSliceDistance) {
closestSliceDistance = dist;
closestSliceData = d;
}
return 'translate(' + x + ',' + y + ')';
});
hoverUpdate.select('text').text(function (d) {
var index = hoverXIndex(d);
return d[binsProp][index][yProp];
});
hoverUpdate.classed('hover-closest', function (d) {
return d === closestSliceData;
});
outlineUpdate.classed('outline-hover', function (d) {
return d === closestSliceData;
});
var index = hoverXIndex(lastSliceData);
xAxisHoverUpdate
.attr('transform', function (d) {
return (
'translate(' +
xScale(
lastSliceData[binsProp][index][xProp] +
lastSliceData[binsProp][index][dxProp] / 2
) +
', ' +
height +
')'
);
})
.select('text')
.text(function (d) {
return format(
lastSliceData[binsProp][index][xProp] +
lastSliceData[binsProp][index][dxProp] / 2
);
});
var fy = yAxis.tickFormat();
yAxisHoverUpdate
.attr('transform', function (d) {
return (
'translate(' +
width +
', ' +
(mode === 'offset' ? yScale(timeAccessor(closestSliceData)) : 0) +
')'
);
})
.style('display', mode === 'offset' ? '' : 'none')
.select('text')
.text(function (d) {
return fy(timeAccessor(closestSliceData));
});
var fsy = ySliceAxis.tickFormat();
ySliceAxisHoverUpdate
.attr('transform', function (d) {
return (
'translate(' +
width +
', ' +
(mode === 'offset'
? 0
: ySliceScale(closestSliceData[binsProp][index][yProp])) +
')'
);
})
.style('display', mode === 'offset' ? 'none' : '')
.select('text')
.text(function (d) {
return fsy(closestSliceData[binsProp][index][yProp]);
});
var svgMouse = d3.mouse(svgNode);
tooltip
.style(
'transform',
'translate(' + (svgMouse[0] + 15) + 'px,' + (svgMouse[1] - 15) + 'px)'
)
.select('span')
.text(
mode === 'offset'
? fsy(closestSliceData[binsProp][index][yProp])
: (timeProp === 'step' ? 'step ' : '') +
fy(timeAccessor(closestSliceData))
);
}
}
}
|
tensorflow/tensorboard
|
tensorboard/plugins/histogram/vz_histogram_timeseries/vz-histogram-timeseries.ts
|
TypeScript
|
apache-2.0
| 22,012 |
/*
* Copyright (C) 2013 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.lite.android.launcher3;
import android.graphics.Rect;
/**
* Allows the implementing {@link View} to not draw underneath system bars.
* e.g., notification bar on top and home key area on the bottom.
*/
public interface Insettable {
void setInsets(Rect insets);
}
|
bojanvu23/android_packages_apps_Trebuchet_Gradle
|
Trebuchet/src/main/java/com/lite/android/launcher3/Insettable.java
|
Java
|
apache-2.0
| 906 |
package examples.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;
@Entity
public class Address {
@TableGenerator(name="Address_Gen",
table="ID_GEN",
pkColumnName="GEN_NAME",
valueColumnName="GEN_VAL",
pkColumnValue="Addr_Gen",
initialValue=10000,
allocationSize=100)
@Id @GeneratedValue(strategy=GenerationType.TABLE,
generator="Address_Gen")
private int id;
private String street;
private String city;
private String state;
private String zip;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String address) {
this.street = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String toString() {
return "Address id: " + getId() +
", street: " + getStreet() +
", city: " + getCity() +
", state: " + getState() +
", zip: " + getZip();
}
}
|
velmuruganvelayutham/jpa
|
examples/Chapter4/11-tableIdGeneration/src/model/examples/model/Address.java
|
Java
|
apache-2.0
| 1,622 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.aggregation;
import com.facebook.presto.byteCode.DynamicClassLoader;
import com.facebook.presto.metadata.FunctionInfo;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.ParametricAggregation;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.operator.aggregation.state.MinMaxByNState;
import com.facebook.presto.operator.aggregation.state.MinMaxByNStateFactory;
import com.facebook.presto.operator.aggregation.state.MinMaxByNStateSerializer;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.BlockBuilderStatus;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.type.ArrayType;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;
import java.lang.invoke.MethodHandle;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static com.facebook.presto.metadata.Signature.orderableTypeParameter;
import static com.facebook.presto.metadata.Signature.typeParameter;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INDEX;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.INPUT_CHANNEL;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.NULLABLE_BLOCK_INPUT_CHANNEL;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INPUT_CHANNEL;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.STATE;
import static com.facebook.presto.operator.aggregation.AggregationUtils.generateAggregationName;
import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.util.Reflection.methodHandle;
import static java.util.Objects.requireNonNull;
public abstract class AbstractMinMaxByNAggregation
extends ParametricAggregation
{
private static final MethodHandle INPUT_FUNCTION = methodHandle(AbstractMinMaxByNAggregation.class, "input", BlockComparator.class, Type.class, Type.class, MinMaxByNState.class, Block.class, Block.class, int.class, long.class);
private static final MethodHandle COMBINE_FUNCTION = methodHandle(AbstractMinMaxByNAggregation.class, "combine", MinMaxByNState.class, MinMaxByNState.class);
private static final MethodHandle OUTPUT_FUNCTION = methodHandle(AbstractMinMaxByNAggregation.class, "output", ArrayType.class, MinMaxByNState.class, BlockBuilder.class);
private final String name;
private final Function<Type, BlockComparator> typeToComparator;
private final Signature signature;
protected AbstractMinMaxByNAggregation(String name, Function<Type, BlockComparator> typeToComparator)
{
this.name = requireNonNull(name, "name is null");
this.typeToComparator = requireNonNull(typeToComparator, "typeToComparator is null");
this.signature = new Signature(name, ImmutableList.of(typeParameter("V"), orderableTypeParameter("K")), "array<V>", ImmutableList.of("V", "K", StandardTypes.BIGINT), false, false);
}
@Override
public Signature getSignature()
{
return signature;
}
@Override
public FunctionInfo specialize(Map<String, Type> types, int arity, TypeManager typeManager, FunctionRegistry functionRegistry)
{
Type keyType = types.get("K");
Type valueType = types.get("V");
Signature signature = new Signature(name, new ArrayType(valueType).getTypeSignature(), valueType.getTypeSignature(), keyType.getTypeSignature(), BIGINT.getTypeSignature());
InternalAggregationFunction aggregation = generateAggregation(valueType, keyType);
return new FunctionInfo(signature, getDescription(), aggregation);
}
public static void input(BlockComparator comparator, Type valueType, Type keyType, MinMaxByNState state, Block value, Block key, int blockIndex, long n)
{
TypedKeyValueHeap heap = state.getTypedKeyValueHeap();
if (heap == null) {
if (n <= 0) {
throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "third argument of max_by/min_by must be a positive integer");
}
heap = new TypedKeyValueHeap(comparator, keyType, valueType, Ints.checkedCast(n));
state.setTypedKeyValueHeap(heap);
}
long startSize = heap.getEstimatedSize();
if (!key.isNull(blockIndex)) {
heap.add(key, value, blockIndex);
}
state.addMemoryUsage(heap.getEstimatedSize() - startSize);
}
public static void combine(MinMaxByNState state, MinMaxByNState otherState)
{
TypedKeyValueHeap otherHeap = otherState.getTypedKeyValueHeap();
if (otherHeap == null) {
return;
}
TypedKeyValueHeap heap = state.getTypedKeyValueHeap();
if (heap == null) {
state.setTypedKeyValueHeap(otherHeap);
return;
}
long startSize = heap.getEstimatedSize();
heap.addAll(otherHeap);
state.addMemoryUsage(heap.getEstimatedSize() - startSize);
}
public static void output(ArrayType outputType, MinMaxByNState state, BlockBuilder out)
{
TypedKeyValueHeap heap = state.getTypedKeyValueHeap();
if (heap == null || heap.isEmpty()) {
out.appendNull();
return;
}
Type elementType = outputType.getElementType();
BlockBuilder arrayBlockBuilder = out.beginBlockEntry();
BlockBuilder reversedBlockBuilder = elementType.createBlockBuilder(new BlockBuilderStatus(), heap.getCapacity());
long startSize = heap.getEstimatedSize();
heap.popAll(reversedBlockBuilder);
state.addMemoryUsage(heap.getEstimatedSize() - startSize);
for (int i = reversedBlockBuilder.getPositionCount() - 1; i >= 0; i--) {
elementType.appendTo(reversedBlockBuilder, i, arrayBlockBuilder);
}
out.closeEntry();
}
protected InternalAggregationFunction generateAggregation(Type valueType, Type keyType)
{
DynamicClassLoader classLoader = new DynamicClassLoader(AbstractMinMaxNAggregation.class.getClassLoader());
BlockComparator comparator = typeToComparator.apply(keyType);
List<Type> inputTypes = ImmutableList.of(valueType, keyType, BIGINT);
MinMaxByNStateSerializer stateSerializer = new MinMaxByNStateSerializer(comparator, keyType, valueType);
Type intermediateType = stateSerializer.getSerializedType();
ArrayType outputType = new ArrayType(valueType);
List<AggregationMetadata.ParameterMetadata> inputParameterMetadata = ImmutableList.of(
new AggregationMetadata.ParameterMetadata(STATE),
new AggregationMetadata.ParameterMetadata(NULLABLE_BLOCK_INPUT_CHANNEL, valueType),
new AggregationMetadata.ParameterMetadata(BLOCK_INPUT_CHANNEL, keyType),
new AggregationMetadata.ParameterMetadata(BLOCK_INDEX),
new AggregationMetadata.ParameterMetadata(INPUT_CHANNEL, BIGINT));
AggregationMetadata metadata = new AggregationMetadata(
generateAggregationName(name, valueType, inputTypes),
inputParameterMetadata,
INPUT_FUNCTION.bindTo(comparator).bindTo(valueType).bindTo(keyType),
null,
null,
COMBINE_FUNCTION,
OUTPUT_FUNCTION.bindTo(outputType),
MinMaxByNState.class,
stateSerializer,
new MinMaxByNStateFactory(),
outputType,
false);
GenericAccumulatorFactoryBinder factory = new AccumulatorCompiler().generateAccumulatorFactoryBinder(metadata, classLoader);
return new InternalAggregationFunction(name, inputTypes, intermediateType, outputType, true, false, factory);
}
}
|
zjshen/presto
|
presto-main/src/main/java/com/facebook/presto/operator/aggregation/AbstractMinMaxByNAggregation.java
|
Java
|
apache-2.0
| 8,905 |
# Copyright 2016 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_health_checking/grpc_version.py.template`!!!
VERSION = '1.33.0.dev0'
|
donnadionne/grpc
|
src/python/grpcio_health_checking/grpc_version.py
|
Python
|
apache-2.0
| 710 |
package de.mukis.docmatcher.csv;
import java.util.Arrays;
import java.util.Objects;
import de.mukis.docmatcher.csv.matcher.CsvMatcher;
public class Columns {
private final int[] columns;
private Columns(int[] columns) {
this.columns = columns;
}
public static Columns columns(int first, int second, int... columns) {
int[] cols = new int[2 + columns.length];
cols[0] = first;
cols[1] = second;
System.arraycopy(columns, 0, cols, 2, columns.length);
return new Columns(cols);
}
public static Columns column(int col) {
return new Columns(new int[] { col });
}
public CsvMatcher are(CsvMatcher matcher) {
matcher.setColumns(this);
return matcher;
}
public CsvMatcher is(CsvMatcher matcher) {
return are(matcher);
}
public int[] get() {
return columns;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(columns);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Columns other = (Columns) obj;
return Objects.deepEquals(columns, other.columns);
}
}
|
muuki88/docmatcher
|
src/main/java/de/mukis/docmatcher/csv/Columns.java
|
Java
|
apache-2.0
| 1,454 |
// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
//
// Copyright 2016-2018 Pascal ECHEMANN.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {SessionManager} from "./SessionManager";
import {GlobalGuidGenerator} from "jec-commons";
import * as crypto from "crypto";
import {SecurityManager} from "../../../core/SecurityManager";
import {Session, SessionError, SessionId} from "jec-exchange";
import {SessionStorage} from "../connectors/SessionStorage";
import {SessionIdUtil} from "../utils/SessionIdUtil";
import {SessionIdBuilder} from "../utils/SessionIdBuilder";
/**
* The default <code>SessionManager</code> implementation to be used by GlassCat
* servers.
*/
export class EjpSessionManager implements SessionManager {
//////////////////////////////////////////////////////////////////////////////
// Constructor function
//////////////////////////////////////////////////////////////////////////////
/**
* Creates a new <code>EjpSessionManager</code> instance.
*/
constructor() {
this.init();
}
//////////////////////////////////////////////////////////////////////////////
// Private properties
//////////////////////////////////////////////////////////////////////////////
/**
* The reference to the GUID for this manager.
*/
private _guid:string = null;
/**
* The type of algorithm used by the associated<code>UserHashModule</code>
* instance for cookies encryption.
*/
private readonly HASH_ALGORITHM:string = "sha256";
/**
* The type of output encoding used by the associated
* <code>UserHashModule</code> instance for cookies encryption.
*/
private readonly OUTPUT_ENCODING:any = "hex";
/**
* The reference to the <code>SessionStorage</code> instance for this manager.
*/
private _connector:SessionStorage = null;
/**
* The reference to the <code>SessionIdBuilder</code> instance for this
* manager.
*/
private _sessionIdBuilder:SessionIdBuilder = null;
//////////////////////////////////////////////////////////////////////////////
// Private methods
//////////////////////////////////////////////////////////////////////////////
/**
* Initializes this session manager.
*/
private init():void {
this._guid = GlobalGuidGenerator.getInstance().generate();
this._sessionIdBuilder = new SessionIdBuilder();
}
//////////////////////////////////////////////////////////////////////////////
// Public methods
//////////////////////////////////////////////////////////////////////////////
/**
* @inheritDoc
*/
public getSessionStorage():SessionStorage {
return this._connector;
}
/**
* @inheritDoc
*/
public setSessionStorage(sessionStorage:SessionStorage):void {
//TODO : log this action
this._connector = sessionStorage;
}
/**
* @inheritDoc
*/
public initSessionId():SessionId {
const sha:crypto.Hash = crypto.createHash(this.HASH_ALGORITHM)
.update(Date.now() + this._guid);
const sessionId:SessionId = this._sessionIdBuilder.buildSessionId(
sha.digest(this.OUTPUT_ENCODING)
);
return sessionId;
}
/**
* @inheritDoc
*/
public addSession(session:Session, result:(error?:SessionError)=>any):void {
this._connector.add(session, result);
}
/**
* @inheritDoc
*/
public getSession(sessionId:SessionId, success:(session:Session)=>any,
error:(error:SessionError)=>any):void {
this._connector.get(
sessionId,
success,
error
);
}
/**
* @inheritDoc
*/
public removeSession(sessionId:SessionId,
result:(error?:SessionError)=>any):void {
this._connector.remove(sessionId, result);
}
}
|
pechemann/jec-glasscat-core
|
src/com/onsoft/glasscat/security/session/managers/EjpSessionManager.ts
|
TypeScript
|
apache-2.0
| 4,312 |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/autoscaling/model/DeleteAutoScalingGroupRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
using namespace Aws::AutoScaling::Model;
using namespace Aws::Utils;
DeleteAutoScalingGroupRequest::DeleteAutoScalingGroupRequest() :
m_autoScalingGroupNameHasBeenSet(false),
m_forceDelete(false),
m_forceDeleteHasBeenSet(false)
{
}
Aws::String DeleteAutoScalingGroupRequest::SerializePayload() const
{
Aws::StringStream ss;
ss << "Action=DeleteAutoScalingGroup&";
if(m_autoScalingGroupNameHasBeenSet)
{
ss << "AutoScalingGroupName=" << StringUtils::URLEncode(m_autoScalingGroupName.c_str()) << "&";
}
if(m_forceDeleteHasBeenSet)
{
ss << "ForceDelete=" << m_forceDelete << "&";
}
ss << "Version=2011-01-01";
return ss.str();
}
|
ambasta/aws-sdk-cpp
|
aws-cpp-sdk-autoscaling/source/model/DeleteAutoScalingGroupRequest.cpp
|
C++
|
apache-2.0
| 1,408 |
/**
* Copyright (c) 2010 Abbcc Corp.
* No 225,Wen Yi RD, Hang Zhou, Zhe Jiang, China.
* All rights reserved.
*
* "AdminService.java is the copyrighted,
* proprietary property of Abbcc Company and its
* subsidiaries and affiliates which retain all right, title and interest
* therein."
*
* Revision History
*
* Date Programmer Notes
* --------- --------------------- --------------------------------------------
* 2009-12-9 wangjin initial
**/
package com.abbcc.service;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import com.abbcc.common.PaginationSupport;
import com.abbcc.models.AbcCellbind;
/**
* *AdminService.java
*/
public interface CellbindService extends BaseService{
public void save(AbcCellbind transientInstance);
public void delete(AbcCellbind persistentInstance);
public AbcCellbind findById(String id);
public List<AbcCellbind> findByExample(AbcCellbind instance);
public List<AbcCellbind> findAll();
public void saveOrUpdate(AbcCellbind instance);
public PaginationSupport findPageByCriteria(
DetachedCriteria detachedCriteria);
public PaginationSupport findPageByCriteria(
DetachedCriteria detachedCriteria, int startIndex);
public PaginationSupport findPageByCriteria(
DetachedCriteria detachedCriteria, int pageSize, int startIndex);
public List findAllByCriteria(DetachedCriteria detachedCriteria);
public int getCountByCriteria(DetachedCriteria detachedCriteria);
public void callProcedure(String procString, List<Object> params)
throws Exception;
public List getCallProcedureResult(String procString, List<Object> params)
throws Exception;
}
|
baowp/platform
|
biz/src/main/java/com/abbcc/service/CellbindService.java
|
Java
|
apache-2.0
| 1,720 |
package com.example.persiandatepicker;
import java.util.Date;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.Toast;
public class PersianDatePicker extends LinearLayout {
private NumberPicker yearNumberPicker, monthNumberPicker, dayNumberPicker;
public PersianDatePicker(Context context, AttributeSet attrs) {
this(context, attrs, -1);
}
public PersianDatePicker(Context context) {
this(context, null, -1);
}
public PersianDatePicker(final Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View root = inflater.inflate(R.layout.pdp, this);
yearNumberPicker = (NumberPicker) root
.findViewById(R.id.yearNumberPicker);
monthNumberPicker = (NumberPicker) root
.findViewById(R.id.monthNumberPicker);
dayNumberPicker = (NumberPicker) root
.findViewById(R.id.dayNumberPicker);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PersianDatePicker, 0, 0);
int year = 1393,month=6,day=19;
year = a.getInteger(R.styleable.PersianDatePicker_year, 1393);
month = a.getInteger(R.styleable.PersianDatePicker_month, 6);
day = a.getInteger(R.styleable.PersianDatePicker_day, 19);
a.recycle();
yearNumberPicker.setMinValue(1380);
yearNumberPicker.setMaxValue(1400);
yearNumberPicker.setValue(year);
monthNumberPicker.setMinValue(1);
monthNumberPicker.setMaxValue(12);
monthNumberPicker.setValue(month);
dayNumberPicker.setMaxValue(31);
dayNumberPicker.setMinValue(1);
dayNumberPicker.setValue(day);
yearNumberPicker.setOnValueChangedListener(new OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker np, int oldValue, int newValue) {
Toast.makeText(context, "Year changed:" + oldValue + " -> " + newValue, Toast.LENGTH_LONG).show();
}
});
}
public Date getSelectedDate() {
return null;
}
public void setSelectedDate(Date date) {
}
}
|
alibehzadian/Smartlab
|
Custom Views/PersianDatePicker-Example/src/com/example/persiandatepicker/PersianDatePicker.java
|
Java
|
apache-2.0
| 2,282 |
phoxy.internal =
{
ChangeURL : function (url)
{
url = phoxy.ConstructURL(url);
phoxy.Log(4, "History push", url);
if (url[0] !== '/')
url = '/' + url;
history.pushState({}, document.title, url);
return false;
}
,
Reset : function (url)
{
if ((url || true) === true)
return location.reload();
location = url;
}
,
Config : function()
{
return phoxy._.config;
}
,
Log : function(level)
{
if (phoxy.state.verbose < level)
return;
var error_names = phoxy._.internal.error_names;
var errorname = error_names[level < error_names.length ? level : error_names.length - 1];
var args = [];
for (var v in arguments)
args.push(arguments[v]);
args[0] = errorname;
var error_methods = phoxy._.internal.error_methods;
var method = error_methods[level < error_methods.length ? level : error_methods.length - 1];
console[method].apply(console, args);
if (level === 0)
throw "Break execution on fatal log";
}
,
Override: function(method_name, new_method)
{
return phoxy._.internal.Override(phoxy, method_name, new_method);
}
};
phoxy._.internal =
{
Load : function( )
{
phoxy.state.loaded = true;
phoxy._.click.InitClickHook();
}
,
GenerateUniqueID : function()
{
var ret = "";
var dictonary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 10; i++)
ret += dictonary.charAt(Math.floor(Math.random() * dictonary.length));
return "phoxy_" + ret;
}
,
DispatchEvent : function(dom_element_id, event_name)
{
var that = phoxy._.render.Div(dom_element_id);
if (document.createEvent)
{
var event = document.createEvent("HTMLEvents");
event.initEvent(event_name, true, true);
event.eventName = event_name;
that.dispatchEvent(event);
}
else
{
var event = document.createEventObject();
event.eventType = event_name;
event.eventName = event_name;
that.fireEvent("on" + event.eventType, event);
}
}
,
HookEvent : function(dom_element_id, event_name, callback)
{
var that = phoxy._.render.Div(dom_element_id);
that.addEventListener(event_name, callback);
}
,
Override : function(object, method_name, new_method)
{
var origin = object[method_name];
object[method_name] = new_method;
object[method_name].origin = origin;
}
,
error_names :
[
"FATAL",
"ERROR",
"WARNING",
"INFO",
"DEBUG"
],
error_methods :
[
"error",
"error",
"warn",
"info",
"log",
"debug"
]
};
|
phoxy/phoxy
|
subsystem/internal.js
|
JavaScript
|
apache-2.0
| 2,785 |
package com.ckt.io.wifidirect.fragment;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.ckt.io.wifidirect.activity.WiFiDirectActivity;
import com.ckt.io.wifidirect.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Lu on 2016/5/22.
*/
public class DeviceListFragment extends ListFragment implements WifiP2pManager.PeerListListener,SwipeRefreshLayout.OnRefreshListener {
private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
ProgressDialog progressDialog = null;
View mContentView = null;
private WifiP2pDevice device;
private SwipeRefreshLayout swipeRefreshLayout;
private WifiManager wifiManager = null;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.setListAdapter(new WiFiPeerListAdapter(getActivity(), R.layout.row_devices, peers));
wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
swipeRefreshLayout = (SwipeRefreshLayout)getActivity().findViewById(R.id.id_swip_ly);
swipeRefreshLayout.setOnRefreshListener(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mContentView = inflater.inflate(R.layout.device_list, null);
return mContentView;
}
public void onRefresh(){
if (!wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(true);
}
Intent intent = new Intent("UPDATE_PEERS");
getActivity().sendBroadcast(intent);
swipeRefreshLayout.setRefreshing(false);
}
/**
* @return this device
*/
public WifiP2pDevice getDevice() {
return device;
}
private static String getDeviceStatus(int deviceStatus) {
Log.d(WiFiDirectActivity.TAG, "Peer status :" + deviceStatus);
switch (deviceStatus) {
case WifiP2pDevice.AVAILABLE:
return "Available";
case WifiP2pDevice.INVITED:
return "Invited";
case WifiP2pDevice.CONNECTED:
return "Connected";
case WifiP2pDevice.FAILED:
return "Failed";
case WifiP2pDevice.UNAVAILABLE:
return "Unavailable";
default:
return "Unknown";
}
}
/**
* Initiate a connection with the peer.
*/
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
WifiP2pDevice device = (WifiP2pDevice) getListAdapter().getItem(position);
((DeviceActionListener) getActivity()).showDetails(device);
}
/**
* Array adapter for ListFragment that maintains WifiP2pDevice list.
*/
private class WiFiPeerListAdapter extends ArrayAdapter<WifiP2pDevice> {
private List<WifiP2pDevice> items;
/**
* @param context
* @param textViewResourceId
* @param objects
*/
public WiFiPeerListAdapter(Context context, int textViewResourceId,
List<WifiP2pDevice> objects) {
super(context, textViewResourceId, objects);
items = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row_devices, null);
}
WifiP2pDevice device = items.get(position);
if (device != null) {
TextView top = (TextView) v.findViewById(R.id.device_name);
TextView bottom = (TextView) v.findViewById(R.id.device_details);
if (top != null) {
top.setText(device.deviceName);
}
if (bottom != null) {
bottom.setText(getDeviceStatus(device.status));
}
}
return v;
}
}
/**
* Update UI for this device.
*
* @param device WifiP2pDevice object
*/
public void updateThisDevice(WifiP2pDevice device) {
this.device = device;
TextView view = (TextView) mContentView.findViewById(R.id.my_name);
view.setText(device.deviceName);
view = (TextView) mContentView.findViewById(R.id.my_status);
view.setText(getDeviceStatus(device.status));
}
@Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
peers.clear();
peers.addAll(peerList.getDeviceList());
((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();
if (peers.size() == 0) {
Log.d(WiFiDirectActivity.TAG, "No devices found");
return;
}
}
public void clearPeers() {
peers.clear();
((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged();
}
/**
*
*/
public void onInitiateDiscovery() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
progressDialog = ProgressDialog.show(getActivity(), "Press back to cancel", "finding peers", true,
true, new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
}
});
}
/**
* An interface-callback for the activity to listen to fragment interaction
* events.
*/
public interface DeviceActionListener {
void showDetails(WifiP2pDevice device);
void cancelDisconnect();
void connect(WifiP2pConfig config);
void disconnect();
}
}
|
lucky-code/Practice
|
kuaichuan2.0/app/src/main/java/com/ckt/io/wifidirect/fragment/DeviceListFragment.java
|
Java
|
apache-2.0
| 6,668 |
/*
* 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.skywalking.oap.server.core.analysis.meter.function.avg;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.skywalking.oap.server.core.Const;
import org.apache.skywalking.oap.server.core.UnexpectedException;
import org.apache.skywalking.oap.server.core.analysis.manual.instance.InstanceTraffic;
import org.apache.skywalking.oap.server.core.analysis.meter.MeterEntity;
import org.apache.skywalking.oap.server.core.analysis.meter.function.AcceptableValue;
import org.apache.skywalking.oap.server.core.analysis.meter.function.MeterFunction;
import org.apache.skywalking.oap.server.core.analysis.metrics.LongValueHolder;
import org.apache.skywalking.oap.server.core.analysis.metrics.Metrics;
import org.apache.skywalking.oap.server.core.analysis.metrics.annotation.ConstOne;
import org.apache.skywalking.oap.server.core.analysis.metrics.annotation.Entrance;
import org.apache.skywalking.oap.server.core.analysis.metrics.annotation.SourceFrom;
import org.apache.skywalking.oap.server.core.query.sql.Function;
import org.apache.skywalking.oap.server.core.remote.grpc.proto.RemoteData;
import org.apache.skywalking.oap.server.core.storage.StorageHashMapBuilder;
import org.apache.skywalking.oap.server.core.storage.annotation.Column;
@MeterFunction(functionName = "avg")
@ToString
public abstract class AvgFunction extends Metrics implements AcceptableValue<Long>, LongValueHolder {
protected static final String SUMMATION = "summation";
protected static final String COUNT = "count";
protected static final String VALUE = "value";
@Setter
@Getter
@Column(columnName = ENTITY_ID, length = 512)
private String entityId;
/**
* Service ID is required for sort query.
*/
@Setter
@Getter
@Column(columnName = InstanceTraffic.SERVICE_ID)
private String serviceId;
@Getter
@Setter
@Column(columnName = SUMMATION, storageOnly = true)
protected long summation;
@Getter
@Setter
@Column(columnName = COUNT, storageOnly = true)
protected long count;
@Getter
@Setter
@Column(columnName = VALUE, dataType = Column.ValueDataType.COMMON_VALUE, function = Function.Avg)
private long value;
@Entrance
public final void combine(@SourceFrom long summation, @ConstOne long count) {
this.summation += summation;
this.count += count;
}
@Override
public final boolean combine(Metrics metrics) {
AvgFunction longAvgMetrics = (AvgFunction) metrics;
combine(longAvgMetrics.summation, longAvgMetrics.count);
return true;
}
@Override
public final void calculate() {
long result = this.summation / this.count;
// The minimum of avg result is 1, that means once there's some data in a duration user can get "1" instead of
// "0".
if (result == 0 && this.summation > 0) {
result = 1;
}
this.value = result;
}
@Override
public Metrics toHour() {
AvgFunction metrics = (AvgFunction) createNew();
metrics.setEntityId(getEntityId());
metrics.setTimeBucket(toTimeBucketInHour());
metrics.setServiceId(getServiceId());
metrics.setSummation(getSummation());
metrics.setCount(getCount());
return metrics;
}
@Override
public Metrics toDay() {
AvgFunction metrics = (AvgFunction) createNew();
metrics.setEntityId(getEntityId());
metrics.setTimeBucket(toTimeBucketInDay());
metrics.setServiceId(getServiceId());
metrics.setSummation(getSummation());
metrics.setCount(getCount());
return metrics;
}
@Override
public int remoteHashCode() {
return entityId.hashCode();
}
@Override
public void deserialize(final RemoteData remoteData) {
this.count = remoteData.getDataLongs(0);
this.summation = remoteData.getDataLongs(1);
setTimeBucket(remoteData.getDataLongs(2));
this.entityId = remoteData.getDataStrings(0);
this.serviceId = remoteData.getDataStrings(1);
}
@Override
public RemoteData.Builder serialize() {
RemoteData.Builder remoteBuilder = RemoteData.newBuilder();
remoteBuilder.addDataLongs(count);
remoteBuilder.addDataLongs(summation);
remoteBuilder.addDataLongs(getTimeBucket());
remoteBuilder.addDataStrings(entityId);
remoteBuilder.addDataStrings(serviceId);
return remoteBuilder;
}
@Override
protected String id0() {
return getTimeBucket() + Const.ID_CONNECTOR + entityId;
}
@Override
public void accept(final MeterEntity entity, final Long value) {
this.entityId = entity.id();
this.serviceId = entity.serviceId();
this.summation += value;
this.count += 1;
}
@Override
public Class<? extends StorageHashMapBuilder> builder() {
return AvgStorageBuilder.class;
}
public static class AvgStorageBuilder implements StorageHashMapBuilder<AvgFunction> {
@Override
public AvgFunction storage2Entity(final Map<String, Object> dbMap) {
AvgFunction metrics = new AvgFunction() {
@Override
public AcceptableValue<Long> createNew() {
throw new UnexpectedException("createNew should not be called");
}
};
metrics.setSummation(((Number) dbMap.get(SUMMATION)).longValue());
metrics.setValue(((Number) dbMap.get(VALUE)).longValue());
metrics.setCount(((Number) dbMap.get(COUNT)).longValue());
metrics.setTimeBucket(((Number) dbMap.get(TIME_BUCKET)).longValue());
metrics.setServiceId((String) dbMap.get(InstanceTraffic.SERVICE_ID));
metrics.setEntityId((String) dbMap.get(ENTITY_ID));
return metrics;
}
@Override
public Map<String, Object> entity2Storage(final AvgFunction storageData) {
Map<String, Object> map = new HashMap<>();
map.put(SUMMATION, storageData.getSummation());
map.put(VALUE, storageData.getValue());
map.put(COUNT, storageData.getCount());
map.put(TIME_BUCKET, storageData.getTimeBucket());
map.put(InstanceTraffic.SERVICE_ID, storageData.getServiceId());
map.put(ENTITY_ID, storageData.getEntityId());
return map;
}
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AvgFunction)) {
return false;
}
AvgFunction function = (AvgFunction) o;
return Objects.equals(entityId, function.entityId) &&
getTimeBucket() == function.getTimeBucket();
}
@Override
public int hashCode() {
return Objects.hash(entityId, getTimeBucket());
}
}
|
ascrutae/sky-walking
|
oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/meter/function/avg/AvgFunction.java
|
Java
|
apache-2.0
| 7,837 |
import time
import django
from django import forms
try:
from django.forms.utils import ErrorDict
except ImportError:
from django.forms.util import ErrorDict
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils.crypto import salted_hmac, constant_time_compare
from django.utils.encoding import force_text
from django.utils.text import get_text_list
from django.utils import timezone
from django.utils.translation import ungettext, ugettext, ugettext_lazy as _
from comments.models import Comment, ThreadedComment
COMMENT_MAX_LENGTH = getattr(settings, 'COMMENT_MAX_LENGTH', 3000)
DEFAULT_COMMENTS_TIMEOUT = getattr(settings, 'COMMENTS_TIMEOUT', (2 * 60 * 60)) # 2h
class CommentSecurityForm(forms.Form):
"""
Handles the security aspects (anti-spoofing) for comment forms.
"""
content_type = forms.CharField(widget=forms.HiddenInput)
object_pk = forms.CharField(widget=forms.HiddenInput)
timestamp = forms.IntegerField(widget=forms.HiddenInput)
security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput)
def __init__(self, target_object, data=None, initial=None, **kwargs):
self.target_object = target_object
if initial is None:
initial = {}
initial.update(self.generate_security_data())
super(CommentSecurityForm, self).__init__(data=data, initial=initial, **kwargs)
def security_errors(self):
"""Return just those errors associated with security"""
errors = ErrorDict()
for f in ["honeypot", "timestamp", "security_hash"]:
if f in self.errors:
errors[f] = self.errors[f]
return errors
def clean_security_hash(self):
"""Check the security hash."""
security_hash_dict = {
'content_type': self.data.get("content_type", ""),
'object_pk': self.data.get("object_pk", ""),
'timestamp': self.data.get("timestamp", ""),
}
expected_hash = self.generate_security_hash(**security_hash_dict)
actual_hash = self.cleaned_data["security_hash"]
if not constant_time_compare(expected_hash, actual_hash):
raise forms.ValidationError("Security hash check failed.")
return actual_hash
def clean_timestamp(self):
"""Make sure the timestamp isn't too far (default is > 2 hours) in the past."""
ts = self.cleaned_data["timestamp"]
if time.time() - ts > DEFAULT_COMMENTS_TIMEOUT:
raise forms.ValidationError("Timestamp check failed")
return ts
def generate_security_data(self):
"""Generate a dict of security data for "initial" data."""
timestamp = int(time.time())
security_dict = {
'content_type': str(self.target_object._meta),
'object_pk': str(self.target_object._get_pk_val()),
'timestamp': str(timestamp),
'security_hash': self.initial_security_hash(timestamp),
}
return security_dict
def initial_security_hash(self, timestamp):
"""
Generate the initial security hash from self.content_object
and a (unix) timestamp.
"""
initial_security_dict = {
'content_type': str(self.target_object._meta),
'object_pk': str(self.target_object._get_pk_val()),
'timestamp': str(timestamp),
}
return self.generate_security_hash(**initial_security_dict)
def generate_security_hash(self, content_type, object_pk, timestamp):
"""
Generate a HMAC security hash from the provided info.
"""
info = (content_type, object_pk, timestamp)
key_salt = "django.contrib.forms.CommentSecurityForm"
value = "-".join(info)
return salted_hmac(key_salt, value).hexdigest()
class CommentDetailsForm(CommentSecurityForm):
"""
Handles the specific details of the comment (name, comment, etc.).
"""
name = forms.CharField(label=_("Name"), max_length=50, widget=forms.HiddenInput)
email = forms.EmailField(label=_("Email address"), widget=forms.HiddenInput)
url = forms.URLField(label=_("URL"), required=False, widget=forms.HiddenInput)
comment = forms.CharField(label=_('Comment'), widget=forms.Textarea,
max_length=COMMENT_MAX_LENGTH)
def get_comment_object(self):
"""
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Does not set any of the fields that would come from a Request object
(i.e. ``user`` or ``ip_address``).
"""
if not self.is_valid():
raise ValueError("get_comment_object may only be called on valid forms")
CommentModel = self.get_comment_model()
new = CommentModel(**self.get_comment_create_data())
new = self.check_for_duplicate_comment(new)
return new
def get_comment_model(self):
"""
Get the comment model to create with this form. Subclasses in custom
comment apps should override this, get_comment_create_data, and perhaps
check_for_duplicate_comment to provide custom comment models.
"""
return Comment
def get_comment_create_data(self):
"""
Returns the dict of data to be used to create a comment. Subclasses in
custom comment apps that override get_comment_model can override this
method to add extra fields onto a custom comment model.
"""
return dict(
content_type=ContentType.objects.get_for_model(self.target_object),
object_pk=force_text(self.target_object._get_pk_val()),
user_name=self.cleaned_data["name"],
user_email=self.cleaned_data["email"],
user_url=self.cleaned_data["url"],
comment=self.cleaned_data["comment"],
submit_date=timezone.now(),
site_id=settings.SITE_ID,
is_public=True,
is_removed=False,
)
def check_for_duplicate_comment(self, new):
"""
Check that a submitted comment isn't a duplicate. This might be caused
by someone posting a comment twice. If it is a dup, silently return the *previous* comment.
"""
possible_duplicates = self.get_comment_model()._default_manager.using(
self.target_object._state.db
).filter(
content_type=new.content_type,
object_pk=new.object_pk,
user_name=new.user_name,
user_email=new.user_email,
user_url=new.user_url,
)
for old in possible_duplicates:
if old.submit_date.date() == new.submit_date.date() and old.comment == new.comment:
return old
return new
def clean_comment(self):
"""
If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't
contain anything in PROFANITIES_LIST.
"""
comment = self.cleaned_data["comment"]
if (not getattr(settings, 'COMMENTS_ALLOW_PROFANITIES', False) and
getattr(settings, 'PROFANITIES_LIST', False)):
bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()]
if bad_words:
raise forms.ValidationError(ungettext(
"Watch your mouth! The word %s is not allowed here.",
"Watch your mouth! The words %s are not allowed here.",
len(bad_words)) % get_text_list(
['"%s%s%s"' % (i[0], '-' * (len(i) - 2), i[-1])
for i in bad_words], ugettext('and')))
return comment
class CommentForm(CommentDetailsForm):
honeypot = forms.CharField(required=False,
label=_('If you enter anything in this field '
'your comment will be treated as spam'))
def clean_honeypot(self):
"""Check that nothing's been entered into the honeypot."""
value = self.cleaned_data["honeypot"]
if value:
raise forms.ValidationError(self.fields["honeypot"].label)
return value
class ThreadedCommentForm(CommentForm):
title = forms.CharField(label=_('Title'), required=False, max_length=getattr(settings, 'COMMENTS_TITLE_MAX_LENGTH', 255), widget=forms.HiddenInput)
parent = forms.IntegerField(required=False, widget=forms.HiddenInput)
def __init__(self, target_object, parent=None, data=None, initial=None):
if django.VERSION >= (1,7):
# Using collections.OrderedDict from Python 2.7+
# This class does not have an insert method, have to replace it.
from collections import OrderedDict
keys = list(self.base_fields.keys())
keys.remove('title')
keys.insert(keys.index('comment'), 'title')
self.base_fields = OrderedDict((k, self.base_fields[k]) for k in keys)
else:
self.base_fields.insert(
self.base_fields.keyOrder.index('comment'), 'title',
self.base_fields.pop('title')
)
self.parent = parent
if initial is None:
initial = {}
initial.update({'parent': self.parent})
super(ThreadedCommentForm, self).__init__(target_object, data=data, initial=initial)
def get_comment_model(self):
return ThreadedComment
def get_comment_create_data(self):
d = super(ThreadedCommentForm, self).get_comment_create_data()
d['parent_id'] = self.cleaned_data['parent']
d['title'] = self.cleaned_data['title']
return d
|
sheshkovsky/jaryan
|
comments/forms.py
|
Python
|
apache-2.0
| 9,802 |
######################################################################
# tc_gid.rb
#
# Test case for the Process.gid and Process.gid= module methods.
#
# NOTE: The Process.gid= tests are only run if the test is run as the
# root user.
######################################################################
require 'test/unit'
require 'test/helper'
class TC_Process_Gid_ModuleMethod < Test::Unit::TestCase
include Test::Helper
unless JRUBY || WINDOWS
def setup
@nobody_gid = Etc.getgrnam('nobody').gid
@login_gid = Etc.getpwnam(Etc.getlogin).gid
end
end
def test_gid_basic
assert_respond_to(Process, :gid)
assert_respond_to(Process, :gid=)
end
unless WINDOWS
def test_gid
if ROOT
assert_equal(0, Process.gid)
else
# assert_equal(@login_gid, Process.gid)
end
end
if ROOT
def test_gid=
assert_nothing_raised{ Process.gid = @nobody_gid }
assert_equal(@nobody_gid, Process.gid)
assert_nothing_raised{ Process.gid = @login_gid }
assert_equal(@login_gid, Process.gid)
end
end
def test_gid_expected_errors
assert_raises(ArgumentError){ Process.gid(0) }
assert_raises(TypeError){ Process.gid = "bogus" }
end
def teardown
@nobody_gid = nil
@login_gid = nil
end
end
end
|
google-code/android-scripting
|
jruby/src/test/externals/ruby_test/test/core/Process/class/tc_gid.rb
|
Ruby
|
apache-2.0
| 1,434 |
package C00_data;
/**
* Created by Administrator on 2016/8/30.
* 进制问题
*
* 二进制显示的是补码,计算机接收的直接量也是补码
*/
public class Test_code {
public static void main(String[] args) {
/*
二进制显示的是补码,计算机接收的直接量也是补码
*/
byte a=-5;
System.out.println("a:"+a);
System.out.println("a的二进制:"+Integer.toBinaryString(a));
byte b=(byte)0xff;
System.out.println("b:"+b);
System.out.println("b的二进制:"+Integer.toBinaryString(b));
byte c=-1;
System.out.println("c:"+c);
System.out.println("c的二进制:"+Integer.toBinaryString(c));
//二进制转换为10进制,字符串第一位可以为-号
//这种方式字符串中为原码
String cc="-111";
int d = Integer.parseInt(cc, 2); // 2进制
System.out.println("d:"+d);
/**
byte short通过算数运算和逻辑运算结果都会是int
*/
byte b1=1;
short s1=2;
// short ss=b1+1;//编译出错
// short ss=s1+1;//编译出错
// short ss=b1+s1;//编译出错
int i=b1+s1;
/**
* 移位运算
*/
byte b2=3;
b2<<=1;
System.out.println("b2<<=1-->"+b2);
/**
*127+1=-128
*/
byte b3=127;
b3++;
System.out.println("127+1="+b3);
}
}
|
wapalxj/Java
|
javaworkplace/SXT/src/C00_data/Test_code.java
|
Java
|
apache-2.0
| 1,493 |
/**
* Main framework
*/
var http = require('http');
var fs = require('fs');
var url = require('url');
var querystring = require('querystring');
var mime = require('mime');
var engineMod = require('./engine.js')
var WebApp = function(path,config){
console.log('Starting PanzerParty at '+path);
var basepath = path;
function checkConfig(config){
if (typeof(config.port)==='undefined')
config.port = 8090;
if (typeof(config.path)==='undefined')
config.path = {};
if (typeof(config.path.statics==='undefined'))
config.path.statics = '/static';
if (typeof(config.path.modules==='undefined'))
config.path.modules = '/modules';
if (typeof(config.path.controllers)==='undefined')
config.path.controllers = '/controllers';
if (typeof(config.path.views)==='undefined')
config.path.views='/views';
if (typeof(config.path.layouts)==='undefined')
config.path.layuots='/layouts';
if (typeof(config.path.l10n)==='undefined')
config.path.l10n='/l10n';
if (typeof(config.controllers)==='undefined')
config.controllers = [];
}
config.root = basepath;
checkConfig(config);
var engine = new engineMod.Engine(config);
this.start = function(){
engine.start();
};
};
exports.WebApp = WebApp;
|
theoddbeard/PanzerParty
|
core/app.js
|
JavaScript
|
apache-2.0
| 1,246 |
using Arinna.Northwind.ProductService.Business.Contract;
using Arinna.Northwind.ProductService.Data.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Text;
namespace Arinna.Northwind.ProductService.Business
{
public class CategoryManager: ICategoryManager
{
private readonly ICategoryRepository categoryRepository;
public CategoryManager(ICategoryRepository categoryRepository)
{
this.categoryRepository = categoryRepository;
}
}
}
|
ZGRTech/Arinna
|
nortwind/Arinna.Northwind.ProductService.Business/CategoryManager.cs
|
C#
|
apache-2.0
| 529 |
import Router from 'viewModels/router'
import read from './read'
const router = new Router;
router.get('token/read', '/', read);
export default router
|
lian-yue/lianyue-server
|
app/viewModels/token/routes.js
|
JavaScript
|
apache-2.0
| 155 |
/*
* Copyright 2014 Texas A&M Engineering Experiment Station
*
* 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 edu.tamu.tcat.crypto.bouncycastle.internal;
import java.security.Provider;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
private static Activator activator;
private static BundleContext bundleContext;
/**
* Instantiate and use this {@link Provider} instance instead of adding it to the
* JVM via {@link java.security.Security#addProvider(Provider)}.
* <br/>There are problems in "redeployable"
* environments (such as OSGI and Tomcat) with using JVM-global singletons. Namely,
* the provider could be added once if whatever added it was "undeployed", the provider
* becomes invalid and throws exceptions when trying to access it.
* <br/>
* To avoid these issues, the provider is constructed explicitly where needed and
* given as an argument to cypher API explicitly rather than having the security
* framework look up a provider by identifier or choose a default.
*/
private final Provider bouncyCastleProvider = new BouncyCastleProvider();
public static Activator getDefault() {
return activator;
}
public static BundleContext getContext() {
return bundleContext;
}
@Override
public void start(BundleContext bundleContext) throws Exception {
Activator.bundleContext = bundleContext;
activator = this;
}
@Override
public void stop(BundleContext bundleContext) throws Exception {
Activator.bundleContext = null;
activator = null;
}
public Provider getBouncyCastleProvider()
{
return bouncyCastleProvider;
}
}
|
tcat-tamu/crypto
|
bundles/edu.tamu.tcat.crypto.bouncycastle/src/edu/tamu/tcat/crypto/bouncycastle/internal/Activator.java
|
Java
|
apache-2.0
| 2,300 |
// Copyright 2014-2015 Boundary, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.boundary.sdk.event.esper;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class NewEmployeeEvent implements Serializable {
/**
*
*/
private static final long serialVersionUID = -8757562061344149582L;
Employee employee;
NewEmployeeEvent(Employee employee) {
this.employee = employee;
}
public NewEmployeeEvent(String firstName,
Map<String,Address> addresses) {
for (Entry<String, Address> entry : addresses.entrySet() ) {
addresses.put(entry.getKey(), entry.getValue());
}
}
public String getName() {
return this.employee.getName();
}
public Address getAddress(String type) {
return employee.getAddresses().get(type);
}
public Employee getSubordinate(int index) {
return employee.getSubordinate(index);
}
public Employee[] getAllSubordinates() {
Employee[] subordinates = new Employee[1];
return employee.getAllSubordinates();
}
public Iterable<EducationHistory> getEducation() {
return employee.getEducation();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("NewEmployeeEvent [employee=");
builder.append(employee);
builder.append("]");
return builder.toString();
}
}
|
boundary/boundary-event-sdk
|
src/test/java/com/boundary/sdk/event/esper/NewEmployeeEvent.java
|
Java
|
apache-2.0
| 1,889 |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2017 Yang Chen (cy2000@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
Detail: https://github.com/etechi/ServiceFramework/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
using System.Threading.Tasks;
using SF.Entities;
namespace SF.Auth.Permissions
{
public class RoleQueryArgument : ObjectQueryArgument<ObjectKey<string>>
{
}
public interface IRoleManager<TRoleInternal,TQueryArgument>
: IEntityManager<ObjectKey<string>, TRoleInternal>,
IEntitySource<ObjectKey<string>, TRoleInternal, TQueryArgument>
where TRoleInternal: Models.RoleInternal
where TQueryArgument: RoleQueryArgument
{
}
public interface IRoleManager : IRoleManager<Models.RoleInternal, RoleQueryArgument>
{ }
}
|
etechi/ServiceFramework
|
Projects/Server/Common/SF.Common.Abstractions/Auth/Permissions/IRoleManager.cs
|
C#
|
apache-2.0
| 1,380 |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.web.form;
import org.kuali.rice.krad.maintenance.MaintenanceDocument;
import org.kuali.rice.krad.uif.UifConstants.ViewType;
/**
* Form class for <code>MaintenanceView</code> screens
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class MaintenanceForm extends DocumentFormBase {
private static final long serialVersionUID = -5805825500852498048L;
protected String dataObjectClassName;
protected String maintenanceAction;
public MaintenanceForm() {
super();
setViewTypeName(ViewType.MAINTENANCE);
}
@Override
public MaintenanceDocument getDocument() {
return (MaintenanceDocument) super.getDocument();
}
// This is to provide a setter with matching type to
// public MaintenanceDocument getDocument() so that no
// issues occur with spring 3.1-M2 bean wrappers
public void setDocument(MaintenanceDocument document) {
super.setDocument(document);
}
public String getDataObjectClassName() {
return this.dataObjectClassName;
}
public void setDataObjectClassName(String dataObjectClassName) {
this.dataObjectClassName = dataObjectClassName;
}
public String getMaintenanceAction() {
return this.maintenanceAction;
}
public void setMaintenanceAction(String maintenanceAction) {
this.maintenanceAction = maintenanceAction;
}
}
|
ua-eas/ua-rice-2.1.9
|
krad/krad-web-framework/src/main/java/org/kuali/rice/krad/web/form/MaintenanceForm.java
|
Java
|
apache-2.0
| 2,006 |
using System;
using System.Collections;
using System.Collections.Generic;
using WizardsChess.Movement;
// Board arranged in A-H, 1-8. where A-H is replaced by 9-16
namespace WizardsChess.Chess.Pieces {
public abstract class ChessPiece{
public ChessPiece(ChessTeam team){
Team = team;
HasMoved = false;
CanJump = false;
}
/*
public ChessPiece(ChessPiece piece)
{
Type = piece.Type;
Team = piece.Team;
HasMoved = piece.HasMoved;
CanJump = piece.CanJump;
}
*/
public abstract ChessPiece DeepCopy();
public PieceType Type { get; protected set; }
public ChessTeam Team { get; }
public bool HasMoved { get; set; }
public bool CanJump { get; protected set; }
public virtual string ToShortString()
{
string piece = Type.ToString().Substring(0, 1);
if (Team == ChessTeam.White)
{
return piece + "w";
}
else if (Team == ChessTeam.Black)
{
return piece + "b";
}
else
{
return piece;
}
}
public override string ToString()
{
return Team.ToString() + "-" + Type.ToString();
}
public abstract IReadOnlyList<Vector2D> GetAllowedMotionVectors();
public abstract IReadOnlyList<Vector2D> GetAttackMotionVectors();
}
}
|
MorganR/wizards-chess
|
WizardsChess/WizardsChessUtils/Chess/Pieces/ChessPiece.cs
|
C#
|
apache-2.0
| 1,218 |
import 'style!../sass/spinner.scss';
const backdrop = `
<div class="js-blocking" id="lightbox-blocking">
<span class="lightbox-spinner"></span>
</div>
`;
const prevControl = `
<div class="lightbox-extra control prev js-control js-prev">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" width="60" height="60" viewBox="0 0 60 60" xml:space="preserve">
<circle class="lightbox-icon-bg" cx="30" cy="30" r="30"/>
<path class="lightbox-icon-arrow" d="M36.8,36.4L30.3,30l6.5-6.4l-3.5-3.4l-10,9.8l10,9.8L36.8,36.4z"/>
</svg>
</div>
`;
const nextControl = `
<div class="lightbox-extra control next js-control js-next">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" width="60" height="60" viewBox="0 0 60 60" xml:space="preserve">
<circle class="lightbox-icon-bg" cx="30" cy="30" r="30"/>
<path class="lightbox-icon-arrow" d="M24.2,23.5l6.6,6.5l-6.6,6.5l3.6,3.5L37.8,30l-10.1-9.9L24.2,23.5z"/>
</svg>
</div>
`;
const closeControl = `
<div class="lightbox-extra control close js-control js-close">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0" y="0" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
<circle class="lightbox-icon-bg" cx="50" cy="50" r="47.5"/>
<polygon class="lightbox-icon-close" points="64.5,39.8 60.2,35.5 50,45.7 39.8,35.5 35.5,39.8 45.7,50 35.5,60.2 39.8,64.5 50,54.3 60.2,64.5 64.5,60.2 54.3,50"/>
</svg>
</div>
`;
export const lightbox = `
<div class="js-lightbox-wrap offscreen" id="lightbox-wrap">
${backdrop}
<div class="js-lightbox-inner-wrap" id="lightbox-inner-wrap">
<div class="js-img-wrap" id="lightbox-img-wrap">
${prevControl}
${nextControl}
${closeControl}
<div class="lightbox-contents js-contents"></div>
</div>
</div>
</div>
`;
|
nemtsov/lightbox
|
src/templates.js
|
JavaScript
|
apache-2.0
| 1,861 |
package com.olmatix.model;
/**
* Created by Rahman on 12/28/2016.
*/
public class SpinnerObject {
private String databaseId;
private String databaseValue;
public SpinnerObject() {
this.databaseId = databaseId;
this.databaseValue = databaseValue;
}
public String getDatabaseId() {
return databaseId;
}
public void setDatabaseId(String databaseId) {
this.databaseId = databaseId;
}
public String getDatabaseValue() {
return databaseValue;
}
public void setDatabaseValue(String databaseValue) {
this.databaseValue = databaseValue;
}
}
|
lesjaw/Olmatix
|
olmatix/src/main/java/com/olmatix/model/SpinnerObject.java
|
Java
|
apache-2.0
| 641 |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.elasticloadbalancing.model;
import com.amazonaws.AmazonServiceException;
/**
* <p>
* The specified load balancer attribute does not exist.
* </p>
*/
public class LoadBalancerAttributeNotFoundException extends AmazonServiceException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new LoadBalancerAttributeNotFoundException with the specified error
* message.
*
* @param message Describes the error encountered.
*/
public LoadBalancerAttributeNotFoundException(String message) {
super(message);
}
}
|
trasa/aws-sdk-java
|
aws-java-sdk-elasticloadbalancing/src/main/java/com/amazonaws/services/elasticloadbalancing/model/LoadBalancerAttributeNotFoundException.java
|
Java
|
apache-2.0
| 1,217 |
package citrixadc
import (
"github.com/citrix/adc-nitro-go/resource/config/transform"
"github.com/citrix/adc-nitro-go/service"
"github.com/hashicorp/terraform/helper/schema"
"fmt"
"log"
)
func resourceCitrixAdcTransformaction() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
Create: createTransformactionFunc,
Read: readTransformactionFunc,
Update: updateTransformactionFunc,
Delete: deleteTransformactionFunc,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"comment": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"cookiedomainfrom": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"cookiedomaininto": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"priority": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"profilename": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"requrlfrom": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"requrlinto": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"resurlfrom": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"resurlinto": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"state": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
}
}
func createTransformactionFunc(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] citrixadc-provider: In createTransformactionFunc")
client := meta.(*NetScalerNitroClient).client
transformactionName := d.Get("name").(string)
// Create does not support all attributes
transformactionNew := transform.Transformaction{
Name: d.Get("name").(string),
Priority: d.Get("priority").(int),
Profilename: d.Get("profilename").(string),
State: d.Get("state").(string),
}
_, err := client.AddResource(service.Transformaction.Type(), transformactionName, &transformactionNew)
if err != nil {
return err
}
// Need to update with full set of attributes
transformaction := transform.Transformaction{
Comment: d.Get("comment").(string),
Cookiedomainfrom: d.Get("cookiedomainfrom").(string),
Cookiedomaininto: d.Get("cookiedomaininto").(string),
Name: d.Get("name").(string),
Priority: d.Get("priority").(int),
Requrlfrom: d.Get("requrlfrom").(string),
Requrlinto: d.Get("requrlinto").(string),
Resurlfrom: d.Get("resurlfrom").(string),
Resurlinto: d.Get("resurlinto").(string),
State: d.Get("state").(string),
}
_, err = client.UpdateResource(service.Transformaction.Type(), transformactionName, &transformaction)
if err != nil {
return err
}
d.SetId(transformactionName)
err = readTransformactionFunc(d, meta)
if err != nil {
log.Printf("[ERROR] netscaler-provider: ?? we just created this transformaction but we can't read it ?? %s", transformactionName)
return nil
}
return nil
}
func readTransformactionFunc(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] citrixadc-provider: In readTransformactionFunc")
client := meta.(*NetScalerNitroClient).client
transformactionName := d.Id()
log.Printf("[DEBUG] citrixadc-provider: Reading transformaction state %s", transformactionName)
data, err := client.FindResource(service.Transformaction.Type(), transformactionName)
if err != nil {
log.Printf("[WARN] citrixadc-provider: Clearing transformaction state %s", transformactionName)
d.SetId("")
return nil
}
d.Set("name", data["name"])
d.Set("comment", data["comment"])
d.Set("cookiedomainfrom", data["cookiedomainfrom"])
d.Set("cookiedomaininto", data["cookiedomaininto"])
d.Set("name", data["name"])
d.Set("priority", data["priority"])
d.Set("profilename", data["profilename"])
d.Set("requrlfrom", data["requrlfrom"])
d.Set("requrlinto", data["requrlinto"])
d.Set("resurlfrom", data["resurlfrom"])
d.Set("resurlinto", data["resurlinto"])
d.Set("state", data["state"])
return nil
}
func updateTransformactionFunc(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] citrixadc-provider: In updateTransformactionFunc")
client := meta.(*NetScalerNitroClient).client
transformactionName := d.Get("name").(string)
transformaction := transform.Transformaction{
Name: d.Get("name").(string),
}
hasChange := false
if d.HasChange("comment") {
log.Printf("[DEBUG] citrixadc-provider: Comment has changed for transformaction %s, starting update", transformactionName)
transformaction.Comment = d.Get("comment").(string)
hasChange = true
}
if d.HasChange("cookiedomainfrom") {
log.Printf("[DEBUG] citrixadc-provider: Cookiedomainfrom has changed for transformaction %s, starting update", transformactionName)
transformaction.Cookiedomainfrom = d.Get("cookiedomainfrom").(string)
hasChange = true
}
if d.HasChange("cookiedomaininto") {
log.Printf("[DEBUG] citrixadc-provider: Cookiedomaininto has changed for transformaction %s, starting update", transformactionName)
transformaction.Cookiedomaininto = d.Get("cookiedomaininto").(string)
hasChange = true
}
if d.HasChange("name") {
log.Printf("[DEBUG] citrixadc-provider: Name has changed for transformaction %s, starting update", transformactionName)
transformaction.Name = d.Get("name").(string)
hasChange = true
}
if d.HasChange("priority") {
log.Printf("[DEBUG] citrixadc-provider: Priority has changed for transformaction %s, starting update", transformactionName)
transformaction.Priority = d.Get("priority").(int)
hasChange = true
}
if d.HasChange("profilename") {
log.Printf("[DEBUG] citrixadc-provider: Profilename has changed for transformaction %s, starting update", transformactionName)
transformaction.Profilename = d.Get("profilename").(string)
hasChange = true
}
if d.HasChange("requrlfrom") {
log.Printf("[DEBUG] citrixadc-provider: Requrlfrom has changed for transformaction %s, starting update", transformactionName)
transformaction.Requrlfrom = d.Get("requrlfrom").(string)
hasChange = true
}
if d.HasChange("requrlinto") {
log.Printf("[DEBUG] citrixadc-provider: Requrlinto has changed for transformaction %s, starting update", transformactionName)
transformaction.Requrlinto = d.Get("requrlinto").(string)
hasChange = true
}
if d.HasChange("resurlfrom") {
log.Printf("[DEBUG] citrixadc-provider: Resurlfrom has changed for transformaction %s, starting update", transformactionName)
transformaction.Resurlfrom = d.Get("resurlfrom").(string)
hasChange = true
}
if d.HasChange("resurlinto") {
log.Printf("[DEBUG] citrixadc-provider: Resurlinto has changed for transformaction %s, starting update", transformactionName)
transformaction.Resurlinto = d.Get("resurlinto").(string)
hasChange = true
}
if d.HasChange("state") {
log.Printf("[DEBUG] citrixadc-provider: State has changed for transformaction %s, starting update", transformactionName)
transformaction.State = d.Get("state").(string)
hasChange = true
}
if hasChange {
_, err := client.UpdateResource(service.Transformaction.Type(), transformactionName, &transformaction)
if err != nil {
return fmt.Errorf("Error updating transformaction %s", transformactionName)
}
}
return readTransformactionFunc(d, meta)
}
func deleteTransformactionFunc(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] citrixadc-provider: In deleteTransformactionFunc")
client := meta.(*NetScalerNitroClient).client
transformactionName := d.Id()
err := client.DeleteResource(service.Transformaction.Type(), transformactionName)
if err != nil {
return err
}
d.SetId("")
return nil
}
|
citrix/terraform-provider-netscaler
|
citrixadc/resource_citrixadc_transformaction.go
|
GO
|
apache-2.0
| 8,186 |
<?php
namespace BuyPlayTix\DataBean;
class ObjectAdapter implements IAdapter
{
public static $DB_DIR;
private $tables = [];
private $queries = [];
public function __construct()
{}
function load($databean, $param = "")
{
$table = $databean->getTable();
$pk = $databean->getPk();
if (! array_key_exists($table, $this->tables)) {
$this->tables[$table] = [];
}
$b = $this->tables[$table];
if (is_array($param)) {
foreach ($b as $bean) {
if (array_key_exists($param[0], $bean) && $bean[$param[0]] == $param[1]) {
$databean->fields = $bean;
$databean->setNew(false);
return $databean;
}
}
} elseif (strlen($param) > 0) {
foreach ($b as $bean) {
if (array_key_exists($pk, $bean) && $bean[$pk] == $param) {
$databean->fields = $bean;
$databean->setNew(false);
return $databean;
}
}
}
$uuid = UUID::get();
$databean->fields[$pk] = $uuid;
$databean->setNew(true);
return $databean;
}
function loadAll($databean, $field = "", $param = "", $andClause = "")
{
if (strlen($field) > 0) {
if (is_array($param) && count($param) == 1) {
$whereClause = ' where ' . $field . ' = ' . $param[0];
} else {
$valList = $this->_parseList($param);
$whereClause = ' where ' . $field . ' in ' . $valList;
}
} elseif (is_array($param) && count($param) > 0) {
if (is_array($param) && count($param) == 1) {
$whereClause = ' where ' . $databean->getPk() . ' = ' . $param[0];
} else {
$valList = $this->_parseList($param);
$whereClause = ' where ' . $databean->getPk() . ' in ' . $valList;
}
} else {
$whereClause = "";
}
$group_by = "";
$order_by = "";
$where = array();
$clause = $whereClause . " " . $andClause;
$chunks = preg_split("/\s*GROUP\s+BY\s*/i", $clause);
if (count($chunks) == 2) {
$clause = $chunks[0];
$group_by = $chunks[1];
}
$chunks = preg_split("/\s*ORDER\s+BY\s*/i", $clause);
if (count($chunks) == 2) {
$clause = $chunks[0];
$order_by = $chunks[1];
}
$clause = preg_replace("/\s*WHERE\s*/i", "", $clause);
$chunks = preg_split("/\s*AND\s*/i", $clause);
foreach ($chunks as $chunk) {
$where_chunks = preg_split("/\s*!=\s*/i", $chunk);
if (count($where_chunks) == 2) {
$field = strtoupper(trim($where_chunks[0]));
$value = trim($where_chunks[1], ' \'');
$where[$field] = array(
"v" => $value,
"condition" => "!="
);
continue;
}
$where_chunks = preg_split("/\s*=\s*/i", $chunk);
if (count($where_chunks) == 2) {
$field = strtoupper(trim($where_chunks[0]));
$value = trim($where_chunks[1], ' \'');
$where[$field] = array(
"v" => $value,
"condition" => "="
);
continue;
}
$where_chunks = preg_split("/\s+in\s*/i", $chunk);
if (count($where_chunks) == 2) {
$field = strtoupper(trim($where_chunks[0]));
$value = str_replace(')', '', str_replace('(', '', $where_chunks[1]));
$values = explode(',', $value);
for ($i = 0; $i < count($values); $i ++) {
$values[$i] = trim($values[$i], ' \'');
}
$where[$field] = array(
"v" => $values,
"condition" => "="
);
continue;
}
}
$databeans = array();
$table = $databean->getTable();
$pk = $databean->getPk();
$b = $this->tables[$table];
foreach ($b as $bean) {
$bean_matches = true;
foreach ($where as $field => $predicate) {
$value = $predicate["v"];
$condition = $predicate["condition"];
if (is_array($value)) {
$found_match = false;
foreach ($value as $v) {
if (array_key_exists($field, $bean) && $this->isMatch($bean[$field], $condition, $v)) {
$found_match = true;
}
}
if (! $found_match) {
$bean_matches = false;
}
} elseif (!array_key_exists($field, $bean) || ($this->isMatch($bean[$field], $condition, $value) === false)) {
$bean_matches = false;
}
}
if ($bean_matches) {
$className = get_class($databean);
$newBean = new $className($bean[$pk]);
$databeans[] = $newBean;
}
}
return $databeans;
}
private function isMatch($beanValue, $condition, $value)
{
if ($condition === '=') {
return $beanValue === $value;
}
if ($condition === '!=') {
return $beanValue !== $value;
}
return false;
}
function update($databean)
{
$table = $databean->getTable();
$pk = $databean->getPk();
if (array_key_exists($table, $this->tables) === false) {
$this->tables[$table] = [];
}
$existingRowKey = null;
for($index = 0; $index < count($this->tables[$table]); $index++) {
$row = $this->tables[$table][$index];
if (array_key_exists($pk, $row) && $row[$pk] === $databean->$pk) {
$existingRowKey = $index;
break;
}
}
$databean->setNew(false);
if ($existingRowKey === null) {
$this->tables[$table][] = $databean->getFields();
return $databean;
}
foreach ($databean->getFields() as $key => $value) {
$this->tables[$table][$existingRowKey][$key] = $value;
}
return $databean;
}
function delete($databean)
{
$table = $databean->getTable();
$pk = $databean->getPk();
if (! array_key_exists($table, $this->tables)) {
return $databean;
}
foreach ($this->tables[$table] as $index => $row) {
if (array_key_exists($pk, $row) && $row[$pk] === $databean->$pk) {
unset($this->tables[$table][$index]);
return $databean;
}
}
}
private function get_pk_value($databean)
{
$pk_value = $databean->get($databean->getPk());
if ($pk_value != NULL) {
return $pk_value;
}
return UUID::get();
}
function raw_delete($table, $where_fields = array())
{
if (array_key_exists($table, $this->tables) === false) {
$this->tables[$table] = [];
return;
}
$t = $this->tables[$table];
foreach ($t as $index => $row) {
$found_match = false;
foreach ($where_fields as $name => $v) {
// print $row[$name] . "\n";
// $v = 1, $row[$name] = 2
$value = $v;
if (is_array($v)) {
$condition = $v['condition'];
$value = $v['value'];
switch ($condition) {
case '<>':
case '!=':
if ($row[$name] == $value) {
$found_match = true;
}
break;
case '>':
if ($row[$name] > $value) {
$found_match = true;
}
break;
case '<':
if ($row[$name] < $value) {
$found_match = true;
}
break;
case 'in':
if (! in_array($row[$name], $value)) {
$found_match = true;
}
break;
case '=':
default:
if ($row[$name] != $value) {
$found_match = true;
}
break;
}
} elseif ($row[$name] === $value) {
$found_match = true;
}
}
if ($found_match) {
unset($t[$index]);
}
}
$this->tables[$table] = $t;
}
function raw_insert($table, $fields = array())
{
if (! isset($this->tables[$table])) {
$this->tables[$table] = array();
}
$t = $this->tables[$table];
foreach ($t as $index => $row) {
$found_match = true;
foreach ($fields as $name => $value) {
if ($row[$name] != $value) {
$found_match = false;
}
}
if ($found_match) {
throw new Exception("Unique constraint failure.");
}
}
$this->tables[$table][] = $fields;
}
function raw_replace($table, $fields = []) {
if (! isset($this->tables[$table])) {
return $this->raw_insert($table, $fields);
}
$pk = "UID";
if (array_key_exists("ID", $fields)) {
$pk = "ID";
}
$foundRow = false;
$t = $this->tables[$table];
foreach ($t as $index => $row) {
if ($row[$pk] === $fields[$pk]) {
$foundRow = true;
foreach($fields as $key => $value) {
$this->tables[$table][$index][$key] = $value;
}
}
}
if (!$foundRow) {
return $this->raw_insert($table, $fields);
}
}
// TODO: Add order and grouping, aggregate
function raw_select($table, $fields = array(), $where_fields = array(), $cast_class = NULL, $order = array(), $group = array())
{
if (array_key_exists($table, $this->tables) === false) {
$this->tables[$table] = array();
}
$results = array();
$t = $this->tables[$table];
foreach ($t as $index => $row) {
$found_match = true;
foreach ($where_fields as $name => $v) {
$value = $v;
if (is_array($v)) {
$condition = $v['condition'];
$value = $v['value'];
switch ($condition) {
case '<>':
case '!=':
if ($row[$name] == $value) {
$found_match = false;
}
break;
case '>':
if ($row[$name] <= $value) {
$found_match = false;
}
break;
case '<':
if ($row[$name] < $value) {
$found_match >= false;
}
break;
case 'in':
if (! in_array($row[$name], $value)) {
$found_match = false;
}
break;
case '=':
default:
if ($row[$name] != $value) {
$found_match = false;
}
break;
}
} elseif (!array_key_exists($name, $row) || $row[$name] != $value) {
$found_match = false;
}
}
if ($found_match) {
if ($cast_class != NULL) {
$class = new \ReflectionClass($cast_class);
$results[] = $class->newInstanceArgs(array(
$row[$fields[0]]
));
} else {
$ret_row = array();
$aggregation = array();
foreach ($fields as $field) {
if (is_array($field)) {
$field_name = $field['name'];
$field_alias = $field['alias'];
if (empty($field_alias)) {
$field_alias = $field_name;
}
switch ($field['aggregation']) {
case 'count':
if (isset($aggregation[$field_alias])) {
$aggregation[$field_alias] = $aggregation[$field_alias]++;
break;
}
$aggregation[$field_alias] = 1;
break;
case 'sum':
if (isset($aggregation[$field_alias])) {
$aggregation[$field_alias] = $aggregation[$field_alias] += $row[$field_name];
break;
}
$aggregation[$field_alias] = $row[$field_name];
break;
default:
throw new \Exception("Unknown aggregation type for field $field_name.");
}
} else {
if (array_key_exists($field, $row)) {
$ret_row[$field] = $row[$field];
} else {
$ret_row[$field] = null;
}
}
}
foreach ($aggregation as $field_name => $field_value) {
$ret_row[$field_name] = $field_value;
}
$results[] = $ret_row;
}
}
}
return $results;
}
function raw_update($table, $fields = array(), $where_fields = array())
{
if (array_key_exists($table, $this->tables) === false) {
$this->tables[$table] = array();
}
$t = $this->tables[$table];
foreach ($t as $index => $row) {
$found_match = true;
foreach ($where_fields as $name => $v) {
$value = $v;
if (is_array($v)) {
switch ($v['condition']) {
case '<>':
case '!=':
if ($row[$name] == $value) {
$found_match = false;
}
break;
case '>':
if ($row[$name] > $value) {
$found_match = false;
}
break;
case '<':
if ($row[$name] < $value) {
$found_match = false;
}
break;
case 'in':
if (! in_array($row[$name], $value)) {
$found_match = false;
}
break;
case '=':
default:
if ($row[$name] != $value) {
$found_match = false;
}
break;
}
$condition = $v['condition'];
$value = $v['value'];
} else {
if ($row[$name] != $value) {
$found_match = false;
}
}
}
if ($found_match) {
foreach ($row as $row_name => $row_value) {
foreach ($fields as $field_name => $field_value) {
if ($row_name === $field_name) {
$this->tables[$table][$index][$row_name] = $field_value;
}
}
}
}
}
}
public function set_named_query_value($name, $value)
{
$this->queries[$name] = $value;
}
function named_query($name, $sql = "", $params = array(), $hash = true)
{
if (! array_key_exists($name, $this->queries)) {
throw new \Exception("No value set for named query: " . $name);
}
return $this->queries[$name];
}
private function _parseList($param = Array())
{
return "('" . implode("','", $param) . "')";
}
public function loadDatabase()
{
if (file_exists(ObjectAdapter::$DB_DIR . "tables.test.db")) {
$lock = fopen(ObjectAdapter::$DB_DIR . "tables.test.db", 'rb');
@flock($lock, LOCK_SH);
$this->tables = unserialize(file_get_contents(ObjectAdapter::$DB_DIR . "tables.test.db"));
@flock($lock, LOCK_UN);
fclose($lock);
}
if (file_exists(ObjectAdapter::$DB_DIR . "queries.test.db")) {
$lock = fopen(ObjectAdapter::$DB_DIR . "queries.test.db", 'rb');
@flock($lock, LOCK_SH);
$this->queries = unserialize(file_get_contents(ObjectAdapter::$DB_DIR . "queries.test.db"));
@flock($lock, LOCK_UN);
fclose($lock);
}
}
public function saveDatabase()
{
file_put_contents(ObjectAdapter::$DB_DIR . "tables.test.db", serialize($this->tables), LOCK_EX);
file_put_contents(ObjectAdapter::$DB_DIR . "queries.test.db", serialize($this->queries), LOCK_EX);
if ((fileperms(ObjectAdapter::$DB_DIR . "tables.test.db") & 0777) !== 0766) {
chmod(ObjectAdapter::$DB_DIR . "tables.test.db", 0766);
}
if ((fileperms(ObjectAdapter::$DB_DIR . "queries.test.db") & 0777) !== 0766) {
chmod(ObjectAdapter::$DB_DIR . "queries.test.db", 0766);
}
}
public function printDatabase()
{
print "Queries: \n";
print_r($this->queries);
print "Tables: \n";
print_r($this->tables);
}
public function clearDatabase()
{
$this->tables = [];
$this->queries = [];
$this->saveDatabase();
}
}
|
tthomas48/databean
|
BuyPlayTix/DataBean/ObjectAdapter.php
|
PHP
|
apache-2.0
| 19,538 |