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
|
---|---|---|---|---|---|
import * as types from '../mutation_types'
const initTime = {
time: new Date().getDate()
};
export default {
repositoryList({ commit },data) {
commit(types.REPOSITORY_LIST, data)
},
updateList({commit},list){
commit(types.UPDATE_LIST,list)
}
};
|
fangyang888/vue-project
|
src/store/actions.js
|
JavaScript
|
apache-2.0
| 273 |
require 'prime/rails/primerails' if defined?(Rails)
|
lazaronixon/prime-rails
|
lib/prime-rails.rb
|
Ruby
|
apache-2.0
| 51 |
/**
* @fileoverview This file is generated by the Angular 2 template compiler.
* Do not edit.
* @suppress {suspiciousCode,uselessCode,missingProperties}
*/
/* tslint:disable */
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
import * as import0 from './item-reorder';
import * as import1 from '@angular/core/src/change_detection/change_detection';
import * as import2 from '@angular/core/src/linker/view';
import * as import3 from '@angular/core/src/linker/view_utils';
import * as import5 from '@angular/core/src/metadata/view';
import * as import6 from '@angular/core/src/linker/view_type';
import * as import7 from '@angular/core/src/linker/component_factory';
import * as import8 from './item';
import * as import9 from '@angular/core/src/linker/element_ref';
import * as import10 from '../icon/icon.ngfactory';
import * as import11 from '../../config/config';
import * as import12 from '../icon/icon';
export var Wrapper_ItemReorder = (function () {
function Wrapper_ItemReorder(p0, p1, p2, p3) {
this._changed = false;
this.context = new import0.ItemReorder(p0, p1, p2, p3);
this._expr_0 = import1.UNINITIALIZED;
this._expr_1 = import1.UNINITIALIZED;
this._expr_2 = import1.UNINITIALIZED;
}
Wrapper_ItemReorder.prototype.ngOnDetach = function (view, componentView, el) {
};
Wrapper_ItemReorder.prototype.ngOnDestroy = function () {
this.context.ngOnDestroy();
(this.subscription0 && this.subscription0.unsubscribe());
};
Wrapper_ItemReorder.prototype.check_reorder = function (currValue, throwOnChange, forceUpdate) {
if ((forceUpdate || import3.checkBinding(throwOnChange, this._expr_0, currValue))) {
this._changed = true;
this.context.reorder = currValue;
this._expr_0 = currValue;
}
};
Wrapper_ItemReorder.prototype.ngDoCheck = function (view, el, throwOnChange) {
var changed = this._changed;
this._changed = false;
return changed;
};
Wrapper_ItemReorder.prototype.checkHost = function (view, componentView, el, throwOnChange) {
var currVal_1 = this.context._enableReorder;
if (import3.checkBinding(throwOnChange, this._expr_1, currVal_1)) {
view.renderer.setElementClass(el, 'reorder-enabled', currVal_1);
this._expr_1 = currVal_1;
}
var currVal_2 = this.context._visibleReorder;
if (import3.checkBinding(throwOnChange, this._expr_2, currVal_2)) {
view.renderer.setElementClass(el, 'reorder-visible', currVal_2);
this._expr_2 = currVal_2;
}
};
Wrapper_ItemReorder.prototype.handleEvent = function (eventName, $event) {
var result = true;
return result;
};
Wrapper_ItemReorder.prototype.subscribe = function (view, _eventHandler, emit0) {
this._eventHandler = _eventHandler;
if (emit0) {
(this.subscription0 = this.context.ionItemReorder.subscribe(_eventHandler.bind(view, 'ionItemReorder')));
}
};
return Wrapper_ItemReorder;
}());
export var Wrapper_Reorder = (function () {
function Wrapper_Reorder(p0, p1) {
this._changed = false;
this.context = new import0.Reorder(p0, p1);
}
Wrapper_Reorder.prototype.ngOnDetach = function (view, componentView, el) {
};
Wrapper_Reorder.prototype.ngOnDestroy = function () {
};
Wrapper_Reorder.prototype.ngDoCheck = function (view, el, throwOnChange) {
var changed = this._changed;
this._changed = false;
return changed;
};
Wrapper_Reorder.prototype.checkHost = function (view, componentView, el, throwOnChange) {
};
Wrapper_Reorder.prototype.handleEvent = function (eventName, $event) {
var result = true;
if ((eventName == 'click')) {
var pd_sub_0 = (this.context.onClick($event) !== false);
result = (pd_sub_0 && result);
}
return result;
};
Wrapper_Reorder.prototype.subscribe = function (view, _eventHandler) {
this._eventHandler = _eventHandler;
};
return Wrapper_Reorder;
}());
var renderType_Reorder_Host = import3.createRenderComponentType('', 0, import5.ViewEncapsulation.None, [], {});
var View_Reorder_Host0 = (function (_super) {
__extends(View_Reorder_Host0, _super);
function View_Reorder_Host0(viewUtils, parentView, parentIndex, parentElement) {
_super.call(this, View_Reorder_Host0, renderType_Reorder_Host, import6.ViewType.HOST, viewUtils, parentView, parentIndex, parentElement, import1.ChangeDetectorStatus.CheckAlways);
}
View_Reorder_Host0.prototype.createInternal = function (rootSelector) {
this._el_0 = import3.selectOrCreateRenderHostElement(this.renderer, 'ion-reorder', import3.EMPTY_INLINE_ARRAY, rootSelector, null);
this.compView_0 = new View_Reorder0(this.viewUtils, this, 0, this._el_0);
this._Reorder_0_3 = new Wrapper_Reorder(this.injectorGet(import8.Item, this.parentIndex), new import9.ElementRef(this._el_0));
this.compView_0.create(this._Reorder_0_3.context);
var disposable_0 = import3.subscribeToRenderElement(this, this._el_0, new import3.InlineArray2(2, 'click', null), this.eventHandler(this.handleEvent_0));
this.init(this._el_0, (this.renderer.directRenderer ? null : [this._el_0]), [disposable_0]);
return new import7.ComponentRef_(0, this, this._el_0, this._Reorder_0_3.context);
};
View_Reorder_Host0.prototype.injectorGetInternal = function (token, requestNodeIndex, notFoundResult) {
if (((token === import0.Reorder) && (0 === requestNodeIndex))) {
return this._Reorder_0_3.context;
}
return notFoundResult;
};
View_Reorder_Host0.prototype.detectChangesInternal = function (throwOnChange) {
this._Reorder_0_3.ngDoCheck(this, this._el_0, throwOnChange);
this.compView_0.detectChanges(throwOnChange);
};
View_Reorder_Host0.prototype.destroyInternal = function () {
this.compView_0.destroy();
};
View_Reorder_Host0.prototype.visitRootNodesInternal = function (cb, ctx) {
cb(this._el_0, ctx);
};
View_Reorder_Host0.prototype.handleEvent_0 = function (eventName, $event) {
this.compView_0.markPathToRootAsCheckOnce();
var result = true;
result = (this._Reorder_0_3.handleEvent(eventName, $event) && result);
return result;
};
return View_Reorder_Host0;
}(import2.AppView));
export var ReorderNgFactory = new import7.ComponentFactory('ion-reorder', View_Reorder_Host0, import0.Reorder);
var styles_Reorder = [];
var renderType_Reorder = import3.createRenderComponentType('', 0, import5.ViewEncapsulation.None, styles_Reorder, {});
export var View_Reorder0 = (function (_super) {
__extends(View_Reorder0, _super);
function View_Reorder0(viewUtils, parentView, parentIndex, parentElement) {
_super.call(this, View_Reorder0, renderType_Reorder, import6.ViewType.COMPONENT, viewUtils, parentView, parentIndex, parentElement, import1.ChangeDetectorStatus.CheckAlways);
}
View_Reorder0.prototype.createInternal = function (rootSelector) {
var parentRenderNode = this.renderer.createViewRoot(this.parentElement);
this._el_0 = import3.createRenderElement(this.renderer, parentRenderNode, 'ion-icon', new import3.InlineArray4(4, 'name', 'reorder', 'role', 'img'), null);
this._Icon_0_3 = new import10.Wrapper_Icon(this.parentView.injectorGet(import11.Config, this.parentIndex), new import9.ElementRef(this._el_0), this.renderer);
this.init(null, (this.renderer.directRenderer ? null : [this._el_0]), null);
return null;
};
View_Reorder0.prototype.injectorGetInternal = function (token, requestNodeIndex, notFoundResult) {
if (((token === import12.Icon) && (0 === requestNodeIndex))) {
return this._Icon_0_3.context;
}
return notFoundResult;
};
View_Reorder0.prototype.detectChangesInternal = function (throwOnChange) {
var currVal_0_0_0 = 'reorder';
this._Icon_0_3.check_name(currVal_0_0_0, throwOnChange, false);
this._Icon_0_3.ngDoCheck(this, this._el_0, throwOnChange);
this._Icon_0_3.checkHost(this, this, this._el_0, throwOnChange);
};
View_Reorder0.prototype.destroyInternal = function () {
this._Icon_0_3.ngOnDestroy();
};
return View_Reorder0;
}(import2.AppView));
//# sourceMappingURL=item-reorder.ngfactory.js.map
|
driftyco/ionic-site
|
content/docs/v3/demos/src/components/item/item-reorder.ngfactory.js
|
JavaScript
|
apache-2.0
| 8,737 |
var mercurius = require('../index.js');
var request = require('supertest');
var crypto = require('crypto');
var should = require('chai').should();
var redis = require('../redis.js');
describe('mercurius register', function() {
var token;
before(function() {
return mercurius.ready;
});
var origRandomBytes = crypto.randomBytes;
afterEach(function() {
crypto.randomBytes = origRandomBytes;
});
it('replies with 500 if there\'s an error while generating the token', function(done) {
crypto.randomBytes = function(len, cb) {
cb(new Error('Fake error.'));
};
request(mercurius.app)
.post('/register')
.send({
machineId: 'machineX',
endpoint: 'http://localhost:50005',
key: '',
})
.expect(500, done);
});
it('successfully registers users', function(done) {
request(mercurius.app)
.post('/register')
.send({
machineId: 'machine',
endpoint: 'https://localhost:50008',
key: '',
})
.expect(200)
.expect(function(res) {
res.body.should.be.an('object');
res.body.machines.should.be.an('object');
res.body.token.should.have.length(16);
token = res.body.token;
})
.end(done);
});
it('successfully registers additional machine', function(done) {
request(mercurius.app)
.post('/register')
.send({
token: token,
machineId: 'machine2',
endpoint: 'endpoint',
key: '',
})
.expect(200)
.expect(function(res) {
res.body.token.should.equal(token);
res.body.machines.machine.endpoint.should.equal('https://localhost:50008');
res.body.machines.machine2.endpoint.should.equal('endpoint');
})
.end(done);
});
it('successfully registers a machine even if it exists', function(done) {
redis.smembers(token)
.then(function(machines) {
var startlength = machines.length;
request(mercurius.app)
.post('/register')
.send({
token: token,
machineId: 'machine2',
endpoint: 'endpoint2',
key: '',
})
.expect(200)
.expect(function(res) {
res.body.token.should.equal(token);
res.body.machines.machine2.endpoint.should.equal('endpoint2');
Object.keys(res.body.machines).should.have.length(startlength);
})
.end(done);
});
});
it('returns 404 if bad token provided', function(done) {
request(mercurius.app)
.post('/register')
.send({
token: 'notexisting',
machineId: 'machine of a not existing token',
endpoint: 'endpoint',
key: '',
})
.expect(404, done);
});
});
|
marco-c/mercurius
|
test/testRegister.js
|
JavaScript
|
apache-2.0
| 2,638 |
using System;
using System.Diagnostics;
using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Media;
namespace ArcGISRuntimeSDKDotNet_StoreSamples.Samples
{
/// <summary>
/// Shows how to swipe one map over another.
/// </summary>
/// <title>Swipe</title>
/// <category>Mapping</category>
public sealed partial class SwipeMap : Page
{
public SwipeMap()
{
this.InitializeComponent();
thumb.RenderTransform = new TranslateTransform() { X = 0, Y = 0 };
mapImagery.Clip = new RectangleGeometry() { Rect = new Rect(0, 0, 0, 0) };
mapStreets.ExtentChanged += mapStreets_ExtentChanged;
}
private void Thumb_DragDelta(object sender, DragDeltaEventArgs e)
{
try
{
var transform = (TranslateTransform)thumb.RenderTransform;
transform.X = Math.Max(0, Math.Min(transform.X + e.HorizontalChange, this.ActualWidth - thumb.ActualWidth));
mapImagery.Clip.Rect = new Rect(0, 0, transform.X, this.ActualHeight);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void mapStreets_ExtentChanged(object sender, EventArgs e)
{
try
{
if (mapImagery.Extent != null)
mapImagery.SetView(mapStreets.Extent);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
}
|
Tyshark9/arcgis-runtime-samples-dotnet
|
src/Store/ArcGISRuntimeSDKDotNet_StoreSamples/Samples/Mapping/Swipe.xaml.cs
|
C#
|
apache-2.0
| 1,647 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.08.18 at 01:26:07 PM PDT
//
package umich.ms.io.type.mzidentml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* A molecule modification specification. If n modifications have been found on a peptide, there should be n instances of Modification. If multiple modifications are provided as cvParams, it is assumed that the modification is ambiguous i.e. one modification or another. A cvParam must be provided with the identification of the modification sourced from a suitable CV e.g. UNIMOD. If the modification is not present in the CV (and this will be checked by the semantic validator within a given tolerance window), there is a “unknown modification†CV term that must be used instead. A neutral loss should be defined as an additional CVParam within Modification. If more complex information should be given about neutral losses (such as presence/absence on particular product ions), this can additionally be encoded within the FragmentationArray.
*
* <p>Java class for ModificationType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ModificationType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cvParam" type="{http://psidev.info/psi/pi/mzIdentML/1.2}CVParamType" maxOccurs="unbounded"/>
* </sequence>
* <attribute name="location" type="{http://www.w3.org/2001/XMLSchema}int" />
* <attribute name="residues" type="{http://psidev.info/psi/pi/mzIdentML/1.2}listOfChars" />
* <attribute name="avgMassDelta" type="{http://www.w3.org/2001/XMLSchema}double" />
* <attribute name="monoisotopicMassDelta" type="{http://www.w3.org/2001/XMLSchema}double" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ModificationType", namespace = "http://psidev.info/psi/pi/mzIdentML/1.2", propOrder = {
"cvParam"
})
public class ModificationType {
@XmlElement(namespace = "http://psidev.info/psi/pi/mzIdentML/1.2", required = true)
protected List<CVParamType> cvParam;
@XmlAttribute(name = "location")
protected Integer location;
@XmlAttribute(name = "residues")
protected List<String> residues;
@XmlAttribute(name = "avgMassDelta")
protected Double avgMassDelta;
@XmlAttribute(name = "monoisotopicMassDelta")
protected Double monoisotopicMassDelta;
/**
* Gets the value of the cvParam property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cvParam property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCvParam().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CVParamType }
*
*
*/
public List<CVParamType> getCvParam() {
if (cvParam == null) {
cvParam = new ArrayList<CVParamType>();
}
return this.cvParam;
}
/**
* Gets the value of the location property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getLocation() {
return location;
}
/**
* Sets the value of the location property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setLocation(Integer value) {
this.location = value;
}
/**
* Gets the value of the residues property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the residues property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getResidues().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getResidues() {
if (residues == null) {
residues = new ArrayList<String>();
}
return this.residues;
}
/**
* Gets the value of the avgMassDelta property.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getAvgMassDelta() {
return avgMassDelta;
}
/**
* Sets the value of the avgMassDelta property.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setAvgMassDelta(Double value) {
this.avgMassDelta = value;
}
/**
* Gets the value of the monoisotopicMassDelta property.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getMonoisotopicMassDelta() {
return monoisotopicMassDelta;
}
/**
* Sets the value of the monoisotopicMassDelta property.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setMonoisotopicMassDelta(Double value) {
this.monoisotopicMassDelta = value;
}
}
|
chhh/MSFTBX
|
xsd-jaxb2-maven-build/target/generated-sources/xjc/umich/ms/io/type/mzidentml/ModificationType.java
|
Java
|
apache-2.0
| 6,447 |
package de.atomfrede.jenkins.domain;
import java.io.Serializable;
import com.google.gson.Gson;
public class TestReport implements Serializable {
private static final long serialVersionUID = -974641584792263440L;
private int failCount;
private int skipCount;
private int totalCount;
public int getFailCount() {
return failCount;
}
public TestReport setFailCount(int failCount) {
this.failCount = failCount;
return this;
}
public int getSkipCount() {
return skipCount;
}
public TestReport setSkipCount(int skipCount) {
this.skipCount = skipCount;
return this;
}
public int getTotalCount() {
return totalCount;
}
public TestReport setTotalCount(int totalCount) {
this.totalCount = totalCount;
return this;
}
public String toJson() {
Gson gson = new Gson();
return gson.toJson(this);
}
}
|
atomfrede/animated-octo-adventure
|
jenkins.service/src/main/java/de/atomfrede/jenkins/domain/TestReport.java
|
Java
|
apache-2.0
| 838 |
/*
* Copyright 2000-2016 JetBrains s.r.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 com.jetbrains.python.refactoring;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.collect.Sets;
import com.intellij.codeInsight.controlflow.ControlFlow;
import com.intellij.codeInsight.controlflow.ControlFlowUtil;
import com.intellij.codeInsight.controlflow.Instruction;
import com.intellij.openapi.util.Comparing;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache;
import com.jetbrains.python.codeInsight.controlflow.ReadWriteInstruction;
import com.jetbrains.python.codeInsight.controlflow.ScopeOwner;
import com.jetbrains.python.psi.PyAugAssignmentStatement;
import com.jetbrains.python.psi.PyElement;
import com.jetbrains.python.psi.PyExpression;
import com.jetbrains.python.psi.PyImplicitImportNameDefiner;
import com.jetbrains.python.psi.PyImportElement;
import com.jetbrains.python.psi.PyReferenceExpression;
import com.jetbrains.python.psi.PyTargetExpression;
import com.jetbrains.python.psi.PyUtil;
import com.jetbrains.python.psi.impl.PyAugAssignmentStatementNavigator;
/**
* @author Dennis.Ushakov
*/
public class PyDefUseUtil
{
private PyDefUseUtil()
{
}
@Nonnull
public static List<Instruction> getLatestDefs(ScopeOwner block, String varName, PsiElement anchor, boolean acceptTypeAssertions, boolean acceptImplicitImports)
{
final ControlFlow controlFlow = ControlFlowCache.getControlFlow(block);
final Instruction[] instructions = controlFlow.getInstructions();
final PyAugAssignmentStatement augAssignment = PyAugAssignmentStatementNavigator.getStatementByTarget(anchor);
if(augAssignment != null)
{
anchor = augAssignment;
}
int instr = ControlFlowUtil.findInstructionNumberByElement(instructions, anchor);
if(instr < 0)
{
return Collections.emptyList();
}
if(anchor instanceof PyTargetExpression)
{
Collection<Instruction> pred = instructions[instr].allPred();
if(!pred.isEmpty())
{
instr = pred.iterator().next().num();
}
}
final Collection<Instruction> result = getLatestDefs(varName, instructions, instr, acceptTypeAssertions, acceptImplicitImports);
return new ArrayList<>(result);
}
private static Collection<Instruction> getLatestDefs(final String varName,
final Instruction[] instructions,
final int instr,
final boolean acceptTypeAssertions,
final boolean acceptImplicitImports)
{
final Collection<Instruction> result = new LinkedHashSet<>();
ControlFlowUtil.iteratePrev(instr, instructions, instruction -> {
final PsiElement element = instruction.getElement();
final PyImplicitImportNameDefiner implicit = PyUtil.as(element, PyImplicitImportNameDefiner.class);
if(instruction instanceof ReadWriteInstruction)
{
final ReadWriteInstruction rwInstruction = (ReadWriteInstruction) instruction;
final ReadWriteInstruction.ACCESS access = rwInstruction.getAccess();
if(access.isWriteAccess() || acceptTypeAssertions && access.isAssertTypeAccess())
{
final String name = elementName(element);
if(Comparing.strEqual(name, varName))
{
result.add(rwInstruction);
return ControlFlowUtil.Operation.CONTINUE;
}
}
}
else if(acceptImplicitImports && implicit != null)
{
if(!implicit.multiResolveName(varName).isEmpty())
{
result.add(instruction);
return ControlFlowUtil.Operation.CONTINUE;
}
}
return ControlFlowUtil.Operation.NEXT;
});
return result;
}
@Nullable
private static String elementName(PsiElement element)
{
if(element instanceof PyImportElement)
{
return ((PyImportElement) element).getVisibleName();
}
if(element instanceof PyReferenceExpression)
{
final QualifiedName qname = ((PyReferenceExpression) element).asQualifiedName();
if(qname != null)
{
return qname.toString();
}
}
return element instanceof PyElement ? ((PyElement) element).getName() : null;
}
@Nonnull
public static PsiElement[] getPostRefs(ScopeOwner block, PyTargetExpression var, PyExpression anchor)
{
final ControlFlow controlFlow = ControlFlowCache.getControlFlow(block);
final Instruction[] instructions = controlFlow.getInstructions();
final int instr = ControlFlowUtil.findInstructionNumberByElement(instructions, anchor);
if(instr < 0)
{
return PyElement.EMPTY_ARRAY;
}
final boolean[] visited = new boolean[instructions.length];
final Collection<PyElement> result = Sets.newHashSet();
for(Instruction instruction : instructions[instr].allSucc())
{
getPostRefs(var, instructions, instruction.num(), visited, result);
}
return result.toArray(new PyElement[result.size()]);
}
private static void getPostRefs(PyTargetExpression var, Instruction[] instructions, int instr, boolean[] visited, Collection<PyElement> result)
{
// TODO: Use ControlFlowUtil.process() for forwards CFG traversal
if(visited[instr])
{
return;
}
visited[instr] = true;
if(instructions[instr] instanceof ReadWriteInstruction)
{
final ReadWriteInstruction instruction = (ReadWriteInstruction) instructions[instr];
final PsiElement element = instruction.getElement();
String name = elementName(element);
if(Comparing.strEqual(name, var.getName()))
{
final ReadWriteInstruction.ACCESS access = instruction.getAccess();
if(access.isWriteAccess())
{
return;
}
result.add((PyElement) instruction.getElement());
}
}
for(Instruction instruction : instructions[instr].allSucc())
{
getPostRefs(var, instructions, instruction.num(), visited, result);
}
}
public static class InstructionNotFoundException extends RuntimeException
{
}
}
|
consulo/consulo-python
|
python-impl/src/main/java/com/jetbrains/python/refactoring/PyDefUseUtil.java
|
Java
|
apache-2.0
| 6,432 |
#!/usr/bin/python
"""postprocess"""
import argparse
import ruamel.yaml
import os
def read(filename):
"""return file contents"""
with open(filename, 'r') as file_in:
return file_in.read()
def write(filename, cwl):
"""write to file"""
with open(filename, 'w') as file_out:
file_out.write(cwl)
def main():
"""main function"""
parser = argparse.ArgumentParser(description='postprocess')
parser.add_argument(
'-f',
action="store",
dest="filename_cwl",
help='Name of the cwl file',
required=True
)
params = parser.parse_args()
dir_path = os.path.dirname(os.path.realpath(__file__))
cwl = ruamel.yaml.load(read(params.filename_cwl),
ruamel.yaml.RoundTripLoader)
script_path = os.path.join(dir_path,'filter_vardict.py')
cwl['baseCommand'] = ['python',script_path]
cwl['inputs']['inputVcf']['type'] = ['string', 'File']
cwl['inputs']['hotspotVcf']['type'] = ['null', 'string', 'File']
write(params.filename_cwl, ruamel.yaml.dump(
cwl, Dumper=ruamel.yaml.RoundTripDumper))
if __name__ == "__main__":
main()
|
rhshah/basicfiltering
|
vardict/postprocess.py
|
Python
|
apache-2.0
| 1,171 |
/*
* Copyright 2017 requery.io
*
* 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.requery.converter;
import io.requery.Converter;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
/**
* Converts from a {@link ZonedDateTime} to a {@link java.sql.Timestamp} for Java 8. Note that
* when converting between the time type and the database type all times will be converted to the
* System default zone offset.
*/
public class ZonedDateTimeConverter implements Converter<ZonedDateTime, Timestamp> {
@Override
public Class<ZonedDateTime> getMappedType() {
return ZonedDateTime.class;
}
@Override
public Class<Timestamp> getPersistedType() {
return Timestamp.class;
}
@Override
public Integer getPersistedSize() {
return null;
}
@Override
public Timestamp convertToPersisted(ZonedDateTime value) {
if (value == null) {
return null;
}
Instant instant = value.toInstant();
return Timestamp.from(instant);
}
@Override
public ZonedDateTime convertToMapped(Class<? extends ZonedDateTime> type, Timestamp value) {
if (value == null) {
return null;
}
Instant instant = value.toInstant();
return ZonedDateTime.ofInstant(instant, ZoneOffset.systemDefault());
}
}
|
requery/requery
|
requery/src/main/java/io/requery/converter/ZonedDateTimeConverter.java
|
Java
|
apache-2.0
| 1,918 |
package com.codeboy.hadoop.wordcount.progressable;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
/***
* take a simple test and split by token
* @author codeboyyong
*
*/
public class SlowWCTokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
Thread.sleep(100); //wait 0.1 seconds
}
}
|
codeboyyong/hadoop-sample
|
wordcount_cli_yarn/src/main/java/com/codeboy/hadoop/wordcount/progressable/SlowWCTokenizerMapper.java
|
Java
|
apache-2.0
| 799 |
/*
* Copyright 2016 TopClouders Hungary Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.topclouders.chessprofile.component;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.Serializable;
/**
* Created by kokeny on 03/04/16.
*/
@Component
public class MailProperties implements Serializable {
@Value("${mail.smtp.user}")
private String userName;
@Value("${mail.smtp.password}")
private char[] password;
@Value("${mail.smtp.url}")
private String url;
@Value("${mail.smtp.port}")
private int port;
public MailProperties(){
super();
}
public String getUserName() {
return userName;
}
public char[] getPassword() {
return password;
}
public String getUrl() {
return url;
}
public int getPort() {
return port;
}
}
|
Gubancs/chess-profile
|
src/main/java/org/topclouders/chessprofile/component/MailProperties.java
|
Java
|
apache-2.0
| 1,441 |
#include <stdio.h>
int main(void)
{
int N, n, cnt;
char tmp;
char big[105][105], small[4][105][105];
while (EOF != scanf("%d %d\n", &N, &n) && N && n) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
scanf(" %c", &big[i][j]);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf(" %c", &tmp);
small[0][i][j] = tmp;
small[1][j][n-1-i] = tmp;
small[2][n-1-i][n-1-j] = tmp;
small[3][n-1-j][i] = tmp;
}
}
/*
for (int i = 0; i < 4; i++)
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++)
printf("%c ", small[i][j][k]);
puts("");
}
*/
int check;
for (int i = 0; i < 4; i++) {
cnt = 0;
for (int j = 0; j <= N-n; j++) {
for (int k = 0; k <= N-n; k++) {
check = 1;
for (int l = 0; l < n; l++) {
for (int m = 0; m < n; m++) {
if (big[j+l][k+m] != small[i][l][m]) {
check = 0;
break;
}
}
if (!check)
break;
}
if (check)
cnt++;
}
}
if (i) printf(" ");
printf("%d", cnt);
}
puts("");
}
return 0;
}
|
geniustanley/problem-solving
|
UVa/10855 - Rotated square.cpp
|
C++
|
apache-2.0
| 1,314 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<title>添加字段</title>
<hdui bootstrap="true"/>
<js file="__GROUP__/static/js/js.js"/>
<css file="__CONTROL_TPL__/css/css.css"/>
<js file="__CONTROL_TPL__/js/js.js"/>
<script type="text/javascript">
var mid = {$mid}
//获得字段模板类型
var tpl_type = "add";
</script>
</head>
<body>
<form action="{|U:'add'}" method="post" onsubmit="return false;" class="form-inline hd-form">
<div class="wrap">
<div class="menu_list">
<ul>
<li><a href="{|U:'Model/Model/index'}">模型列表</a></li>
<li><a href="{|U('index',array('mid'=>$_GET['mid']))}">字段列表</a></li>
<li><a href="javascript:;" class="action">添加字段</a></li>
</ul>
</div>
<div class="table_title">
添加字段
</div>
<input type="hidden" name="mid" value="{$model.mid}"/>
<table class="table1">
<tr>
<td class="w100">模型</td>
<td>
<input type="text" disabled="disabled" value="{$model.model_name}"/>
</td>
</tr>
<tr>
<td>类型</td>
<td>
<select id="field_type" name="show_type">
<option value="input">单行文本</option>
<option value="textarea">多行文本</option>
<option value="number">数字</option>
<option value="select">选项</option>
<option value="editor">编辑器</option>
<option value="image">图片</option>
<option value="images">多图片</option>
<option value="date">日期与时间</option>
</select>
</td>
</tr>
<if value="$model.type==1">
<tr>
<td>表</td>
<td>
<label><input type="radio" name="table_type" value="1"/> 主表</label>
<label><input type="radio" name="table_type" value="2" checked="checked"/> 附表</label>
</td>
</tr>
<else>
<input type="hidden" name="is_main_table" value="1"/>
</if>
<tr>
<td>
字段别名<span class="star">*</span>
</td>
<td>
<input type="text" name="title" class="w200"/>
</td>
</tr>
<tr>
<td>
字段名<span class="star">*</span>
</td>
<td>
<input type="text" name="field_name" class="w200"/>
</td>
</tr>
<tr>
<td>输入提示</td>
<td>
<input type="text" name="set[message]" class="w200"/>
</td>
</tr>
</table>
<div class="field_tpl">
</div>
<table class="table1">
<tr>
<td class="w100">
会员中心显示
</td>
<td>
<label><input type="radio" name="ismember" value="1" checked="checked"/> 是</label>
<label><input type="radio" name="ismember" value="0"/> 否</label>
</td>
</tr>
</table>
</div>
<div class="btn_wrap">
<input type="submit" value="确定" class="btn btn-primary"/>
</div>
</form>
</body>
</html>
|
shizhen0632/hdcms
|
hd/Hdcms/Field/Tpl/Field/add.php
|
PHP
|
apache-2.0
| 3,971 |
#!/usr/bin/env python
import SimpleITK as sitk
import skimage as ski
import skimage.segmentation
import numpy as np
import timeit
def mask_label_contour(image, seg):
"""Combine an image and segmentation by masking the segmentation contour.
For an input image (scalar or vector), and a multi-label
segmentation image, creates an output image where the countour of
each label masks the input image to black."""
return sitk.Mask(image, sitk.LabelContour(seg+1)==0)
# this script generates images to compare ski-image SLIC
# implementaiton vs ours.
# We have slightly different parameterizations. The image is 512x512,
# if we target 256 superpixels of size 32x32 we have simular
# parameters for each implementation.
img=sitk.ReadImage("/home/blowekamp/src/scikit-image/skimage/data/astronaut.png")
aimg_lab=ski.color.rgb2lab(sitk.GetArrayFromImage(img))
ski_slic_aimg=skimage.segmentation.slic(aimg_lab,n_segments=256,convert2lab=False)
sitk.WriteImage(mask_label_contour(img, sitk.GetImageFromArray(ski_slic_aimg))
, "astronaut_ski_slic.png")
print(min(timeit.repeat(lambda: skimage.segmentation.slic(aimg_lab,n_segments=256,convert2lab=False), number=1, repeat=5)))
img_lab = sitk.GetImageFromArray(aimg_lab, isVector=True)
sitk_slic_img=sitk.SLIC(img_lab, [32,32], maximumNumberOfIterations=10)
sitk.WriteImage(mask_label_contour(img, sitk_slic_img), "astronaut_sitk_slic.png")
print(min(timeit.repeat(lambda: sitk.SLIC(img_lab, [32,32], maximumNumberOfIterations=10), number=1, repeat=5)))
|
blowekamp/itkSuperPixel
|
doc/scripts/evaluation_ski.py
|
Python
|
apache-2.0
| 1,526 |
/*
* Copyright 2010 James Pether Sörling
*
* 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.
*
* $Id$
* $HeadURL$
*/
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.02.24 at 11:39:39 PM CET
//
package com.hack23.cia.model.external.worldbank.data.impl;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.hack23.cia.model.common.api.ModelObject;
/**
* The Class DataElement.
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"data"
})
@XmlRootElement(name = "data")
@Entity(name = "DataElement")
@Table(name = "DATA_ELEMENT")
@Inheritance(strategy = InheritanceType.JOINED)
public class DataElement
implements ModelObject
{
/**
*
*/
private static final long serialVersionUID = 1L;
/** The data. */
@XmlElement(required = true)
protected List<WorldBankData> data = new ArrayList<>();
/** The page. */
@XmlAttribute(name = "page")
protected BigInteger page;
/** The pages. */
@XmlAttribute(name = "pages")
protected BigInteger pages;
/** The per page. */
@XmlAttribute(name = "per_page")
protected BigInteger perPage;
/** The total. */
@XmlAttribute(name = "total")
protected BigInteger total;
/** The hjid. */
@XmlAttribute(name = "Hjid")
protected Long hjid;
/**
* Gets the data.
*
* @return the data
*/
@OneToMany(targetEntity = WorldBankData.class, cascade = {
CascadeType.ALL
})
@JoinColumn(name = "DATA__DATA_ELEMENT_HJID")
public List<WorldBankData> getData() {
return this.data;
}
/**
* Sets the data.
*
* @param data the new data
*/
public void setData(final List<WorldBankData> data) {
this.data = data;
}
/**
* Gets the page.
*
* @return the page
*/
@Basic
@Column(name = "PAGE", precision = 20)
public BigInteger getPage() {
return page;
}
/**
* Sets the page.
*
* @param value the new page
*/
public void setPage(final BigInteger value) {
this.page = value;
}
/**
* Gets the pages.
*
* @return the pages
*/
@Basic
@Column(name = "PAGES", precision = 20)
public BigInteger getPages() {
return pages;
}
/**
* Sets the pages.
*
* @param value the new pages
*/
public void setPages(final BigInteger value) {
this.pages = value;
}
/**
* Gets the per page.
*
* @return the per page
*/
@Basic
@Column(name = "PER_PAGE", precision = 20)
public BigInteger getPerPage() {
return perPage;
}
/**
* Sets the per page.
*
* @param value the new per page
*/
public void setPerPage(final BigInteger value) {
this.perPage = value;
}
/**
* Gets the total.
*
* @return the total
*/
@Basic
@Column(name = "TOTAL", precision = 20)
public BigInteger getTotal() {
return total;
}
/**
* Sets the total.
*
* @param value the new total
*/
public void setTotal(final BigInteger value) {
this.total = value;
}
/**
* With data.
*
* @param data the data
* @return the data element
*/
public DataElement withData(final List<WorldBankData> data) {
setData(data);
return this;
}
/**
* With page.
*
* @param value the value
* @return the data element
*/
public DataElement withPage(final BigInteger value) {
setPage(value);
return this;
}
/**
* With pages.
*
* @param value the value
* @return the data element
*/
public DataElement withPages(final BigInteger value) {
setPages(value);
return this;
}
/**
* With per page.
*
* @param value the value
* @return the data element
*/
public DataElement withPerPage(final BigInteger value) {
setPerPage(value);
return this;
}
/**
* With total.
*
* @param value the value
* @return the data element
*/
public DataElement withTotal(final BigInteger value) {
setTotal(value);
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public final String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
/**
* Gets the hjid.
*
* @return the hjid
*/
@Id
@Column(name = "HJID")
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getHjid() {
return hjid;
}
/**
* Sets the hjid.
*
* @param value the new hjid
*/
public void setHjid(final Long value) {
this.hjid = value;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
return new EqualsBuilder().append(getData().toArray(), ((DataElement) obj).getData().toArray()).isEquals();
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public final int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
|
Hack23/cia
|
model.external.worldbank.data.impl/src/main/java/com/hack23/cia/model/external/worldbank/data/impl/DataElement.java
|
Java
|
apache-2.0
| 6,818 |
package com.fasterxml.jackson.databind.util;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
public class EnumResolver<T extends Enum<T>>
implements Serializable
{
private static final long serialVersionUID = 1L;
protected final Class<T> _enumClass;
protected final T[] _enums;
protected final HashMap<String, T> _enumsById;
protected EnumResolver(Class<T> paramClass, T[] paramArrayOfT, HashMap<String, T> paramHashMap)
{
this._enumClass = paramClass;
this._enums = paramArrayOfT;
this._enumsById = paramHashMap;
}
public static <ET extends Enum<ET>> EnumResolver<ET> constructFor(Class<ET> paramClass, AnnotationIntrospector paramAnnotationIntrospector)
{
Enum[] arrayOfEnum = (Enum[])paramClass.getEnumConstants();
if (arrayOfEnum == null)
throw new IllegalArgumentException("No enum constants for class " + paramClass.getName());
HashMap localHashMap = new HashMap();
int i = arrayOfEnum.length;
for (int j = 0; j < i; j++)
{
Enum localEnum = arrayOfEnum[j];
localHashMap.put(paramAnnotationIntrospector.findEnumValue(localEnum), localEnum);
}
return new EnumResolver(paramClass, arrayOfEnum, localHashMap);
}
public static EnumResolver<?> constructUnsafe(Class<?> paramClass, AnnotationIntrospector paramAnnotationIntrospector)
{
return constructFor(paramClass, paramAnnotationIntrospector);
}
public static EnumResolver<?> constructUnsafeUsingMethod(Class<?> paramClass, Method paramMethod)
{
return constructUsingMethod(paramClass, paramMethod);
}
public static EnumResolver<?> constructUnsafeUsingToString(Class<?> paramClass)
{
return constructUsingToString(paramClass);
}
public static <ET extends Enum<ET>> EnumResolver<ET> constructUsingMethod(Class<ET> paramClass, Method paramMethod)
{
Enum[] arrayOfEnum = (Enum[])paramClass.getEnumConstants();
HashMap localHashMap = new HashMap();
int i = arrayOfEnum.length;
while (true)
{
i--;
if (i >= 0)
{
Enum localEnum = arrayOfEnum[i];
try
{
Object localObject = paramMethod.invoke(localEnum, new Object[0]);
if (localObject != null)
localHashMap.put(localObject.toString(), localEnum);
}
catch (Exception localException)
{
throw new IllegalArgumentException("Failed to access @JsonValue of Enum value " + localEnum + ": " + localException.getMessage());
}
}
}
return new EnumResolver(paramClass, arrayOfEnum, localHashMap);
}
public static <ET extends Enum<ET>> EnumResolver<ET> constructUsingToString(Class<ET> paramClass)
{
Enum[] arrayOfEnum = (Enum[])paramClass.getEnumConstants();
HashMap localHashMap = new HashMap();
int i = arrayOfEnum.length;
while (true)
{
i--;
if (i < 0)
break;
Enum localEnum = arrayOfEnum[i];
localHashMap.put(localEnum.toString(), localEnum);
}
return new EnumResolver(paramClass, arrayOfEnum, localHashMap);
}
public T findEnum(String paramString)
{
return (Enum)this._enumsById.get(paramString);
}
public T getEnum(int paramInt)
{
if ((paramInt < 0) || (paramInt >= this._enums.length))
return null;
return this._enums[paramInt];
}
public Class<T> getEnumClass()
{
return this._enumClass;
}
public int lastValidIndex()
{
return -1 + this._enums.length;
}
}
/* Location: /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
* Qualified Name: com.fasterxml.jackson.databind.util.EnumResolver
* JD-Core Version: 0.6.2
*/
|
mmmsplay10/QuizUpWinner
|
quizup/com/fasterxml/jackson/databind/util/EnumResolver.java
|
Java
|
apache-2.0
| 3,736 |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using MOE.Common.Business.Bins;
using MOE.Common.Business.DataAggregation;
using MOE.Common.Models;
namespace MOE.Common.Business.WCFServiceLibrary
{
[DataContract]
public class ApproachYellowRedActivationsAggregationOptions : ApproachAggregationMetricOptions
{
public ApproachYellowRedActivationsAggregationOptions()
{
MetricTypeID = 20;
AggregatedDataTypes = new List<AggregatedDataType>();
AggregatedDataTypes.Add(new AggregatedDataType {Id = 0, DataName = "SevereRedLightViolations" });
AggregatedDataTypes.Add(new AggregatedDataType {Id = 1, DataName = "TotalRedLightViolations" });
}
public override string ChartTitle
{
get
{
string chartTitle;
chartTitle = "AggregationChart\n";
chartTitle += TimeOptions.Start.ToString();
if (TimeOptions.End > TimeOptions.Start)
chartTitle += " to " + TimeOptions.End + "\n";
if (TimeOptions.DaysOfWeek != null)
foreach (var dayOfWeek in TimeOptions.DaysOfWeek)
chartTitle += dayOfWeek + " ";
if (TimeOptions.TimeOfDayStartHour != null && TimeOptions.TimeOfDayStartMinute != null &&
TimeOptions.TimeOfDayEndHour != null && TimeOptions.TimeOfDayEndMinute != null)
chartTitle += "Limited to: " +
new TimeSpan(0, TimeOptions.TimeOfDayStartHour.Value,
TimeOptions.TimeOfDayStartMinute.Value, 0) + " to " + new TimeSpan(0,
TimeOptions.TimeOfDayEndHour.Value,
TimeOptions.TimeOfDayEndMinute.Value, 0) + "\n";
chartTitle += TimeOptions.SelectedBinSize + " bins ";
chartTitle += SelectedXAxisType + " Aggregation ";
chartTitle += SelectedAggregationType.ToString();
return chartTitle;
}
}
public override string YAxisTitle => SelectedAggregationType + " of " + Regex.Replace(
SelectedAggregatedDataType.DataName,
@"(\B[A-Z]+?(?=[A-Z][^A-Z])|\B[A-Z]+?(?=[^A-Z]))", " $1") + " " +
TimeOptions.SelectedBinSize + " bins";
protected override int GetAverageByPhaseNumber(Models.Signal signal, int phaseNumber)
{
var splitFailAggregationBySignal =
new YellowRedActivationsAggregationBySignal(this, signal);
return splitFailAggregationBySignal.Average;
}
protected override double GetSumByPhaseNumber(Models.Signal signal, int phaseNumber)
{
var splitFailAggregationBySignal =
new YellowRedActivationsAggregationBySignal(this, signal);
return splitFailAggregationBySignal.Average;
}
protected override int GetAverageByDirection(Models.Signal signal, DirectionType direction)
{
var splitFailAggregationBySignal =
new YellowRedActivationsAggregationBySignal(this, signal, direction);
return splitFailAggregationBySignal.Average;
}
protected override double GetSumByDirection(Models.Signal signal, DirectionType direction)
{
var yellowRedActivationsAggregationBySignal =
new YellowRedActivationsAggregationBySignal(this, signal, direction);
return yellowRedActivationsAggregationBySignal.Average;
}
protected override List<BinsContainer> GetBinsContainersBySignal(Models.Signal signal)
{
var yellowRedActivationsAggregationBySignal = new YellowRedActivationsAggregationBySignal(this, signal);
return yellowRedActivationsAggregationBySignal.BinsContainers;
}
protected override List<BinsContainer> GetBinsContainersByDirection(DirectionType directionType,
Models.Signal signal)
{
var splitFailAggregationBySignal =
new YellowRedActivationsAggregationBySignal(this, signal, directionType);
return splitFailAggregationBySignal.BinsContainers;
}
protected override List<BinsContainer> GetBinsContainersByPhaseNumber(Models.Signal signal, int phaseNumber)
{
var splitFailAggregationBySignal =
new YellowRedActivationsAggregationBySignal(this, signal, phaseNumber);
return splitFailAggregationBySignal.BinsContainers;
}
public override List<BinsContainer> GetBinsContainersByRoute(List<Models.Signal> signals)
{
var aggregations = new ConcurrentBag<YellowRedActivationsAggregationBySignal>();
Parallel.ForEach(signals,
signal => { aggregations.Add(new YellowRedActivationsAggregationBySignal(this, signal)); });
var binsContainers = BinFactory.GetBins(TimeOptions);
foreach (var splitFailAggregationBySignal in aggregations)
for (var i = 0; i < binsContainers.Count; i++)
for (var binIndex = 0; binIndex < binsContainers[i].Bins.Count; binIndex++)
{
var bin = binsContainers[i].Bins[binIndex];
bin.Sum += splitFailAggregationBySignal.BinsContainers[i].Bins[binIndex].Sum;
bin.Average = Convert.ToInt32(Math.Round((double) (bin.Sum / signals.Count)));
}
return binsContainers;
}
protected override List<BinsContainer> GetBinsContainersByApproach(Approach approach, bool getprotectedPhase)
{
var approachYellowRedActivationsAggregationContainer = new YellowRedActivationsAggregationByApproach(
approach, this, StartDate, EndDate,
getprotectedPhase, SelectedAggregatedDataType);
return approachYellowRedActivationsAggregationContainer.BinsContainers;
}
}
}
|
udotdevelopment/ATSPM
|
MOE.Common/Business/WCFServiceLibrary/ApproachYellowRedActivationsAggregationOptions.cs
|
C#
|
apache-2.0
| 6,335 |
<?php
namespace app\modules\pages\controllers;
use Yii;
use app\modules\app\controllers\AppController;
class DefaultController extends AppController
{
public function actionIndex()
{
return $this->render('index');
}
}
|
FrenzelGmbH/company-website
|
modules/pages/controllers/DefaultController.php
|
PHP
|
apache-2.0
| 226 |
/**
* Created by king on 15-5-20.
*
* ch10.net_maxconnections_clientB.js
*/
console.info("------ net getconnections() ------");
console.info();
var net = require("net"); // TODO: 引入网络(Net)模块
var HOST = '127.0.0.1'; // TODO: 定义服务器地址
var PORT = 8877; // TODO: 定义端口号
/**
* 使用net.connect()函数方法创建一个TCP客户端实例
*/
var client = net.connect(PORT, HOST, function() {
console.log('client B connected');
console.info();
client.write('client write : Hello Server!');
//client.end();
});
/**
* 为TCP客户端实例添加一个"end"事件处理函数
*/
client.on('end', function() {
console.log('clientB disconnected');
console.info();
});
|
0end1/code_base
|
Node.js_Codebase/chapter10/ServerMaxConnections/ch10.net_maxconnections_clientB.js
|
JavaScript
|
apache-2.0
| 743 |
/*
*
* 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.flex.compiler.internal.as.codegen;
import org.apache.flex.abc.ABCConstants;
import org.apache.flex.abc.instructionlist.InstructionList;
import org.apache.flex.abc.semantics.MethodInfo;
import org.apache.flex.abc.semantics.Name;
import org.apache.flex.abc.visitors.IABCVisitor;
import org.apache.flex.abc.visitors.IClassVisitor;
import org.apache.flex.abc.visitors.ITraitVisitor;
import org.apache.flex.abc.visitors.ITraitsVisitor;
import org.apache.flex.compiler.common.DependencyType;
import org.apache.flex.compiler.definitions.IDefinition;
import org.apache.flex.compiler.internal.definitions.ClassDefinition;
import org.apache.flex.compiler.internal.definitions.FunctionDefinition;
import org.apache.flex.compiler.internal.scopes.ASScope;
import org.apache.flex.compiler.internal.tree.as.ClassNode;
import org.apache.flex.compiler.internal.tree.as.FunctionNode;
import org.apache.flex.compiler.internal.tree.as.ImportNode;
import org.apache.flex.compiler.internal.tree.as.InterfaceNode;
import org.apache.flex.compiler.internal.tree.as.PackageNode;
import org.apache.flex.compiler.internal.tree.as.VariableNode;
import org.apache.flex.compiler.problems.DuplicateFunctionDefinitionProblem;
import org.apache.flex.compiler.problems.ICompilerProblem;
import org.apache.flex.compiler.scopes.IASScope;
import org.apache.flex.compiler.tree.ASTNodeID;
import org.apache.flex.compiler.tree.as.IASNode;
import org.apache.flex.compiler.tree.mxml.IMXMLDocumentNode;
/**
* A GlobalDirectiveProcessor translates directives at global scope into ABC.
* JSGlobalDirectiveProcessor is derived from GlobalDirectiveProcessor and adds
* workarounds necessary for FalconJS. Ideally FalconJS should use
* GlobalDirectiveProcessor and retire JSGlobalDirectiveProcessor. This
* implementation is part of FalconJS. For more details on FalconJS see
* org.apache.flex.compiler.JSDriver
*/
public class JSGlobalDirectiveProcessor extends GlobalDirectiveProcessor
{
JSGenerator m_generator;
private String m_packageName = null;
/**
* @param current_scope - the scope to use. It may be created a priori by
* the caller, so it's not created by nesting an enclosing scope.
* @param emitter - the ABC emitter.
*/
public JSGlobalDirectiveProcessor(JSGenerator generator, LexicalScope current_scope, IABCVisitor emitter)
{
super(current_scope, emitter);
m_generator = generator;
}
@Override
void declareFunction(FunctionNode f)
{
// No modifiers allowed at global scope.
// super.verifyModifiers(f);
// MISSING in GlobalDirectiveProcessor
MethodInfo mi = m_generator.generateFunction(f, currentScope, null);
if (mi != null)
{
FunctionDefinition funcDef = f.getDefinition();
JSSharedData.instance.registerDefinition(funcDef);
// TODO: generalize excluding functions using metadata annotations.
final String packageName = funcDef.getPackageName();
if (!packageName.equals("com.jquery"))
{
final IClassVisitor cv = ((JSEmitter)emitter).visitPackage(m_packageName);
cv.visit();
this.currentScope.traitsVisitor = cv.visitClassTraits();
cv.visitEnd();
/*
* InstanceInfo iinfo = new InstanceInfo(); iinfo.name =
* JSGeneratingReducer.makeName(packageName); IClassVisitor cv =
* emitter.visitClass(iinfo, new ClassInfo()); cv.visit();
* cv.visitInstanceTraits(); ITraitsVisitor ctraits =
* cv.visitClassTraits(); final Name funcName =
* funcDef.getMName(currentScope.getProject(),
* currentScope.getProblems()); final ITraitVisitor tv =
* ctraits.visitMethodTrait(TRAIT_Method, funcName, 0, mi);
* tv.visitAttribute(Trait.TRAIT_FINAL, Boolean.TRUE);
*/
/*
* final String key = packageName; ICompilationUnit cu =
* m_generator.m_compilationUnit; ICompilationUnit registeredCU
* = JSSharedData.instance.getCompilationUnit(key); if( cu !=
* registeredCU ) { // make the current cu dependent on the
* registered cu. if( registeredCU != null ) { final
* CompilerProject compilerProject =
* (CompilerProject)cu.getProject();
* compilerProject.addDependency(cu, registeredCU,
* DependencyType.INHERITANCE); } else {
* JSSharedData.instance.registerCompilationUnit(key, cu); } }
*/
}
Name funcName = funcDef.getMName(this.currentScope.getProject());
if (funcName == null)
{
// getMName() emitted a diagnostic,
// repair and continue.
funcName = new Name("<invalid>");
}
ITraitVisitor tv = null;
int traitKind = this.processingPackage ?
DirectiveProcessor.functionTraitKind(f, ABCConstants.TRAIT_Method) :
DirectiveProcessor.functionTraitKind(f, ABCConstants.TRAIT_Var);
if (!this.currentScope.traitsVisitor.getTraits().containsTrait(traitKind, funcName))
{
this.currentScope.declareVariableName(funcName);
if (!this.processingPackage)
{
// Functions at the global scope create a var of type '*'
// TODO: this should be typed as 'Function' if strict mode is on
if (f.isGetter() || f.isSetter())
{
tv = this.currentScope.traitsVisitor.visitMethodTrait(
DirectiveProcessor.functionTraitKind(f, ABCConstants.TRAIT_Var),
funcName,
ITraitsVisitor.RUNTIME_DISP_ID,
mi);
}
else
{
tv = this.currentScope.traitsVisitor.visitSlotTrait(
DirectiveProcessor.functionTraitKind(f, ABCConstants.TRAIT_Var),
funcName,
ITraitsVisitor.RUNTIME_SLOT,
LexicalScope.anyType,
LexicalScope.noInitializer);
/*
* this.currentScope.getInitInstructions().addInstruction
* (ABCConstants.OP_getglobalscope);
* this.currentScope.getInitInstructions
* ().addInstruction(ABCConstants.OP_newfunction, mi);
* this
* .currentScope.getInitInstructions().addInstruction
* (ABCConstants.OP_setproperty, funcName);
*/
}
}
else
{
tv = this.currentScope.traitsVisitor.visitMethodTrait(DirectiveProcessor.functionTraitKind(f, ABCConstants.TRAIT_Method), funcName, 0, mi);
}
if (tv != null)
{
this.currentScope.processMetadata(tv, funcDef.getAllMetaTags());
}
}
else
{
ICompilerProblem problem = new DuplicateFunctionDefinitionProblem(f, funcName.getBaseName());
this.currentScope.addProblem(problem);
}
}
}
/**
* Declare a class.
*/
@Override
void declareClass(ClassNode c)
{
verifyClassModifiers(c);
verifySkinning(c.getDefinition());
currentScope.getMethodBodySemanticChecker().checkNamespaceOfDefinition(c, c.getDefinition(), currentScope.getProject());
JSClassDirectiveProcessor cp = JSSharedData.backend.createClassDirectiveProcessor(m_generator, c, this.currentScope, this.emitter);
cp.traverse(c.getScopedNode());
cp.finishClassDefinition();
}
/**
* Declare an interface.
*/
@Override
void declareInterface(InterfaceNode interface_ast)
{
verifyInterfaceModifiers(interface_ast);
currentScope.getMethodBodySemanticChecker().checkNamespaceOfDefinition(interface_ast, interface_ast.getDefinition(), currentScope.getProject());
InterfaceDirectiveProcessor ip = JSSharedData.backend.createInterfaceDirectiveProcessor(m_generator, interface_ast, this.currentScope, this.emitter);
ip.traverse(interface_ast.getScopedNode());
ip.finishInterfaceDefinition();
}
/**
* Process a random directive, which at the global level is probably a loose
* instruction.
*/
@Override
void processDirective(IASNode n)
{
// Use nodes have no effect
/*
* if(n.getNodeID() == ASTNodeID.UseID ) { if(
* !JSSharedData.GENERATE_EMBED_WRAPPER ) return; }
*/
// workaround for Falcon bug.
// DirectiveProcessor is observing NamespaceIdentifierID instead of NamespaceID
if (n.getNodeID() == ASTNodeID.NamespaceID)
{
try
{
final IClassVisitor cv = ((JSEmitter)emitter).visitPackage(m_packageName);
cv.visit();
this.currentScope.traitsVisitor = cv.visitClassTraits();
cv.visitEnd();
m_generator.generateInstructions(n, CmcEmitter.__statement_NT, this.currentScope);
// assert(stmt_insns == null);
}
finally
{
// this.currentScope.traitsVisitor = null;
}
return;
}
// Handle a loose statement.
InstructionList stmt_insns = m_generator.generateInstructions(n, CmcJSEmitter.__statement_NT, currentScope);
if (stmt_insns != null)
directiveInsns.addAll(stmt_insns);
}
@Override
void declarePackage(PackageNode p)
{
m_packageName = p.getName();
((JSEmitter)emitter).visitPackage(m_packageName);
JSSharedData.instance.registerPackage(m_packageName);
super.declarePackage(p);
}
/**
* Declare a variable.
*/
@Override
void declareVariable(VariableNode var)
{
super.declareVariable(var);
}
/**
* Translate a ImportNode AST into ABC. Subclasses should override this if
* they can process imports.
*
* @param imp - the import's AST.
*/
@Override
void processImportDirective(ImportNode imp)
{
String importName = imp.getImportName();
if (!importName.contains("."))
{
final IASScope scope = JSGeneratingReducer.getScopeFromNode(imp);
final IDefinition def = ((ASScope)scope).findProperty(currentScope.getProject(), imp.getImportName(), DependencyType.INHERITANCE);
if (def == null)
{
importName = null;
}
else
{
// workaround for Falcon bug.
// Falcon does not always recognize dependencies to package functions provided by SWCs.
// In this workaround we explicitly set a EXPRESSION dependency.
/*
* if( def != null ) { final ICompilationUnit fromCU =
* m_generator.m_compilationUnit; final CompilerProject
* compilerProject = (CompilerProject)currentScope.project;
* final ASProjectScope projectScope =
* compilerProject.getScope(); final ICompilationUnit toCU =
* projectScope.getCompilationUnitForDefinition(def); if( fromCU
* != toCU ) { // sharedData.verboseMessage(
* "Adding dependency: " + className );
* compilerProject.addDependency(fromCU, toCU,
* DependencyGraph.DependencyType.EXPRESSION); } }
*/
// skip imports from the same package.
if (def.getPackageName().equals(m_packageName))
importName = null;
else
importName = JSGeneratingReducer.definitionToString(currentScope.getProject(), def);
}
}
if (importName != null)
{
JSEmitter emitter = (JSEmitter)this.currentScope.getEmitter();
emitter.visitImport(importName, imp.getImportKind());
}
}
/**
* Declare an MXML document.
*/
@Override
void declareMXMLDocument(IMXMLDocumentNode d)
{
verifySkinning((ClassDefinition)d.getDefinition());
try
{
MXMLClassDirectiveProcessor dp;
dp = new JSMXMLClassDirectiveProcessor(d, this.currentScope, this.emitter);
dp.processMainClassDefinitionNode(d);
dp.finishClassDefinition();
}
catch (Error e)
{
System.out.print(e);
}
}
}
|
adufilie/flex-falcon
|
compiler.js/src/org/apache/flex/compiler/internal/as/codegen/JSGlobalDirectiveProcessor.java
|
Java
|
apache-2.0
| 14,034 |
package myapp;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ThymeleafTemplateTestServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
resp.getWriter().println("<!DOCTYPE html>");
resp.getWriter().println(
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:th=\"http://www.thymeleaf.org\">");
resp.getWriter().println("<head>");
resp.getWriter().println("<meta charset=\"UTF-8\">");
resp.getWriter().println("</head>");
resp.getWriter().println("<body>");
resp.getWriter().println("<div th:fragment=\"datetime\">" + new Date().toString() + "</div>");
resp.getWriter().println("</body>");
resp.getWriter().println("</html>");
}
}
|
dsanoster/thymeleaf-template-test
|
src/main/java/myapp/ThymeleafTemplateTestServlet.java
|
Java
|
apache-2.0
| 947 |
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor
#
# 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.
""" Contains the logic for `aq add interface --network_device`."""
from aquilon.exceptions_ import ArgumentError
from aquilon.aqdb.model import NetworkDevice
from aquilon.worker.broker import BrokerCommand
from aquilon.worker.dbwrappers.interface import (get_or_create_interface,
check_netdev_iftype)
from aquilon.worker.processes import DSDBRunner
class CommandAddInterfaceNetworkDevice(BrokerCommand):
requires_plenaries = True
required_parameters = ["interface", "network_device", "iftype"]
invalid_parameters = ["automac", "pg", "autopg", "model", "vendor",
"bus_address"]
def render(self, session, logger, plenaries, interface, network_device,
mac, iftype, comments, **arguments):
for arg in self.invalid_parameters:
if arguments.get(arg) is not None:
raise ArgumentError("Cannot use argument --%s when adding an "
"interface to a network device." % arg)
check_netdev_iftype(iftype)
dbnetdev = NetworkDevice.get_unique(session, network_device, compel=True)
oldinfo = DSDBRunner.snapshot_hw(dbnetdev)
get_or_create_interface(session, dbnetdev, name=interface, mac=mac,
interface_type=iftype, comments=comments,
preclude=True)
session.flush()
plenaries.add(dbnetdev)
plenaries.add(dbnetdev.host)
with plenaries.transaction():
dsdb_runner = DSDBRunner(logger=logger)
dsdb_runner.update_host(dbnetdev, oldinfo)
dsdb_runner.commit_or_rollback("Could not update network device in DSDB")
return
|
guillaume-philippon/aquilon
|
lib/aquilon/worker/commands/add_interface_network_device.py
|
Python
|
apache-2.0
| 2,483 |
# -*- coding: utf-8 -*-
#
# 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.
from typing import Iterable
from airflow.models import BaseOperator
from airflow.providers.amazon.aws.hooks.s3 import S3Hook
from airflow.utils.decorators import apply_defaults
class S3ListOperator(BaseOperator):
"""
List all objects from the bucket with the given string prefix in name.
This operator returns a python list with the name of objects which can be
used by `xcom` in the downstream task.
:param bucket: The S3 bucket where to find the objects. (templated)
:type bucket: str
:param prefix: Prefix string to filters the objects whose name begin with
such prefix. (templated)
:type prefix: str
:param delimiter: the delimiter marks key hierarchy. (templated)
:type delimiter: str
:param aws_conn_id: The connection ID to use when connecting to S3 storage.
:type aws_conn_id: str
:param verify: Whether or not to verify SSL certificates for S3 connection.
By default SSL certificates are verified.
You can provide the following values:
- ``False``: do not validate SSL certificates. SSL will still be used
(unless use_ssl is False), but SSL certificates will not be
verified.
- ``path/to/cert/bundle.pem``: A filename of the CA cert bundle to uses.
You can specify this argument if you want to use a different
CA cert bundle than the one used by botocore.
:type verify: bool or str
**Example**:
The following operator would list all the files
(excluding subfolders) from the S3
``customers/2018/04/`` key in the ``data`` bucket. ::
s3_file = S3ListOperator(
task_id='list_3s_files',
bucket='data',
prefix='customers/2018/04/',
delimiter='/',
aws_conn_id='aws_customers_conn'
)
"""
template_fields = ('bucket', 'prefix', 'delimiter') # type: Iterable[str]
ui_color = '#ffd700'
@apply_defaults
def __init__(self,
bucket,
prefix='',
delimiter='',
aws_conn_id='aws_default',
verify=None,
*args,
**kwargs):
super().__init__(*args, **kwargs)
self.bucket = bucket
self.prefix = prefix
self.delimiter = delimiter
self.aws_conn_id = aws_conn_id
self.verify = verify
def execute(self, context):
hook = S3Hook(aws_conn_id=self.aws_conn_id, verify=self.verify)
self.log.info(
'Getting the list of files from bucket: %s in prefix: %s (Delimiter {%s)',
self.bucket, self.prefix, self.delimiter
)
return hook.list_keys(
bucket_name=self.bucket,
prefix=self.prefix,
delimiter=self.delimiter)
|
Fokko/incubator-airflow
|
airflow/contrib/operators/s3_list_operator.py
|
Python
|
apache-2.0
| 3,690 |
package gex.newsml.g2;
import lombok.ToString;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;
import org.w3c.dom.Element;
/**
* The type for geographic coordinates (Type defined in this XML Schema only)
*
* <p>
* Java class for GeoCoordinatesType complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType name="GeoCoordinatesType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attGroup ref="{http://iptc.org/std/nar/2006-10-01/}commonPowerAttributes"/>
* <attribute name="latitude" use="required" type="{http://www.w3.org/2001/XMLSchema}decimal" />
* <attribute name="longitude" use="required" type="{http://www.w3.org/2001/XMLSchema}decimal" />
* <attribute name="altitude" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="gpsdatum" type="{http://www.w3.org/2001/XMLSchema}string" />
* <anyAttribute processContents='lax' namespace='##other'/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GeoCoordinatesType", propOrder = { "any" })
@ToString
public class GeoCoordinatesType {
@XmlAnyElement(lax = true)
protected List<Object> any;
@XmlAttribute(name = "latitude", required = true)
protected BigDecimal latitude;
@XmlAttribute(name = "longitude", required = true)
protected BigDecimal longitude;
@XmlAttribute(name = "altitude")
protected BigInteger altitude;
@XmlAttribute(name = "gpsdatum")
protected String gpsdatum;
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
@XmlAttribute(name = "creator")
protected String creator;
@XmlAttribute(name = "creatoruri")
protected String creatoruri;
@XmlAttribute(name = "modified")
protected String modified;
@XmlAttribute(name = "custom")
protected Boolean custom;
@XmlAttribute(name = "how")
protected String how;
@XmlAttribute(name = "howuri")
protected String howuri;
@XmlAttribute(name = "why")
protected String why;
@XmlAttribute(name = "whyuri")
protected String whyuri;
@XmlAttribute(name = "pubconstraint")
protected List<String> pubconstraint;
@XmlAttribute(name = "pubconstrainturi")
protected List<String> pubconstrainturi;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
* Gets the value of the any property.
*
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the any property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getAny().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list {@link Object }
* {@link Element }
*
*
*/
public List<Object> getAny() {
if (any == null) {
any = new ArrayList<Object>();
}
return this.any;
}
/**
* Gets the value of the latitude property.
*
* @return possible object is {@link BigDecimal }
*
*/
public BigDecimal getLatitude() {
return latitude;
}
/**
* Sets the value of the latitude property.
*
* @param value
* allowed object is {@link BigDecimal }
*
*/
public void setLatitude(BigDecimal value) {
this.latitude = value;
}
/**
* Gets the value of the longitude property.
*
* @return possible object is {@link BigDecimal }
*
*/
public BigDecimal getLongitude() {
return longitude;
}
/**
* Sets the value of the longitude property.
*
* @param value
* allowed object is {@link BigDecimal }
*
*/
public void setLongitude(BigDecimal value) {
this.longitude = value;
}
/**
* Gets the value of the altitude property.
*
* @return possible object is {@link BigInteger }
*
*/
public BigInteger getAltitude() {
return altitude;
}
/**
* Sets the value of the altitude property.
*
* @param value
* allowed object is {@link BigInteger }
*
*/
public void setAltitude(BigInteger value) {
this.altitude = value;
}
/**
* Gets the value of the gpsdatum property.
*
* @return possible object is {@link String }
*
*/
public String getGpsdatum() {
return gpsdatum;
}
/**
* Sets the value of the gpsdatum property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setGpsdatum(String value) {
this.gpsdatum = value;
}
/**
* Gets the value of the id property.
*
* @return possible object is {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the creator property.
*
* @return possible object is {@link String }
*
*/
public String getCreator() {
return creator;
}
/**
* Sets the value of the creator property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setCreator(String value) {
this.creator = value;
}
/**
* Gets the value of the creatoruri property.
*
* @return possible object is {@link String }
*
*/
public String getCreatoruri() {
return creatoruri;
}
/**
* Sets the value of the creatoruri property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setCreatoruri(String value) {
this.creatoruri = value;
}
/**
* Gets the value of the modified property.
*
* @return possible object is {@link String }
*
*/
public String getModified() {
return modified;
}
/**
* Sets the value of the modified property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setModified(String value) {
this.modified = value;
}
/**
* Gets the value of the custom property.
*
* @return possible object is {@link Boolean }
*
*/
public Boolean isCustom() {
return custom;
}
/**
* Sets the value of the custom property.
*
* @param value
* allowed object is {@link Boolean }
*
*/
public void setCustom(Boolean value) {
this.custom = value;
}
/**
* Gets the value of the how property.
*
* @return possible object is {@link String }
*
*/
public String getHow() {
return how;
}
/**
* Sets the value of the how property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setHow(String value) {
this.how = value;
}
/**
* Gets the value of the howuri property.
*
* @return possible object is {@link String }
*
*/
public String getHowuri() {
return howuri;
}
/**
* Sets the value of the howuri property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setHowuri(String value) {
this.howuri = value;
}
/**
* Gets the value of the why property.
*
* @return possible object is {@link String }
*
*/
public String getWhy() {
return why;
}
/**
* Sets the value of the why property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setWhy(String value) {
this.why = value;
}
/**
* Gets the value of the whyuri property.
*
* @return possible object is {@link String }
*
*/
public String getWhyuri() {
return whyuri;
}
/**
* Sets the value of the whyuri property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setWhyuri(String value) {
this.whyuri = value;
}
/**
* Gets the value of the pubconstraint property.
*
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the pubconstraint property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getPubconstraint().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list {@link String }
*
*
*/
public List<String> getPubconstraint() {
if (pubconstraint == null) {
pubconstraint = new ArrayList<String>();
}
return this.pubconstraint;
}
/**
* Gets the value of the pubconstrainturi property.
*
* <p>
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the pubconstrainturi property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getPubconstrainturi().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list {@link String }
*
*
*/
public List<String> getPubconstrainturi() {
if (pubconstrainturi == null) {
pubconstrainturi = new ArrayList<String>();
}
return this.pubconstrainturi;
}
/**
* Gets a map that contains attributes that aren't bound to any typed
* property on this class.
*
* <p>
* the map is keyed by the name of the attribute and the value is the string
* value of the attribute.
*
* the map returned by this method is live, and you can add new attribute by
* updating the map directly. Because of this design, there's no setter.
*
*
* @return always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
}
|
gextech/iptc-newsml
|
src/main/java/gex/newsml/g2/GeoCoordinatesType.java
|
Java
|
apache-2.0
| 10,700 |
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2014 Bo Zimmerman
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.
*/
@SuppressWarnings("rawtypes")
public class Spell_MarkerPortal extends Spell
{
@Override public String ID() { return "Spell_MarkerPortal"; }
private final static String localizedName = CMLib.lang()._("Marker Portal");
@Override public String name() { return localizedName; }
@Override protected int canTargetCode(){return 0;}
@Override public int classificationCode(){return Ability.ACODE_SPELL|Ability.DOMAIN_CONJURATION;}
@Override public long flags(){return Ability.FLAG_TRANSPORTING;}
@Override public int abstractQuality(){ return Ability.QUALITY_INDIFFERENT;}
Room newRoom=null;
Room oldRoom=null;
@Override
public void unInvoke()
{
if(canBeUninvoked())
{
if(newRoom!=null)
{
newRoom.showHappens(CMMsg.MSG_OK_VISUAL,_("The swirling portal closes."));
newRoom.rawDoors()[Directions.GATE]=null;
newRoom.setRawExit(Directions.GATE,null);
}
if(oldRoom!=null)
{
oldRoom.showHappens(CMMsg.MSG_OK_VISUAL,_("The swirling portal closes."));
oldRoom.rawDoors()[Directions.GATE]=null;
oldRoom.setRawExit(Directions.GATE,null);
}
}
super.unInvoke();
}
@Override
public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
{
newRoom=null;
oldRoom=null;
try
{
for(final Enumeration r=CMLib.map().rooms();r.hasMoreElements();)
{
final Room R=(Room)r.nextElement();
if(CMLib.flags().canAccess(mob,R))
for(final Enumeration<Ability> a=R.effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)
&&(A.ID().equals("Spell_SummonMarker"))
&&(A.invoker()==mob))
{
newRoom=R;
break;
}
}
if(newRoom!=null) break;
}
}catch(final NoSuchElementException nse){}
if(newRoom==null)
{
mob.tell(_("You can't seem to focus on your marker. Are you sure you've already summoned it?"));
return false;
}
oldRoom=mob.location();
if(oldRoom==newRoom)
{
mob.tell(_("But your marker is HERE!"));
return false;
}
if((oldRoom.getRoomInDir(Directions.GATE)!=null)
||(oldRoom.getExitInDir(Directions.GATE)!=null))
{
mob.tell(_("A portal cannot be created here."));
return false;
}
int profNeg=0;
for(int i=0;i<newRoom.numInhabitants();i++)
{
final MOB t=newRoom.fetchInhabitant(i);
if(t!=null)
{
int adjustment=t.phyStats().level()-(mob.phyStats().level()+(2*getXLEVELLevel(mob)));
if(t.isMonster()) adjustment=adjustment*3;
profNeg+=adjustment;
}
}
profNeg+=newRoom.numItems()*20;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,-profNeg,auto);
if((success)
&&((newRoom.getRoomInDir(Directions.GATE)==null)
&&(newRoom.getExitInDir(Directions.GATE)==null)))
{
final CMMsg msg=CMClass.getMsg(mob,oldRoom,this,verbalCastCode(mob,oldRoom,auto),_("^S<S-NAME> conjur(s) a blinding, swirling portal here.^?"));
final CMMsg msg2=CMClass.getMsg(mob,newRoom,this,verbalCastCode(mob,newRoom,auto),_("A blinding, swirling portal appears here."));
if((oldRoom.okMessage(mob,msg))&&(newRoom.okMessage(mob,msg2)))
{
oldRoom.send(mob,msg);
newRoom.send(mob,msg2);
final Exit e=CMClass.getExit("GenExit");
e.setDescription(_("A swirling portal to somewhere"));
e.setDisplayText(_("A swirling portal to somewhere"));
e.setDoorsNLocks(false,true,false,false,false,false);
e.setExitParams("portal","close","open","closed.");
e.setName(_("a swirling portal"));
final Ability A1=CMClass.getAbility("Prop_RoomView");
if(A1!=null)
{
A1.setMiscText(CMLib.map().getExtendedRoomID(newRoom));
e.addNonUninvokableEffect(A1);
}
final Exit e2=(Exit)e.copyOf();
final Ability A2=CMClass.getAbility("Prop_RoomView");
if(A2!=null)
{
A2.setMiscText(CMLib.map().getExtendedRoomID(mob.location()));
e2.addNonUninvokableEffect(A2);
}
oldRoom.rawDoors()[Directions.GATE]=newRoom;
newRoom.rawDoors()[Directions.GATE]=oldRoom;
oldRoom.setRawExit(Directions.GATE,e);
newRoom.setRawExit(Directions.GATE,e2);
beneficialAffect(mob,e,asLevel,5);
}
}
else
beneficialWordsFizzle(mob,null,_("<S-NAME> attempt(s) to conjur a portal, but fizzle(s) the spell."));
// return whether it worked
return success;
}
}
|
vjanmey/EpicMudfia
|
com/planet_ink/coffee_mud/Abilities/Spells/Spell_MarkerPortal.java
|
Java
|
apache-2.0
| 5,758 |
/*
* Copyright 2012-2017 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.apigateway.model.transform;
import java.util.Map;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.apigateway.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* Deployment JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeploymentJsonUnmarshaller implements Unmarshaller<Deployment, JsonUnmarshallerContext> {
public Deployment unmarshall(JsonUnmarshallerContext context) throws Exception {
Deployment deployment = new Deployment();
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 null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("id", targetDepth)) {
context.nextToken();
deployment.setId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("description", targetDepth)) {
context.nextToken();
deployment.setDescription(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("createdDate", targetDepth)) {
context.nextToken();
deployment.setCreatedDate(context.getUnmarshaller(java.util.Date.class).unmarshall(context));
}
if (context.testExpression("apiSummary", targetDepth)) {
context.nextToken();
deployment.setApiSummary(new MapUnmarshaller<String, java.util.Map<String, MethodSnapshot>>(context.getUnmarshaller(String.class),
new MapUnmarshaller<String, MethodSnapshot>(context.getUnmarshaller(String.class), MethodSnapshotJsonUnmarshaller.getInstance()))
.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 deployment;
}
private static DeploymentJsonUnmarshaller instance;
public static DeploymentJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DeploymentJsonUnmarshaller();
return instance;
}
}
|
dagnir/aws-sdk-java
|
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/transform/DeploymentJsonUnmarshaller.java
|
Java
|
apache-2.0
| 3,671 |
<?php
namespace Regweb\Authorization;
interface AuthSchemeInterface {
public function getAccessToken();
}
|
regweb/regweb-api-php
|
src/Regweb/Authorization/AuthSchemeInterface.php
|
PHP
|
apache-2.0
| 107 |
<?php
/**
*qdPM
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@qdPM.net so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade qdPM to newer
* versions in the future. If you wish to customize qdPM for your
* needs please refer to http://www.qdPM.net for more information.
*
* @copyright Copyright (c) 2009 Sergey Kharchishin and Kym Romanets (http://www.qdpm.net)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
?>
<?php
/**
* TasksPriorityTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class TasksPriorityTable extends Doctrine_Table
{
/**
* Returns an instance of this class.
*
* @return object TasksPriorityTable
*/
public static function getInstance()
{
return Doctrine_Core::getTable('TasksPriority');
}
}
|
arokia/oasis
|
source/oasis-ems/core/lib/model/doctrine/TasksPriorityTable.class.php
|
PHP
|
apache-2.0
| 1,251 |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'spec_helper'
include TwitterCldr::Shared
describe Territory do
let(:code) { '013' }
let(:territory) { Territory.new(code) }
describe '#parents' do
let(:parents) { %w[013 territory parents] }
it 'delegates to TerritoriesContainment.parents' do
expect(TerritoriesContainment).to receive(:parents).with(code).and_return(parents)
expect(territory.parents).to eq(parents)
end
end
describe '#children' do
let(:children) { %w[013 territory children] }
it 'delegates to TerritoriesContainment.children' do
expect(TerritoriesContainment).to receive(:children).with(code).and_return(children)
expect(territory.children).to eq(children)
end
end
describe '#contains?' do
let(:other_code) { 'RU' }
it 'delegates to TerritoriesContainment.contains?' do
expect(TerritoriesContainment).to receive(:contains?).with(code, other_code)
territory.contains?(other_code)
end
end
end
|
surfdome/twitter-cldr-rb
|
spec/shared/territory_spec.rb
|
Ruby
|
apache-2.0
| 1,060 |
/*
* Copyright (C) 2019 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.
*/
@NonNullApi
package androidx.media3.extractor.flac;
import androidx.media3.common.util.NonNullApi;
|
androidx/media
|
libraries/extractor/src/main/java/androidx/media3/extractor/flac/package-info.java
|
Java
|
apache-2.0
| 720 |
// Copyright 2015 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "file.h"
#include <errno.h>
#include <fcntl.h>
#ifdef __linux__
#include <linux/fs.h>
#endif // __linux__
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
// TEMP_FAILURE_RETRY is defined by some versions of <unistd.h>.
#include <algorithm>
namespace bsdiff {
std::unique_ptr<File> File::FOpen(const char* pathname, const char *flags) {
FILE* fd = fopen(pathname, flags);
if (fd == NULL)
return std::unique_ptr<File>();
return std::unique_ptr<File>(new File(fd));
}
File::~File() {
Close();
}
bool File::Read(void* buf, size_t count, size_t* bytes_read) {
if (fd_ < 0) {
errno = EBADF;
return false;
}
//ssize_t rc = TEMP_FAILURE_RETRY(read(fd_, buf, count));
size_t rc = fread(buf, count,1,fd_);
if (rc != 1)
return false;
*bytes_read = static_cast<size_t>(count);
return true;
}
bool File::Write(const void* buf, size_t count, size_t* bytes_written) {
if (fd_ < 0) {
errno = EBADF;
return false;
}
size_t rc = fwrite(buf, count,1,fd_);
if (rc != 1)
return false;
*bytes_written = static_cast<size_t>(count);
return true;
}
bool File::Seek(off_t pos) {
if (fd_ == NULL) {
errno = EBADF;
return false;
}
// fseek() uses a long value for the offset which could be smaller than off_t.
if (pos > std::numeric_limits<long>::max()) {
errno = EOVERFLOW;
return false;
}
int ret = fseek(fd_, pos, SEEK_SET);
if (ret != 0)
{
errno = EINVAL;
return false;
}
/*off_t newpos = lseek(fd_, pos, SEEK_SET);
if (newpos < 0)
return false;
if (newpos != pos) {
errno = EINVAL;
return false;
}*/
return true;
}
bool File::Close() {
if (fd_ == NULL) {
errno = EBADF;
return false;
}
bool success = (fclose(fd_) == 0);
if (!success /*&& errno == EINTR*/)
success = true;
fd_ = NULL;
return success;
}
bool File::GetSize(uint64_t* size) {
*size = fsize;
return fsize >= 0;
/*
struct stat stbuf;
if (fstat(fd_, &stbuf) == -1)
return false;
if (S_ISREG(stbuf.st_mode)) {
*size = stbuf.st_size;
return true;
}
if (S_ISBLK(stbuf.st_mode)) {
#if defined(BLKGETSIZE64)
return ioctl(fd_, BLKGETSIZE64, size);
#elif defined(DKIOCGETBLOCKCOUNT)
uint64_t sectors = 0;
if (ioctl(fd_, DKIOCGETBLOCKCOUNT, §ors) == 0) {
*size = sectors << 9;
return true;
}
return false;
#else
// Fall back to doing seeks to know the EOF.
off_t pos = lseek(fd_, 0, SEEK_CUR);
if (pos == -1)
return false;
off_t end_pos = lseek(fd_, 0, SEEK_END);
if (end_pos == -1)
return false;
*size = end_pos;
lseek(fd_, 0, SEEK_END);
return true;
#endif
}
return false;
*/
}
File::File(FILE* fd)
: fd_(fd)
{
fsize = -1;
fseek(fd, 0, SEEK_END);
fsize = ftell(fd);
fseek(fd, 0, SEEK_SET);
}
} // namespace bsdiff
|
LuaExtend/LuaExtend
|
tools/bsdiff_bzip/android_bsdiff/file.cpp
|
C++
|
apache-2.0
| 3,032 |
from processor import Processor
file_name = "program_samples\hello.hex"
processor = Processor(file_name)
processor.load()
processor.run()
if __name__ == '__main__':
pass
|
AlexLitvino/i8080_simulator
|
runner.py
|
Python
|
apache-2.0
| 177 |
using System.Web;
using System.Web.Optimization;
namespace ProApps.Web.Mvc
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new ScriptBundle("~/bundles/gtools").Include(
"~/Scripts/google-analytics.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
// Set EnableOptimizations to false for debugging. For more information,
// visit http://go.microsoft.com/fwlink/?LinkId=301862
BundleTable.EnableOptimizations = true;
}
}
}
|
alprise/proapps
|
ProApps.Web.Mvc/App_Start/BundleConfig.cs
|
C#
|
apache-2.0
| 1,579 |
/**
*
*/
package autor.builder.xml;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.xml.sax.helpers.DefaultHandler;
import autor.builder.message.ConsoleHelper;
import autor.builder.utils.ConsoLevel;
/**
* @author shanlin
*
*/
public class XmlDefaultHandler extends DefaultHandler{
private static final String MARKER_TYPE = "autor.xmlProblem";
protected void addMarker(IFile file, String message, int lineNumber,
int severity) {
try {
IMarker marker = file.createMarker(MARKER_TYPE);
marker.setAttribute(IMarker.MESSAGE, message);
marker.setAttribute(IMarker.SEVERITY, severity);
if (lineNumber == -1) {
lineNumber = 1;
}
marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
String msg = "-"+file.getName()+" line number:"+lineNumber+" "+message;
ConsoleHelper.print(ConsoLevel.getBySeverity(severity), new Object[]{msg});
} catch (CoreException e) {
ConsoleHelper.printError("--AuotR plugin error: add Marker error"+e.getMessage());
}
}
}
|
Ronshanlin/autor
|
src/autor/builder/xml/XmlDefaultHandler.java
|
Java
|
apache-2.0
| 1,091 |
/*
* proto/v1beta1/grafeas.proto
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* API version: version not set
* Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)
*/
package grafeas
import (
"context"
"io/ioutil"
"net/http"
"net/url"
"strings"
"fmt"
"github.com/antihax/optional"
)
// Linger please
var (
_ context.Context
)
type GrafeasV1Beta1ApiService service
/*
GrafeasV1Beta1ApiService Creates new notes in batch.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param parent The name of the project in the form of `projects/[PROJECT_ID]`, under which the notes are to be created.
* @param body
@return V1beta1BatchCreateNotesResponse
*/
func (a *GrafeasV1Beta1ApiService) BatchCreateNotes(ctx context.Context, parent string, body V1beta1BatchCreateNotesRequest) (V1beta1BatchCreateNotesResponse, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Post")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1BatchCreateNotesResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{parent=projects/*}/notes:batchCreate"
localVarPath = strings.Replace(localVarPath, "{"+"parent"+"}", fmt.Sprintf("%v", parent), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1BatchCreateNotesResponse
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Creates new occurrences in batch.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param parent The name of the project in the form of `projects/[PROJECT_ID]`, under which the occurrences are to be created.
* @param body
@return V1beta1BatchCreateOccurrencesResponse
*/
func (a *GrafeasV1Beta1ApiService) BatchCreateOccurrences(ctx context.Context, parent string, body V1beta1BatchCreateOccurrencesRequest) (V1beta1BatchCreateOccurrencesResponse, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Post")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1BatchCreateOccurrencesResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{parent=projects/*}/occurrences:batchCreate"
localVarPath = strings.Replace(localVarPath, "{"+"parent"+"}", fmt.Sprintf("%v", parent), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1BatchCreateOccurrencesResponse
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Creates a new note.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param parent The name of the project in the form of `projects/[PROJECT_ID]`, under which the note is to be created.
* @param body The note to create.
@return V1beta1Note
*/
func (a *GrafeasV1Beta1ApiService) CreateNote(ctx context.Context, parent string, body V1beta1Note) (V1beta1Note, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Post")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1Note
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{parent=projects/*}/notes"
localVarPath = strings.Replace(localVarPath, "{"+"parent"+"}", fmt.Sprintf("%v", parent), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1Note
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Creates a new occurrence.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param parent The name of the project in the form of `projects/[PROJECT_ID]`, under which the occurrence is to be created.
* @param body The occurrence to create.
@return V1beta1Occurrence
*/
func (a *GrafeasV1Beta1ApiService) CreateOccurrence(ctx context.Context, parent string, body V1beta1Occurrence) (V1beta1Occurrence, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Post")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1Occurrence
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{parent=projects/*}/occurrences"
localVarPath = strings.Replace(localVarPath, "{"+"parent"+"}", fmt.Sprintf("%v", parent), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1Occurrence
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Deletes the specified note.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param name The name of the note in the form of `projects/[PROVIDER_ID]/notes/[NOTE_ID]`.
@return interface{}
*/
func (a *GrafeasV1Beta1ApiService) DeleteNote(ctx context.Context, name string) (interface{}, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Delete")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue interface{}
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{name=projects/*/notes/*}"
localVarPath = strings.Replace(localVarPath, "{"+"name"+"}", fmt.Sprintf("%v", name), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v interface{}
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Deletes the specified occurrence. For example, use this method to delete an occurrence when the occurrence is no longer applicable for the given resource.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param name The name of the occurrence in the form of `projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]`.
@return interface{}
*/
func (a *GrafeasV1Beta1ApiService) DeleteOccurrence(ctx context.Context, name string) (interface{}, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Delete")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue interface{}
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{name=projects/*/occurrences/*}"
localVarPath = strings.Replace(localVarPath, "{"+"name"+"}", fmt.Sprintf("%v", name), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v interface{}
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Gets the specified note.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param name The name of the note in the form of `projects/[PROVIDER_ID]/notes/[NOTE_ID]`.
@return V1beta1Note
*/
func (a *GrafeasV1Beta1ApiService) GetNote(ctx context.Context, name string) (V1beta1Note, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Get")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1Note
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{name=projects/*/notes/*}"
localVarPath = strings.Replace(localVarPath, "{"+"name"+"}", fmt.Sprintf("%v", name), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1Note
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Gets the specified occurrence.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param name The name of the occurrence in the form of `projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]`.
@return V1beta1Occurrence
*/
func (a *GrafeasV1Beta1ApiService) GetOccurrence(ctx context.Context, name string) (V1beta1Occurrence, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Get")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1Occurrence
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{name=projects/*/occurrences/*}"
localVarPath = strings.Replace(localVarPath, "{"+"name"+"}", fmt.Sprintf("%v", name), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1Occurrence
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Gets the note attached to the specified occurrence. Consumer projects can use this method to get a note that belongs to a provider project.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param name The name of the occurrence in the form of `projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]`.
@return V1beta1Note
*/
func (a *GrafeasV1Beta1ApiService) GetOccurrenceNote(ctx context.Context, name string) (V1beta1Note, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Get")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1Note
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{name=projects/*/occurrences/*}/notes"
localVarPath = strings.Replace(localVarPath, "{"+"name"+"}", fmt.Sprintf("%v", name), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1Note
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Gets a summary of the number and severity of occurrences.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param parent The name of the project to get a vulnerability summary for in the form of `projects/[PROJECT_ID]`.
* @param optional nil or *GetVulnerabilityOccurrencesSummaryOpts - Optional Parameters:
* @param "Filter" (optional.String) - The filter expression.
@return V1beta1VulnerabilityOccurrencesSummary
*/
type GetVulnerabilityOccurrencesSummaryOpts struct {
Filter optional.String
}
func (a *GrafeasV1Beta1ApiService) GetVulnerabilityOccurrencesSummary(ctx context.Context, parent string, localVarOptionals *GetVulnerabilityOccurrencesSummaryOpts) (V1beta1VulnerabilityOccurrencesSummary, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Get")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1VulnerabilityOccurrencesSummary
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{parent=projects/*}/occurrences:vulnerabilitySummary"
localVarPath = strings.Replace(localVarPath, "{"+"parent"+"}", fmt.Sprintf("%v", parent), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
if localVarOptionals != nil && localVarOptionals.Filter.IsSet() {
localVarQueryParams.Add("filter", parameterToString(localVarOptionals.Filter.Value(), ""))
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1VulnerabilityOccurrencesSummary
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Lists occurrences referencing the specified note. Provider projects can use this method to get all occurrences across consumer projects referencing the specified note.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param name The name of the note to list occurrences for in the form of `projects/[PROVIDER_ID]/notes/[NOTE_ID]`.
* @param optional nil or *ListNoteOccurrencesOpts - Optional Parameters:
* @param "Filter" (optional.String) - The filter expression.
* @param "PageSize" (optional.Int32) - Number of occurrences to return in the list.
* @param "PageToken" (optional.String) - Token to provide to skip to a particular spot in the list.
@return V1beta1ListNoteOccurrencesResponse
*/
type ListNoteOccurrencesOpts struct {
Filter optional.String
PageSize optional.Int32
PageToken optional.String
}
func (a *GrafeasV1Beta1ApiService) ListNoteOccurrences(ctx context.Context, name string, localVarOptionals *ListNoteOccurrencesOpts) (V1beta1ListNoteOccurrencesResponse, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Get")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1ListNoteOccurrencesResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{name=projects/*/notes/*}/occurrences"
localVarPath = strings.Replace(localVarPath, "{"+"name"+"}", fmt.Sprintf("%v", name), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
if localVarOptionals != nil && localVarOptionals.Filter.IsSet() {
localVarQueryParams.Add("filter", parameterToString(localVarOptionals.Filter.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.PageSize.IsSet() {
localVarQueryParams.Add("page_size", parameterToString(localVarOptionals.PageSize.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.PageToken.IsSet() {
localVarQueryParams.Add("page_token", parameterToString(localVarOptionals.PageToken.Value(), ""))
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1ListNoteOccurrencesResponse
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Lists notes for the specified project.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param parent The name of the project to list notes for in the form of `projects/[PROJECT_ID]`.
* @param optional nil or *ListNotesOpts - Optional Parameters:
* @param "Filter" (optional.String) - The filter expression.
* @param "PageSize" (optional.Int32) - Number of notes to return in the list. Must be positive. Max allowed page size is 1000. If not specified, page size defaults to 20.
* @param "PageToken" (optional.String) - Token to provide to skip to a particular spot in the list.
@return V1beta1ListNotesResponse
*/
type ListNotesOpts struct {
Filter optional.String
PageSize optional.Int32
PageToken optional.String
}
func (a *GrafeasV1Beta1ApiService) ListNotes(ctx context.Context, parent string, localVarOptionals *ListNotesOpts) (V1beta1ListNotesResponse, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Get")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1ListNotesResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{parent=projects/*}/notes"
localVarPath = strings.Replace(localVarPath, "{"+"parent"+"}", fmt.Sprintf("%v", parent), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
if localVarOptionals != nil && localVarOptionals.Filter.IsSet() {
localVarQueryParams.Add("filter", parameterToString(localVarOptionals.Filter.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.PageSize.IsSet() {
localVarQueryParams.Add("page_size", parameterToString(localVarOptionals.PageSize.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.PageToken.IsSet() {
localVarQueryParams.Add("page_token", parameterToString(localVarOptionals.PageToken.Value(), ""))
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1ListNotesResponse
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Lists occurrences for the specified project.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param parent The name of the project to list occurrences for in the form of `projects/[PROJECT_ID]`.
* @param optional nil or *ListOccurrencesOpts - Optional Parameters:
* @param "Filter" (optional.String) - The filter expression.
* @param "PageSize" (optional.Int32) - Number of occurrences to return in the list. Must be positive. Max allowed page size is 1000. If not specified, page size defaults to 20.
* @param "PageToken" (optional.String) - Token to provide to skip to a particular spot in the list.
@return V1beta1ListOccurrencesResponse
*/
type ListOccurrencesOpts struct {
Filter optional.String
PageSize optional.Int32
PageToken optional.String
}
func (a *GrafeasV1Beta1ApiService) ListOccurrences(ctx context.Context, parent string, localVarOptionals *ListOccurrencesOpts) (V1beta1ListOccurrencesResponse, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Get")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1ListOccurrencesResponse
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{parent=projects/*}/occurrences"
localVarPath = strings.Replace(localVarPath, "{"+"parent"+"}", fmt.Sprintf("%v", parent), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
if localVarOptionals != nil && localVarOptionals.Filter.IsSet() {
localVarQueryParams.Add("filter", parameterToString(localVarOptionals.Filter.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.PageSize.IsSet() {
localVarQueryParams.Add("page_size", parameterToString(localVarOptionals.PageSize.Value(), ""))
}
if localVarOptionals != nil && localVarOptionals.PageToken.IsSet() {
localVarQueryParams.Add("page_token", parameterToString(localVarOptionals.PageToken.Value(), ""))
}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1ListOccurrencesResponse
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Updates the specified note.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param name The name of the note in the form of `projects/[PROVIDER_ID]/notes/[NOTE_ID]`.
* @param body The updated note.
@return V1beta1Note
*/
func (a *GrafeasV1Beta1ApiService) UpdateNote(ctx context.Context, name string, body V1beta1Note) (V1beta1Note, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Patch")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1Note
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{name=projects/*/notes/*}"
localVarPath = strings.Replace(localVarPath, "{"+"name"+"}", fmt.Sprintf("%v", name), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1Note
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
/*
GrafeasV1Beta1ApiService Updates the specified occurrence.
* @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background().
* @param name The name of the occurrence in the form of `projects/[PROJECT_ID]/occurrences/[OCCURRENCE_ID]`.
* @param body The updated occurrence.
@return V1beta1Occurrence
*/
func (a *GrafeasV1Beta1ApiService) UpdateOccurrence(ctx context.Context, name string, body V1beta1Occurrence) (V1beta1Occurrence, *http.Response, error) {
var (
localVarHttpMethod = strings.ToUpper("Patch")
localVarPostBody interface{}
localVarFileName string
localVarFileBytes []byte
localVarReturnValue V1beta1Occurrence
)
// create path and map variables
localVarPath := a.client.cfg.BasePath + "/v1beta1/{name=projects/*/occurrences/*}"
localVarPath = strings.Replace(localVarPath, "{"+"name"+"}", fmt.Sprintf("%v", name), -1)
localVarHeaderParams := make(map[string]string)
localVarQueryParams := url.Values{}
localVarFormParams := url.Values{}
// to determine the Content-Type header
localVarHttpContentTypes := []string{"application/json"}
// set Content-Type header
localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)
if localVarHttpContentType != "" {
localVarHeaderParams["Content-Type"] = localVarHttpContentType
}
// to determine the Accept header
localVarHttpHeaderAccepts := []string{"application/json"}
// set Accept header
localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)
if localVarHttpHeaderAccept != "" {
localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
}
// body params
localVarPostBody = &body
r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)
if err != nil {
return localVarReturnValue, nil, err
}
localVarHttpResponse, err := a.client.callAPI(r)
if err != nil || localVarHttpResponse == nil {
return localVarReturnValue, localVarHttpResponse, err
}
localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)
localVarHttpResponse.Body.Close()
if err != nil {
return localVarReturnValue, localVarHttpResponse, err
}
if localVarHttpResponse.StatusCode < 300 {
// If we succeed, return the data, otherwise pass on to decode error.
err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err == nil {
return localVarReturnValue, localVarHttpResponse, err
}
}
if localVarHttpResponse.StatusCode >= 300 {
newErr := GenericSwaggerError{
body: localVarBody,
error: localVarHttpResponse.Status,
}
if localVarHttpResponse.StatusCode == 200 {
var v V1beta1Occurrence
err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type"));
if err != nil {
newErr.error = err.Error()
return localVarReturnValue, localVarHttpResponse, newErr
}
newErr.model = v
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, newErr
}
return localVarReturnValue, localVarHttpResponse, nil
}
|
grafeas/client-go
|
0.1.0/api_grafeas_v1_beta1.go
|
GO
|
apache-2.0
| 52,653 |
package application.beadando3.view;
import application.beadando3.services.implementations.PingModelServiceImplementation;
import java.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import application.beadando3.Main;
import application.beadando3.DAO.PingModelDAO;
import application.beadando3.model.PingModel;
import helper.Ping;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.stage.Stage;
/**
* @author danida
*
*/
public class PingView {
@FXML
private TextField destinationIP;
@FXML
private TextArea output;
@FXML
private TextArea dboutput;
/**
* Pingtable contains all if the former ping results.
*/
@FXML
public TableView<PingModel> pingTable;
@FXML
private TableColumn<PingModel, String> destination;
@FXML
private TableColumn<PingModel, String> executiondate;
private PingModelDAO pmdao;
private Ping ping;
private final static Logger logger = LoggerFactory.getLogger(PingView.class);
/**
* Reference to the main application.
*/
public static Main mainApp;
/**
* Initializing the view of the Ping.
*/
@FXML
void initialize() {
pmdao = new PingModelDAO();
ping = new Ping();
PingModelServiceImplementation pm = new PingModelServiceImplementation(pmdao);
pingTable.setItems(FXCollections.observableList(pm.getAll()));
destination.setCellValueFactory(cellData -> cellData.getValue().getDestinationProperty());
executiondate.setCellValueFactory(cellData -> cellData.getValue().getExecution_DateProperty());
pingTable.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> {
if (newValue != null){
dboutput.setText(newValue.getOutput());
}
else {
dboutput.setText("");
}
});
}
/**
* Getter of the destination.
* @return Returns the value of the DestionationIP textfield
*/
public TextField getDestinationIP() {
return destinationIP;
}
/**
* Setter of the destiantionIP.
* @param destinationIP - Value of the destinationIP
*/
public void setDestinationIP(TextField destinationIP) {
this.destinationIP = destinationIP;
}
/**
* Getter of the ping output.
* @return Returns the output of the ping that had been run.
*/
public TextArea getOutput() {
return output;
}
/**
* Setter of the output.
* @param output - The output of the ping command
*/
public void setOutput(String output) {
this.output.setText(output);
}
/**
* Calls the ping helper and create new thread which runs and updates the output.
*/
public void dothePing() {
ping.setDestinationIP(destinationIP.getText());
ping.setPingView(this);
Thread t = new Thread(ping);
t.start();
}
/**
* Creates and saves the pingmodel based on the outputs.
*/
@FXML
public void handleSaving(){
PingModelServiceImplementation pd = new PingModelServiceImplementation(pmdao);
PingModel pm = new PingModel();
pm.setDestination(destinationIP.getText());
pm.setOutput(output.getText());
LocalDateTime now = LocalDateTime.now();
pm.setExecution_date(now);
pm.setId(null);
pd.save(pm);
pingTable.setItems(FXCollections.observableList(pd.getAll()));
}
/**
* Deletes the pingmodel based on the selection.
*/
@FXML
public void handleDeleting(){
PingModelServiceImplementation rm = new PingModelServiceImplementation(pmdao);
int selectedIndex = pingTable.getSelectionModel().getSelectedIndex();
try{
PingModel pingmodel= pingTable.getItems().get(selectedIndex);
rm.delete(pingmodel);
pingTable.setItems(FXCollections.observableList(rm.getAll()));
}
catch (ArrayIndexOutOfBoundsException e){
logger.error("User trying to delete ping without selecting it");
Alert alert = new Alert(AlertType.WARNING);
alert.initOwner(mainApp.getPrimaryStage());
alert.setTitle("No Selection");
alert.setHeaderText("No Ping record Selected");
alert.setContentText("Please select a ping result from the table.");
alert.showAndWait();
}
}
}
|
danida/beadando
|
src/main/java/application/beadando3/view/PingView.java
|
Java
|
apache-2.0
| 4,485 |
/* (C) Copyright 2015 Laran Evans */
package com.laranevans.warehouse.web.exception;
import java.util.ArrayList;
import java.util.List;
public class JsonFriendlyErrors {
private List<JsonFriendlyError> errors = new ArrayList<>();
public JsonFriendlyErrors(){}
public JsonFriendlyErrors(List<JsonFriendlyError> errors) {
this.errors.addAll(errors);
}
public JsonFriendlyErrors add(JsonFriendlyError error) {
errors.add(error);
return this;
}
public JsonFriendlyErrors add(ErrorCodes code, String message) {
errors.add(new JsonFriendlyError(code, message));
return this;
}
public List<JsonFriendlyError> getErrors() {
return errors;
}
}
|
laran/warehouse
|
warehouse/src/main/java/com/laranevans/warehouse/web/exception/JsonFriendlyErrors.java
|
Java
|
apache-2.0
| 730 |
package main;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class SpriteSheet {
private ArrayList<BufferedImage> subImages = new ArrayList<BufferedImage>();
public SpriteSheet(String imgStr, int index, int width){
BufferedImage img = null;
try {
img = ImageIO.read(new File(imgStr));
} catch (IOException e) {
e.printStackTrace();
}
for(int i = 0; i < index; i++){
subImages.add(img.getSubimage(i * width, 0, width, img.getHeight()));
}
}
public BufferedImage getImageByIndex(int index){
return subImages.get(index);
}
}
|
pehnquihn/pongmmo
|
Pong/src/main/SpriteSheet.java
|
Java
|
apache-2.0
| 665 |
#!/usr/local/bin/python2.7
# -*- coding: utf-8 -*-
__author__ = 'https://github.com/password123456/'
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import requests
import urllib
import urllib2
import json
import datetime
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def get_recent_lotto():
url = 'http://www.nlotto.co.kr/common.do?method=getLottoNumber'
try:
r = requests.get(url)
data = json.loads(r.text)
except Exception, e:
print '%s[-] Exception::%s%s' % (bcolors.WARNING, e, bcolors.ENDC)
sys.exit(0)
else:
r.close()
drwNoDate = data['drwNoDate']
drwNo = data['drwNo']
firstWinamnt = data['firstWinamnt']
drwtNo1 = data['drwtNo1']
drwtNo2 = data['drwtNo2']
drwtNo3 = data['drwtNo3']
drwtNo4 = data['drwtNo4']
drwtNo5 = data['drwtNo5']
drwtNo6 = data['drwtNo6']
bnusNo = data['bnusNo']
# 당첨금 자리수 변환
firstWinamnt = format(firstWinamnt, ',')
content = '** 최근 로또 조회 **\n'
content = content + ' [+] 로또 : http://www.nlotto.co.kr\n [+] 추첨일자: %s\n [+] 회차: %d 회\n [+] 당첨번호: %d %d %d %d %d %d\n [+] 보너스: %d \n [*] 당첨금: %s 원\n' % (drwNoDate, drwNo, drwtNo1, drwtNo2, drwtNo3, drwtNo4, drwtNo5, drwtNo6, bnusNo, firstWinamnt )
#print content
return content
content = get_recent_lotto()
def main():
get_recent_lotto()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
sys.exit(0)
except Exception, e:
print '%s[-] Exception::%s%s' % (bcolors.WARNING, e, bcolors.ENDC)
|
password123456/lotto
|
get_recent_lotto.py
|
Python
|
apache-2.0
| 1,787 |
/*
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.sakaiproject.kernel.api;
/**
* A service to provide Classloaders to the kernel based on component
* specifications. These classloaders should be fully populate with the the
* class path elements in the component specification, and where appropriate
* packages should be exported and dependencies injected into the shared
* classloader. The resulting classloader should configured and ready for use.
*/
public interface ClassLoaderService {
/**
* Create a ComponentClassLoader based on the specification
*
* @param spec
* the ComponentSpecification
* @return the new Component Classloader
* @throws ComponentSpecificationException
*/
ClassLoader getComponentClassLoader(ComponentSpecification spec)
throws ComponentSpecificationException;
}
|
sakai-mirror/k2
|
agnostic/shared/src/main/java/org/sakaiproject/kernel/api/ClassLoaderService.java
|
Java
|
apache-2.0
| 1,593 |
/*
* Copyright (c) Created by Cody.yi on 2016/9/5.
*/
package com.cody.handler.framework.viewmodel;
/**
* Created by cody.yi on 2016/8/24.
* <p>
* 不包含头部的list view
*
* @param <ItemViewModel> ListView中的item ViewModel
*/
public class ListWithSearchViewModel<ItemViewModel extends XItemViewModel> extends ListViewModel<ItemViewModel> implements IWithSearchViewModel {
private final SearchViewModel mSearchViewModel = SearchViewModel.createDefaultSearch();
@Override
public SearchViewModel getSearchViewModel() {
return mSearchViewModel;
}
}
|
codyer/CleanFramework
|
handler/src/main/java/com/cody/handler/framework/viewmodel/ListWithSearchViewModel.java
|
Java
|
apache-2.0
| 589 |
// Copyright © 2013-2020 Andy Goryachev <andy@goryachev.com>
package goryachev.common.io;
public class BitStreamCommon
{
protected static final int BITS_PER_BYTE = 8;
protected static final int MASK[] =
{
0x00000000,
0x00000001,
0x00000003,
0x00000007,
0x0000000f,
0x0000001f,
0x0000003f,
0x0000007f,
0x000000ff,
0x000001ff,
0x000003ff,
0x000007ff,
0x00000fff,
0x00001fff,
0x00003fff,
0x00007fff,
0x0000ffff,
0x0001ffff,
0x0003ffff,
0x0007ffff,
0x000fffff,
0x001fffff,
0x003fffff,
0x007fffff,
0x00ffffff,
0x01ffffff,
0x03ffffff,
0x07ffffff,
0x0fffffff,
0x1fffffff,
0x3fffffff,
0x7fffffff,
0xffffffff
};
public static int getMask(int bits)
{
return MASK[bits];
}
}
|
andy-goryachev/JsonPretty
|
src/goryachev/common/io/BitStreamCommon.java
|
Java
|
apache-2.0
| 828 |
package br.ufrn.Myeclone.model;
import javax.persistence.Entity;
@Entity
public class Acao extends Tarefa{
}
|
JorgePereiraUFRN/Myeclone
|
Myeclone/src/br/ufrn/Myeclone/model/Acao.java
|
Java
|
apache-2.0
| 123 |
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var ts = require("typescript");
var index_1 = require("../../models/index");
var components_1 = require("../components");
var AliasConverter = (function (_super) {
__extends(AliasConverter, _super);
function AliasConverter() {
_super.apply(this, arguments);
this.priority = 100;
}
AliasConverter.prototype.supportsNode = function (context, node, type) {
if (!type || !node || !node.typeName)
return false;
if (!type.symbol)
return true;
var checker = context.checker;
var symbolName = checker.getFullyQualifiedName(type.symbol).split('.');
if (!symbolName.length)
return false;
if (symbolName[0].substr(0, 1) == '"')
symbolName.shift();
var nodeName = ts.getTextOfNode(node.typeName).split('.');
if (!nodeName.length)
return false;
var common = Math.min(symbolName.length, nodeName.length);
symbolName = symbolName.slice(-common);
nodeName = nodeName.slice(-common);
return nodeName.join('.') != symbolName.join('.');
};
AliasConverter.prototype.convertNode = function (context, node) {
var name = ts.getTextOfNode(node.typeName);
return new index_1.ReferenceType(name, index_1.ReferenceType.SYMBOL_ID_RESOLVE_BY_NAME);
};
AliasConverter = __decorate([
components_1.Component({ name: 'type:alias' })
], AliasConverter);
return AliasConverter;
})(components_1.ConverterTypeComponent);
exports.AliasConverter = AliasConverter;
|
aciccarello/typedoc
|
lib/converter/types/alias.js
|
JavaScript
|
apache-2.0
| 2,391 |
/*
* 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.ivy.plugins.conflict;
import java.util.Collection;
import org.apache.ivy.core.module.descriptor.DependencyDescriptor;
import org.apache.ivy.core.module.id.ModuleRevisionId;
import org.apache.ivy.core.settings.IvySettings;
import org.apache.ivy.plugins.IvySettingsAware;
public abstract class AbstractConflictManager implements ConflictManager, IvySettingsAware {
private String name;
private IvySettings settings;
public IvySettings getSettings() {
return settings;
}
public void setSettings(IvySettings settings) {
this.settings = settings;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
public void handleAllBlacklistedRevisions(DependencyDescriptor dd,
Collection<ModuleRevisionId> foundBlacklisted) {
}
}
|
jaikiran/ant-ivy
|
src/java/org/apache/ivy/plugins/conflict/AbstractConflictManager.java
|
Java
|
apache-2.0
| 1,770 |
/* Copyright 2015 1060 Research Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.polestar.data.login;
import org.netkernel.layer0.nkf.*;
import org.netkernel.mod.hds.*;
import org.netkernel.module.standard.endpoint.StandardAccessorImpl;
import io.polestar.data.db.PersistenceFactory;
import io.polestar.data.util.MonitorUtils;
public class AuthenticationDataAccessor extends StandardAccessorImpl
{
public AuthenticationDataAccessor()
{ this.declareThreadSafe();
this.declareInhibitCheckForBadExpirationOnMutableResource();
}
public void onSource(INKFRequestContext aContext) throws Exception
{
IHDSDocument authData=PersistenceFactory.getPersistence(aContext).getAuthentication(aContext);
INKFResponse resp=aContext.createResponseFrom(authData);
MonitorUtils.attachGoldenThread(aContext, "gt:auth");
}
public void onSink(INKFRequestContext aContext) throws Exception
{
IHDSMutator m=aContext.source("res:/md/authentication",IHDSDocument.class).getMutableClone();
IHDSReader primary=aContext.sourcePrimary(IHDSDocument.class).getReader();
String username=(String)primary.getFirstValue("/*/username");
String password=(String)primary.getFirstValue("/*/password");
IHDSMutator user=m.getFirstNodeOrNull("/authentication/user[username='"+username+"']");
if (user!=null)
{
INKFRequest req=aContext.createRequest("active:generatePasswordHash");
req.addArgumentByValue("password",password);
req.setRepresentationClass(String.class);
String hash=(String)aContext.issueRequest(req);
user.setCursor("password").setValue(hash);
IHDSDocument state=m.toDocument(false);
PersistenceFactory.getPersistence(aContext).setAuthentication(state, aContext);
MonitorUtils.cutGoldenThread(aContext, "gt:auth");
}
}
}
|
tonbut/polestar
|
module/urn.io.polestar/src/io/polestar/data/login/AuthenticationDataAccessor.java
|
Java
|
apache-2.0
| 2,279 |
using System.Collections.Generic;
namespace Angular_ASPNETCore_Seed.Models
{
public struct PagingResult<T>
{
public IEnumerable<T> Records { get; set; }
public int TotalRecords { get; set; }
public PagingResult(IEnumerable<T> items, int totalRecords)
{
TotalRecords = totalRecords;
Records = items;
}
}
}
|
HadwinJ/PerfectDemo
|
PerfectSolution/Angular_ASPNETCore_Seed/Models/PagingResult.cs
|
C#
|
apache-2.0
| 386 |
/*
* Copyright (C) 2015-2021 KeepSafe Software
*
* 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.getkeepsafe.dexcount.plugin;
import com.android.repository.Revision;
import com.android.repository.Revision.PreviewComparison;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
* Utility for obtaining an appropriate task applicator factory for a given
* Android Gradle Plugin revision.
*/
public final class TaskApplicators {
private TaskApplicators() {
// no instances
}
public static Optional<TaskApplicator.Factory> getFactory(Revision revision) {
List<TaskApplicator.Factory> factories = Arrays.asList(
new SevenOhApplicator.Factory(),
new FourTwoApplicator.Factory(),
new FourOneApplicator.Factory(),
new ThreeSixApplicator.Factory(),
new ThreeFourApplicator.Factory(),
new JavaOnlyApplicator.Factory()
);
return factories.stream()
.filter(it -> revision.compareTo(it.getMinimumRevision(), PreviewComparison.IGNORE) >= 0)
.findFirst();
}
}
|
KeepSafe/dexcount-gradle-plugin
|
src/main/java/com/getkeepsafe/dexcount/plugin/TaskApplicators.java
|
Java
|
apache-2.0
| 1,649 |
/**
* @file
* Declares the array type.
*/
#pragma once
#include "tuple.hpp"
#include "data.hpp"
#include "../values/array.hpp"
#include "../../cast.hpp"
#include <boost/functional/hash.hpp>
#include <boost/variant.hpp>
#include <limits>
#include <ostream>
#include <functional>
namespace puppet { namespace runtime { namespace types {
/**
* Represents the Puppet Array type.
* @tparam Type The type of a runtime type.
*/
template <typename Type>
struct basic_array
{
/**
* Constructs an Array type.
* @param type The element type of the array. Defaults to the Data type.
* @param from The "from" type parameter.
* @param to The "to" type parameter.
*/
explicit basic_array(Type type = data(), int64_t from = std::numeric_limits<int64_t>::min(), int64_t to = std::numeric_limits<int64_t>::max()) :
_element_type(rvalue_cast(type)),
_from(from),
_to(to)
{
}
/**
* Gets the element type of the array.
* @return Returns the element type of the array.
*/
Type const& element_type() const
{
return _element_type;
}
/**
* Gets the "from" type parameter.
* @return Returns the "from" type parameter.
*/
int64_t from() const
{
return _from;
}
/**
* Gets the "to" type parameter.
* @return Returns the "to" type parameter.
*/
int64_t to() const
{
return _to;
}
/**
* Gets the name of the type.
* @return Returns the name of the type (i.e. Array).
*/
static const char* name()
{
return "Array";
}
/**
* Determines if the given value is an instance of this type.
* @tparam Value The type of the runtime value.
* @param value The value to determine if it is an instance of this type. This value will never be a variable.
* @return Returns true if the given value is an instance of this type or false if not.
*/
template <typename Value>
bool is_instance(Value const& value) const
{
// Forward declaration of unsafe_is_instance for recursion
bool unsafe_is_instance(void const*, void const*);
// Check for array
auto ptr = boost::get<values::basic_array<Value>>(&value);
if (!ptr) {
return false;
}
// Check for size is range
int64_t size = static_cast<int64_t>(ptr->size());
if (!(_to < _from ? (size >= _to && size <= _from) : (size >= _from && size <= _to))) {
return false;
}
// Check that each element is of the type
for (auto const& element : *ptr) {
if (!unsafe_is_instance(&element, &_element_type)) {
return false;
}
}
return true;
}
/**
* Determines if the given type is a specialization (i.e. more specific) of this type.
* @param other The other type to check for specialization.
* @return Returns true if the other type is a specialization or false if not.
*/
bool is_specialization(Type const& other) const
{
// For the other type to be a specialization, it must be an Array or Tuple
// For Tuple, the number of types must be 1
// The element types must match
// And the range of other needs to be inside of this type's range
int64_t from, to;
auto array = boost::get<basic_array<Type>>(&other);
if (!array) {
// Check for Array[ElementType]
if (array->element_type() != _element_type) {
return false;
}
from = array->from();
to = array->to();
} else {
// Check for a Tuple[ElementType]
auto tuple = boost::get<basic_tuple<Type>>(&other);
if (!tuple || tuple->types().size() != 1 || tuple->types().front() != _element_type) {
return false;
}
from = tuple->from();
to = tuple->to();
}
// Check for equality
if (from == _from && to == _to) {
return false;
}
return std::min(from, to) >= std::min(_from, _to) &&
std::max(from, to) <= std::max(_from, _to);
}
private:
Type _element_type;
int64_t _from;
int64_t _to;
};
/**
* Stream insertion operator for array type.
* @tparam Type The runtime "type" type.
* @param os The output stream to write the type to.
* @param type The type to write.
* @return Returns the given output stream.
*/
template <typename Type>
std::ostream& operator<<(std::ostream& os, basic_array<Type> const& type)
{
os << basic_array<Type>::name() << '[' << type.element_type();
bool from_default = type.from() == std::numeric_limits<int64_t>::min();
bool to_default = type.to() == std::numeric_limits<int64_t>::max();
if (from_default && to_default) {
// Only output the type
os << ']';
return os;
}
os << ", ";
if (from_default) {
os << "default";
} else {
os << type.from();
}
os << ", ";
if (to_default) {
os << "default";
} else {
os << type.to();
}
os << ']';
return os;
}
/**
* Equality operator for array.
* @tparam Type The "runtime type" type.
* @param left The left type to compare.
* @param right The right type to compare.
* @return Returns true if the two types are equal or false if not.
*/
template <typename Type>
bool operator==(basic_array<Type> const& left, basic_array<Type> const& right)
{
return left.from() == right.from() && left.to() == right.to() && left.element_type() == right.element_type();
}
}}} // puppet::runtime::types
namespace boost {
/**
* Hash specialization for Array type.
* @tparam Type The "runtime type" type.
*/
template <typename Type>
struct hash<puppet::runtime::types::basic_array<Type>>
{
/**
* Hashes the Array type.
* @param type The type to hash.
* @return Returns the hash value for the type.
*/
size_t operator()(puppet::runtime::types::basic_array<Type> const& type) const
{
size_t seed = 0;
hash_combine(seed, puppet::runtime::types::basic_array<Type>::name());
hash_combine(seed, type.element_type());
hash_combine(seed, type.from());
hash_combine(seed, type.to());
return seed;
}
};
}
|
iankronquist/puppetcpp
|
lib/include/puppet/runtime/types/array.hpp
|
C++
|
apache-2.0
| 7,145 |
public class Test5
{
public static void main(String[] args)
{
Goods iphone = new Iphone();
iphone.setName("iphone");
iphone.setPrice(5000.0);
Goods shoes =new Shoes();
shoes.setName("鞋");
shoes.setPrice(123.0);
Item item =new Item();
item.setGoods(iphone);
item.setAmount(2);
Item item1 =new Item();
item1.setGoods(shoes);
item1.setAmount(3);
Order order = new Order();
order.order(item);
Order order1 = new Order();
order1.order(item1);
Customer customer = new Customer();
customer.order(order);
Customer customer2 = new Customer();
customer2.order(order1);
Payment aliay = new Aliay();
customer.pay(aliay);
aliay.pay(order.getTotalMoney());
}
}
class Customer
{
public void order(Order order)
{
System.out.println("订单内容:");
}
public void pay(Payment payment)
{
System.out.println("你选择的支付方式是:");
}
}
class Order
{
private String id;
// private date createDate;
Item[] items = new Item[2];
public void order(Item item)
{
}
public double getTotalMoney()
{
Goods iphone = new Iphone();
Goods shoes =new Shoes();
return (double)(iphone.getPrice()*items[0].getAmount()+shoes.getPrice()*items[1].getAmount());
}
}
class Item
{
private Goods goods;
private int amount;
public void setGoods(Goods goods)
{
this.goods = goods;
}
public Goods getGoods()
{
return goods;
}
public void setAmount(int amount)
{
this.amount = amount;
}
public int getAmount()
{
return amount;
}
}
class Goods
{
private double price;
private String name;
public void setPrice(double price)
{
this.price = price;
}
public double getPrice()
{
return price;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
class Iphone extends Goods
{
}
class Shoes extends Goods
{
}
interface Payment
{
void pay(double money);
}
class Aliay implements Payment
{
public void pay(double money)
{
System.out.println("阿里支付"+money);
}
}
class ApplePay implements Payment
{
public void pay(double money)
{
System.out.println("苹果支付"+money);
}
}
class WeixinPay implements Payment
{
public void pay(double money)
{
System.out.println("微信支付"+money);
}
}
|
JAVA201708/Homework
|
201709/20170915/Team1/Malanlan/编程题/ex05/Test5.java
|
Java
|
apache-2.0
| 2,394 |
/**
* 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.cassandra.db;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeoutException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.concurrent.JMXEnabledThreadPoolExecutor;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.compaction.CompactionManager;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.db.filter.QueryPath;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.gms.ApplicationState;
import org.apache.cassandra.gms.FailureDetector;
import org.apache.cassandra.gms.Gossiper;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.service.*;
import org.apache.cassandra.thrift.*;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.WrappedRunnable;
import org.cliffc.high_scale_lib.NonBlockingHashSet;
/**
* For each endpoint for which we have hints, there is a row in the system hints CF.
* The key for this row is ByteBuffer.wrap(string), i.e. "127.0.0.1".
* (We have to use String keys for compatibility with OPP.)
* SuperColumns in these rows are the mutations to replay, with uuid names:
*
* <dest ip>: { // key
* <uuid>: { // supercolumn
* mutation: <mutation> // subcolumn
* version: <mutation serialization version>
* table: <table of hinted mutation>
* key: <key of hinted mutation>
* }
* }
*
* When FailureDetector signals that a node that was down is back up, we page through
* the hinted mutations and send them over one at a time, waiting for
* hinted_handoff_throttle_delay in between each.
*
* deliverHints is also exposed to JMX so it can be run manually if FD ever misses
* its cue somehow.
*/
public class HintedHandOffManager implements HintedHandOffManagerMBean
{
public static final HintedHandOffManager instance = new HintedHandOffManager();
public static final String HINTS_CF = "HintsColumnFamily";
private static final Logger logger_ = LoggerFactory.getLogger(HintedHandOffManager.class);
private static final int PAGE_SIZE = 1024;
private static final String SEPARATOR = "-";
private static final int LARGE_NUMBER = 65536; // 64k nodes ought to be enough for anybody.
private final NonBlockingHashSet<InetAddress> queuedDeliveries = new NonBlockingHashSet<InetAddress>();
private final ExecutorService executor_ = new JMXEnabledThreadPoolExecutor("HintedHandoff");
public HintedHandOffManager()
{
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try
{
mbs.registerMBean(this, new ObjectName("org.apache.cassandra.db:type=HintedHandoffManager"));
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void registerMBean()
{
logger_.debug("Created HHOM instance, registered MBean.");
}
private static boolean sendMutation(InetAddress endpoint, RowMutation mutation) throws IOException
{
IWriteResponseHandler responseHandler = WriteResponseHandler.create(endpoint);
MessagingService.instance().sendRR(mutation, endpoint, responseHandler);
try
{
responseHandler.get();
}
catch (TimeoutException e)
{
return false;
}
try
{
Thread.sleep(DatabaseDescriptor.getHintedHandoffThrottleDelay());
}
catch (InterruptedException e)
{
throw new AssertionError(e);
}
return true;
}
private static void deleteHint(ByteBuffer tokenBytes, ByteBuffer hintId, long timestamp) throws IOException
{
RowMutation rm = new RowMutation(Table.SYSTEM_TABLE, tokenBytes);
rm.delete(new QueryPath(HINTS_CF, hintId), timestamp);
rm.apply();
}
public void deleteHintsForEndpoint(final String ipOrHostname)
{
try
{
InetAddress endpoint = InetAddress.getByName(ipOrHostname);
deleteHintsForEndpoint(endpoint);
}
catch (UnknownHostException e)
{
logger_.warn("Unable to find "+ipOrHostname+", not a hostname or ipaddr of a node?:");
e.printStackTrace();
throw new RuntimeException(e);
}
}
public void deleteHintsForEndpoint(final InetAddress endpoint)
{
if (!StorageService.instance.getTokenMetadata().isMember(endpoint))
return;
Token<?> token = StorageService.instance.getTokenMetadata().getToken(endpoint);
ByteBuffer tokenBytes = StorageService.getPartitioner().getTokenFactory().toByteArray(token);
final ColumnFamilyStore hintStore = Table.open(Table.SYSTEM_TABLE).getColumnFamilyStore(HINTS_CF);
final RowMutation rm = new RowMutation(Table.SYSTEM_TABLE, tokenBytes);
rm.delete(new QueryPath(HINTS_CF), System.currentTimeMillis());
// execute asynchronously to avoid blocking caller (which may be processing gossip)
Runnable runnable = new Runnable()
{
public void run()
{
try
{
logger_.info("Deleting any stored hints for " + endpoint);
rm.apply();
hintStore.forceFlush();
CompactionManager.instance.submitMaximal(hintStore, Integer.MAX_VALUE);
}
catch (Exception e)
{
logger_.warn("Could not delete hints for " + endpoint + ": " + e);
}
}
};
StorageService.tasks.execute(runnable);
}
private static boolean pagingFinished(ColumnFamily hintColumnFamily, ByteBuffer startColumn)
{
// done if no hints found or the start column (same as last column processed in previous iteration) is the only one
return hintColumnFamily == null
|| (hintColumnFamily.getSortedColumns().size() == 1 && hintColumnFamily.getColumn(startColumn) != null);
}
private int waitForSchemaAgreement(InetAddress endpoint) throws InterruptedException
{
Gossiper gossiper = Gossiper.instance;
int waited = 0;
// first, wait for schema to be gossiped.
while (gossiper.getEndpointStateForEndpoint(endpoint).getApplicationState(ApplicationState.SCHEMA) == null) {
Thread.sleep(1000);
waited += 1000;
if (waited > 2 * StorageService.RING_DELAY)
throw new RuntimeException("Didin't receive gossiped schema from " + endpoint + " in " + 2 * StorageService.RING_DELAY + "ms");
}
waited = 0;
// then wait for the correct schema version.
// usually we use DD.getDefsVersion, which checks the local schema uuid as stored in the system table.
// here we check the one in gossip instead; this serves as a canary to warn us if we introduce a bug that
// causes the two to diverge (see CASSANDRA-2946)
while (!gossiper.getEndpointStateForEndpoint(endpoint).getApplicationState(ApplicationState.SCHEMA).value.equals(
gossiper.getEndpointStateForEndpoint(FBUtilities.getBroadcastAddress()).getApplicationState(ApplicationState.SCHEMA).value))
{
Thread.sleep(1000);
waited += 1000;
if (waited > 2 * StorageService.RING_DELAY)
throw new RuntimeException("Could not reach schema agreement with " + endpoint + " in " + 2 * StorageService.RING_DELAY + "ms");
}
logger_.debug("schema for {} matches local schema", endpoint);
return waited;
}
private void deliverHintsToEndpoint(InetAddress endpoint) throws IOException, DigestMismatchException, InvalidRequestException, TimeoutException, InterruptedException
{
try
{
logger_.debug("Checking remote({}) schema before delivering hints", endpoint);
int waited = waitForSchemaAgreement(endpoint);
// sleep a random amount to stagger handoff delivery from different replicas.
// (if we had to wait, then gossiper randomness took care of that for us already.)
if (waited == 0) {
int sleep = new Random().nextInt(60000);
logger_.debug("Sleeping {}ms to stagger hint delivery", sleep);
Thread.sleep(sleep);
}
if (!FailureDetector.instance.isAlive(endpoint))
{
logger_.info("Endpoint {} died before hint delivery, aborting", endpoint);
return;
}
}
finally
{
queuedDeliveries.remove(endpoint);
}
// 1. Get the key of the endpoint we need to handoff
// 2. For each column, deserialize the mutation and send it to the endpoint
// 3. Delete the subcolumn if the write was successful
// 4. Force a flush
// 5. Do major compaction to clean up all deletes etc.
// find the hints for the node using its token.
Token<?> token = StorageService.instance.getTokenMetadata().getToken(endpoint);
logger_.info("Started hinted handoff for token: {} with IP: {}", token, endpoint);
ByteBuffer tokenBytes = StorageService.getPartitioner().getTokenFactory().toByteArray(token);
DecoratedKey<?> epkey = StorageService.getPartitioner().decorateKey(tokenBytes);
int rowsReplayed = 0;
ColumnFamilyStore hintStore = Table.open(Table.SYSTEM_TABLE).getColumnFamilyStore(HINTS_CF);
ByteBuffer startColumn = ByteBufferUtil.EMPTY_BYTE_BUFFER;
delivery:
while (true)
{
QueryFilter filter = QueryFilter.getSliceFilter(epkey, new QueryPath(HINTS_CF), startColumn, ByteBufferUtil.EMPTY_BYTE_BUFFER, false, PAGE_SIZE);
ColumnFamily hintColumnFamily = ColumnFamilyStore.removeDeleted(hintStore.getColumnFamily(filter), Integer.MAX_VALUE);
if (pagingFinished(hintColumnFamily, startColumn))
break;
for (IColumn hint : hintColumnFamily.getSortedColumns())
{
startColumn = hint.name();
IColumn versionColumn = hint.getSubColumn(ByteBufferUtil.bytes("version"));
IColumn tableColumn = hint.getSubColumn(ByteBufferUtil.bytes("table"));
IColumn keyColumn = hint.getSubColumn(ByteBufferUtil.bytes("key"));
IColumn mutationColumn = hint.getSubColumn(ByteBufferUtil.bytes("mutation"));
assert versionColumn != null;
assert tableColumn != null;
assert keyColumn != null;
assert mutationColumn != null;
DataInputStream in = new DataInputStream(ByteBufferUtil.inputStream(mutationColumn.value()));
RowMutation rm = RowMutation.serializer().deserialize(in, ByteBufferUtil.toInt(versionColumn.value()));
if (sendMutation(endpoint, rm))
{
deleteHint(tokenBytes, hint.name(), versionColumn.timestamp());
rowsReplayed++;
}
else
{
logger_.info("Could not complete hinted handoff to " + endpoint);
break delivery;
}
}
}
if (rowsReplayed > 0)
{
hintStore.forceFlush();
try
{
CompactionManager.instance.submitMaximal(hintStore, Integer.MAX_VALUE).get();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
logger_.info(String.format("Finished hinted handoff of %s rows to endpoint %s",
rowsReplayed, endpoint));
}
/*
* This method is used to deliver hints to a particular endpoint.
* When we learn that some endpoint is back up we deliver the data
* to him via an event driven mechanism.
*/
public void deliverHints(final InetAddress to)
{
if (!queuedDeliveries.add(to))
return;
Runnable r = new WrappedRunnable()
{
public void runMayThrow() throws Exception
{
deliverHintsToEndpoint(to);
}
};
executor_.execute(r);
}
public void deliverHints(String to) throws UnknownHostException
{
deliverHints(InetAddress.getByName(to));
}
public List<String> listEndpointsPendingHints()
{
List<Row> rows = getHintsSlice(1);
// Extract the keys as strings to be reported.
LinkedList<String> result = new LinkedList<String>();
for (Row r : rows)
{
if (r.cf != null) //ignore removed rows
result.addFirst(new String(r.key.key.array()));
}
return result;
}
public Map<String, Integer> countPendingHints()
{
List<Row> rows = getHintsSlice(Integer.MAX_VALUE);
Map<String, Integer> result = new HashMap<String, Integer>();
for (Row r : rows)
{
if (r.cf != null) //ignore removed rows
result.put(new String(r.key.key.array()), r.cf.getColumnCount());
}
return result;
}
private List<Row> getHintsSlice(int column_count)
{
// ColumnParent for HintsCF...
ColumnParent parent = new ColumnParent(HINTS_CF);
// Get count # of columns...
SlicePredicate predicate = new SlicePredicate();
SliceRange sliceRange = new SliceRange();
sliceRange.setStart(new byte[0]).setFinish(new byte[0]);
sliceRange.setCount(column_count);
predicate.setSlice_range(sliceRange);
// From keys "" to ""...
IPartitioner<?> partitioner = StorageService.getPartitioner();
ByteBuffer empty = ByteBufferUtil.EMPTY_BYTE_BUFFER;
Range range = new Range(partitioner.getToken(empty), partitioner.getToken(empty));
// Get a bunch of rows!
List<Row> rows;
try
{
rows = StorageProxy.getRangeSlice(new RangeSliceCommand("system", parent, predicate, range, LARGE_NUMBER), ConsistencyLevel.ONE);
}
catch (Exception e)
{
logger_.info("HintsCF getEPPendingHints timed out.");
throw new RuntimeException(e);
}
return rows;
}
}
|
segfault/apache_cassandra
|
src/java/org/apache/cassandra/db/HintedHandOffManager.java
|
Java
|
apache-2.0
| 15,835 |
/*
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.
*/
namespace NetFreeSwitch.Framework.FreeSwitch.Commands {
/// <summary>
/// DivertEvent
/// </summary>
public class DivertEventsCommand : BaseCommand {
private readonly bool _flag;
public DivertEventsCommand(bool flag) { _flag = flag; }
public override string Command { get { return "divert_events"; } }
public override string Argument { get { return _flag ? "on" : "off"; } }
}
}
|
Tochemey/NetFreeSwitch.Framework
|
NetFreeSwitch.Framework/FreeSwitch/Commands/DivertEventsCommand.cs
|
C#
|
apache-2.0
| 1,199 |
# Copyright (c) 2010-2011 OpenStack, 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.
import json
from lxml import etree
from keystone.logic.types import fault
class User(object):
"""Document me!"""
def __init__(self, password=None, id=None, name=None, tenant_id=None,
email=None, enabled=None, tenant_roles=None):
self.id = id
self.name = name
self.tenant_id = tenant_id
self.password = password
self.email = email
self.enabled = enabled and True or False
self.tenant_roles = tenant_roles
@staticmethod
def from_xml(xml_str):
try:
dom = etree.Element("root")
dom.append(etree.fromstring(xml_str))
root = dom.find("{http://docs.openstack.org/identity/api/v2.0}" \
"user")
if root == None:
raise fault.BadRequestFault("Expecting User")
name = root.get("name")
tenant_id = root.get("tenantId")
email = root.get("email")
password = root.get("password")
enabled = root.get("enabled")
if not name:
raise fault.BadRequestFault("Expecting User")
elif not password:
raise fault.BadRequestFault("Expecting User password")
elif not email:
raise fault.BadRequestFault("Expecting User email")
enabled = enabled is None or enabled.lower() in ["true", "yes"]
return User(password, id, name, tenant_id, email, enabled)
except etree.LxmlError as e:
raise fault.BadRequestFault("Cannot parse User", str(e))
@staticmethod
def from_json(json_str):
try:
obj = json.loads(json_str)
if not "user" in obj:
raise fault.BadRequestFault("Expecting User")
user = obj["user"]
id = user.get('id', None)
name = user.get('name', None)
if not "password" in user:
raise fault.BadRequestFault("Expecting User Password")
password = user["password"]
if (id == None or len(id.strip()) == 0) and (
name == None or len(name.strip()) == 0):
raise fault.BadRequestFault("Expecting User")
elif password == None or len(password.strip()) == 0:
raise fault.BadRequestFault("Expecting User password")
if "tenantId" in user:
tenant_id = user["tenantId"]
else:
tenant_id = None
if "email" not in user:
raise fault.BadRequestFault("Expecting User Email")
email = user["email"]
if "enabled" in user:
set_enabled = user["enabled"]
if not isinstance(set_enabled, bool):
raise fault.BadRequestFault("Bad enabled attribute!")
else:
set_enabled = True
return User(password, id, name, tenant_id, email, set_enabled)
except (ValueError, TypeError) as e:
raise fault.BadRequestFault("Cannot parse Tenant", str(e))
def to_dom(self):
dom = etree.Element("user",
xmlns="http://docs.openstack.org/identity/api/v2.0")
if self.email:
dom.set("email", unicode(self.email))
if self.tenant_id:
dom.set("tenantId", unicode(self.tenant_id))
if self.id:
dom.set("id", unicode(self.id))
if self.name:
dom.set("name", unicode(self.name))
if self.enabled:
dom.set("enabled", unicode(self.enabled).lower())
if self.password:
dom.set("password", unicode(self.password))
if self.tenant_roles:
dom_roles = etree.Element("tenantRoles")
for role in self.tenant_roles:
dom_role = etree.Element("tenantRole")
dom_role.text = role
dom_roles.append(dom_role)
dom.append(dom_roles)
return dom
def to_xml(self):
return etree.tostring(self.to_dom())
def to_dict(self):
user = {}
if self.id:
user["id"] = unicode(self.id)
if self.name:
user["name"] = unicode(self.name)
if self.tenant_id:
user["tenantId"] = unicode(self.tenant_id)
if self.password:
user["password"] = unicode(self.password)
user["email"] = unicode(self.email)
user["enabled"] = self.enabled
if self.tenant_roles:
user["tenantRoles"] = list(self.tenant_roles)
return {'user': user}
def to_json(self):
return json.dumps(self.to_dict())
class User_Update(object):
"""Document me!"""
def __init__(self, password=None, id=None, name=None, tenant_id=None,
email=None, enabled=None):
self.id = id
self.name = name
self.tenant_id = tenant_id
self.password = password
self.email = email
self.enabled = bool(enabled) if enabled is not None else None
@staticmethod
def from_xml(xml_str):
try:
dom = etree.Element("root")
dom.append(etree.fromstring(xml_str))
root = dom.find("{http://docs.openstack.org/identity/api/v2.0}" \
"user")
if root == None:
raise fault.BadRequestFault("Expecting User")
id = root.get("id")
name = root.get("name")
tenant_id = root.get("tenantId")
email = root.get("email")
password = root.get("password")
enabled = root.get("enabled")
if enabled == None or enabled == "true" or enabled == "yes":
set_enabled = True
elif enabled == "false" or enabled == "no":
set_enabled = False
else:
raise fault.BadRequestFault("Bad enabled attribute!")
# TODO: WTF is this?!
if password == '':
password = id
return User(password=password, id=id, name=name,
tenant_id=tenant_id, email=email, enabled=set_enabled)
except etree.LxmlError as e:
raise fault.BadRequestFault("Cannot parse User", str(e))
@staticmethod
def from_json(json_str):
try:
obj = json.loads(json_str)
if not "user" in obj:
raise fault.BadRequestFault("Expecting User")
user = obj["user"]
id = user.get('id', None)
name = user.get('name', None)
password = user.get('password', None)
tenant_id = user.get('tenantId', None)
email = user.get('email', None)
enabled = user.get('enabled', True)
if not isinstance(enabled, bool):
raise fault.BadRequestFault("Bad enabled attribute!")
# TODO: WTF is this?!
if password == '':
password = id
return User(password, id, name, tenant_id, email, enabled)
except (ValueError, TypeError) as e:
raise fault.BadRequestFault("Cannot parse Tenant", str(e))
def to_dom(self):
dom = etree.Element("user",
xmlns="http://docs.openstack.org/identity/api/v2.0")
if self.email:
dom.set("email", unicode(self.email))
if self.tenant_id:
dom.set("tenantId", unicode(self.tenant_id))
if self.id:
dom.set("id", unicode(self.id))
if self.name:
dom.set("name", unicode(self.name))
if self.enabled is not None:
dom.set("enabled", unicode(self.enabled).lower())
if self.password:
dom.set("password", unicode(self.password))
return dom
def to_xml(self):
return etree.tostring(self.to_dom())
def to_dict(self):
user = {}
if self.id:
user["id"] = unicode(self.id)
if self.name:
user["name"] = unicode(self.name)
if self.tenant_id:
user["tenantId"] = unicode(self.tenant_id)
if self.password:
user["password"] = unicode(self.password)
if self.email:
user["email"] = unicode(self.email)
if self.enabled is not None:
user["enabled"] = self.enabled
return {'user': user}
def to_json(self):
return json.dumps(self.to_dict())
class Users(object):
"""A collection of users."""
def __init__(self, values, links):
self.values = values
self.links = links
def to_xml(self):
dom = etree.Element("users")
dom.set(u"xmlns", "http://docs.openstack.org/identity/api/v2.0")
for t in self.values:
dom.append(t.to_dom())
for t in self.links:
dom.append(t.to_dom())
return etree.tostring(dom)
def to_json(self):
values = [t.to_dict()["user"] for t in self.values]
links = [t.to_dict()["links"] for t in self.links]
return json.dumps({"users": values, "users_links": links})
|
genius1611/Keystone
|
keystone/logic/types/user.py
|
Python
|
apache-2.0
| 9,678 |
// Copyright 2022 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package storage
import (
"context"
"github.com/apigee/registry/server/registry/internal/storage/models"
"github.com/apigee/registry/server/registry/names"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gorm.io/gorm"
)
func (c *Client) GetProject(ctx context.Context, name names.Project) (*models.Project, error) {
v := new(models.Project)
if err := c.db.Take(v, "key = ?", name.String()).Error; err == gorm.ErrRecordNotFound {
return nil, status.Errorf(codes.NotFound, "%q not found in database", name)
} else if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return v, nil
}
func (c *Client) GetApi(ctx context.Context, name names.Api) (*models.Api, error) {
v := new(models.Api)
if err := c.db.Take(v, "key = ?", name.String()).Error; err == gorm.ErrRecordNotFound {
return nil, status.Errorf(codes.NotFound, "%q not found in database", name)
} else if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return v, nil
}
func (c *Client) GetVersion(ctx context.Context, name names.Version) (*models.Version, error) {
v := new(models.Version)
if err := c.db.Take(v, "key = ?", name.String()).Error; err == gorm.ErrRecordNotFound {
return nil, status.Errorf(codes.NotFound, "%q not found in database", name)
} else if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return v, nil
}
func (c *Client) GetSpec(ctx context.Context, name names.Spec) (*models.Spec, error) {
name = name.Normal()
op := c.db.
Where("project_id = ?", name.ProjectID).
Where("api_id = ?", name.ApiID).
Where("version_id = ?", name.VersionID).
Where("spec_id = ?", name.SpecID).
Order("revision_create_time desc")
v := new(models.Spec)
if err := op.First(v).Error; err == gorm.ErrRecordNotFound {
return nil, status.Errorf(codes.NotFound, "%q not found in database", name)
} else if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return v, nil
}
func (c *Client) GetSpecRevision(ctx context.Context, name names.SpecRevision) (*models.Spec, error) {
name, err := c.unwrapSpecRevisionTag(ctx, name)
if err != nil {
return nil, err
}
v := new(models.Spec)
if err := c.db.Take(v, "key = ?", name.String()).Error; err == gorm.ErrRecordNotFound {
return nil, status.Errorf(codes.NotFound, "%q not found in database", name)
} else if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return v, nil
}
func (c *Client) GetSpecRevisionContents(ctx context.Context, name names.SpecRevision) (*models.Blob, error) {
name, err := c.unwrapSpecRevisionTag(ctx, name)
if err != nil {
return nil, err
}
v := new(models.Blob)
if err := c.db.Take(v, "key = ?", name.String()).Error; err == gorm.ErrRecordNotFound {
return nil, status.Errorf(codes.NotFound, "%q not found in database", name)
} else if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return v, nil
}
func (c *Client) GetDeployment(ctx context.Context, name names.Deployment) (*models.Deployment, error) {
name = name.Normal()
op := c.db.
Where("project_id = ?", name.ProjectID).
Where("api_id = ?", name.ApiID).
Where("deployment_id = ?", name.DeploymentID).
Order("revision_create_time desc")
v := new(models.Deployment)
if err := op.First(v).Error; err == gorm.ErrRecordNotFound {
return nil, status.Errorf(codes.NotFound, "%q not found in database", name)
} else if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return v, nil
}
func (c *Client) GetDeploymentRevision(ctx context.Context, name names.DeploymentRevision) (*models.Deployment, error) {
name, err := c.unwrapDeploymentRevisionTag(ctx, name)
if err != nil {
return nil, err
}
v := new(models.Deployment)
if err := c.db.Take(v, "key = ?", name.String()).Error; err == gorm.ErrRecordNotFound {
return nil, status.Errorf(codes.NotFound, "%q not found in database", name)
} else if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return v, nil
}
func (c *Client) GetArtifact(ctx context.Context, name names.Artifact) (*models.Artifact, error) {
v := new(models.Artifact)
if err := c.db.Take(v, "key = ?", name.String()).Error; err == gorm.ErrRecordNotFound {
return nil, status.Errorf(codes.NotFound, "%q not found in database", name)
} else if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return v, nil
}
func (c *Client) GetArtifactContents(ctx context.Context, name names.Artifact) (*models.Blob, error) {
v := new(models.Blob)
if err := c.db.Take(v, "key = ?", name.String()).Error; err == gorm.ErrRecordNotFound {
return nil, status.Errorf(codes.NotFound, "%q not found in database", name)
} else if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return v, nil
}
|
apigee/registry
|
server/registry/internal/storage/get.go
|
GO
|
apache-2.0
| 5,445 |
package com.cody.app.framework.hybrid.core;
import com.cody.xf.common.NotProguard;
/**
* Created by cody.yi on 2017/4/13.
* 所有Js处理类实现这个接口
* Js调用的方法必须按照一定的格式定义,否则不生效
* 格式:
* public static void ***(WebView webView, JsonObject data, JsCallback callback){}
*/
@NotProguard
public interface JsHandler {
}
|
codyer/CleanFramework
|
app/src/main/java/com/cody/app/framework/hybrid/core/JsHandler.java
|
Java
|
apache-2.0
| 380 |
var SPI = require('spi');
var extend = require('util')._extend;
var openSpi = function() {
var device = '/dev/spidev0.0';
return new SPI.Spi(device, [], function(s) {
s.open();
});
};
var Adc = function(options) {
var self = this;
var settings = extend( {
voltage: 3.3, //3.3V by default
spi: null
}, options);
self.voltage = settings.voltage;
self.spi = settings.spi || openSpi();
/**
* Read voltage (in a range 0-3.3V by default).
* @param channel
* @param callback
*/
self.readVoltage = function(channel, callback) {
self.readSpi(channel, function(value) {
var voltage = ((value * self.voltage) / self.maxValue);
callback(voltage);
});
};
/**
* Read normalized value (in a range 0-1).
* @param channel
* @param callback
*/
self.readNormalizedValue = function(channel, callback) {
self.readSpi(channel, function(value) {
var normalizedValue = ((value) / self.maxValue);
callback(normalizedValue);
});
};
/**
* Read raw ADC value (the range depends on ADC resolution).
* @param channel
* @param callback
*/
self.readRawValue = function(channel, callback) {
self.readSpi(channel, callback);
}
};
module.exports.Mcp3208 = function(options) {
var self = this;
Adc.call(self, options);
self.maxValue = 4095;
self.readSpi = function(channel, callback) {
var tx = new Buffer([4 | 2 | (channel >> 2), (channel & 3) << 6, 0]);
var rx = new Buffer([0, 0, 0]);
self.spi.transfer(tx, rx, function(dev, buffer) {
var value = ((buffer[1] & 15) << 8) + buffer[2];
callback(value);
})
};
};
module.exports.Mcp3008 = function(options) {
var self = this;
Adc.call(self, options);
self.maxValue = 1023;
self.readSpi = function(channel, callback) {
var tx = new Buffer([1, (8 + channel) << 4, 0]);
var rx = new Buffer([0, 0, 0]);
self.spi.transfer(tx, rx, function(dev, buffer) {
var value = ((buffer[1] & 3) << 8) + buffer[2];
callback(value);
})
};
};
|
anha1/mcp-adc
|
mcp-adc.js
|
JavaScript
|
apache-2.0
| 2,219 |
<?php
@session_start();
@require_once("db.php");
@header("Content-Type: application/json; charset=utf8");
if(!empty($_SESSION['username'])) {
$username = $_SESSION['username'];
$cn = connect();
$valid = true;
$isPasswordCorrect = false;
$message = "";
// Checking form data.
if(!empty($_POST['changePasswordNewPassword'])) {
$newPassword = $_POST['changePasswordNewPassword'];
} else {
$valid = false;
$message .= "No new password received.<br>";
}
if(!empty($_POST['changePasswordConfirmPassword'])) {
$cpassword = $_POST['changePasswordConfirmPassword'];
} else {
$valid = false;
$message .= "No confirm password received.<br>";
}
if((!empty($newPassword) && !empty($cpassword)) && ($newPassword != $cpassword)) {
$valid = false;
$message .= "New password and confirm password is mismatch.<br>";
}
if(!empty($_POST['changePasswordOldPassword'])) {
$oldPassword = $_POST['changePasswordOldPassword'];
$rs = @mysql_query("SELECT COUNT(*) FROM `user` WHERE `username`='" . $username . "' AND `password`='" . md5($oldPassword) . "';", $cn);
$n = (int) @mysql_result($rs, 0, 0);
if($n == 1) {
$isPasswordCorrect = true;
}
} else {
$valid = false;
$message .= "No old password received.<br>";
}
if($valid) {
if($isPasswordCorrect) {
// Changing password.
$encNewPassword = md5($newPassword);
$encOldPassword = md5($oldPassword);
$query = <<<QUERY
UPDATE `user` SET `password`='$encNewPassword' WHERE `username`='$username' AND `password`='$encOldPassword';
QUERY;
if(@mysql_query($query, $cn)) {
$result = array(
"result" => "success"
);
} else {
$result = array(
"result" => "fail"
);
}
} else {
$result = array(
"result" => "incorrect_pass"
);
}
} else {
$result = array(
"result" => $message
);
}
disconnect($cn);
} else {
$result = array(
"result" => "fail"
);
}
echo(json_encode($result));
?>
|
gluons/Cooking-Community
|
changepassword.php
|
PHP
|
apache-2.0
| 1,922 |
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from sqlalchemy import Column, ForeignKey, CheckConstraint, \
PrimaryKeyConstraint, func, or_, and_, true, literal_column, \
select, cast, TEXT
from sqlalchemy.orm import relationship, backref, Query
from sqlalchemy.types import BigInteger, Enum, Integer
from pycroft.model.base import ModelBase
from pycroft.model.ddl import DDLManager, Function, Trigger, View
from pycroft.model.types import DateTimeTz
from pycroft.model.user import User
from pycroft.model.host import IP, Host, Interface
ddl = DDLManager()
class TrafficEvent:
timestamp = Column(DateTimeTz, server_default=func.current_timestamp(), nullable=False)
amount = Column(BigInteger, CheckConstraint('amount >= 0'),
nullable=False)
class TrafficVolume(TrafficEvent, ModelBase):
__table_args__ = (
PrimaryKeyConstraint('ip_id', 'type', 'timestamp'),
)
type = Column(Enum("Ingress", "Egress", name="traffic_direction"),
nullable=False)
ip_id = Column(Integer, ForeignKey(IP.id, ondelete="CASCADE"),
nullable=False, index=True)
ip = relationship(IP, backref=backref("traffic_volumes",
cascade="all, delete-orphan",
cascade_backrefs=False))
user_id = Column(Integer, ForeignKey(User.id, ondelete='CASCADE'),
nullable=True, index=True)
user = relationship(User,
backref=backref("traffic_volumes",
cascade="all, delete-orphan",
cascade_backrefs=False),
uselist=False)
packets = Column(Integer, CheckConstraint('packets >= 0'),
nullable=False)
TrafficVolume.__table__.add_is_dependent_on(IP.__table__)
pmacct_traffic_egress = View(
name='pmacct_traffic_egress',
query=(
Query([])
.add_columns(TrafficVolume.packets.label('packets'),
TrafficVolume.amount.label('bytes'),
TrafficVolume.timestamp.label('stamp_inserted'),
TrafficVolume.timestamp.label('stamp_updated'),
IP.address.label('ip_src'))
.select_from(TrafficVolume)
.filter_by(type='Egress')
.join(IP)
.statement # turns our `Selectable` into something compilable
),
)
ddl.add_view(TrafficVolume.__table__, pmacct_traffic_egress)
pmacct_expression_replacements = dict(
tv_tname=TrafficVolume.__tablename__,
tv_type=TrafficVolume.type.key,
tv_ip_id=TrafficVolume.ip_id.key,
tv_timestamp=TrafficVolume.timestamp.key,
tv_amount=TrafficVolume.amount.key,
tv_packets=TrafficVolume.packets.key,
tv_user_id=TrafficVolume.user_id.key,
ip_tname=IP.__tablename__,
ip_id=str(IP.id.expression),
ip_interface_id=str(IP.interface_id.expression),
ip_address=str(IP.address.expression),
host_tname=Host.__tablename__,
host_id=str(Host.id.expression),
host_owner_id=str(Host.owner_id.expression),
interface_tname=Interface.__tablename__,
interface_id=str(Interface.id.expression),
interface_host_id=str(Interface.host_id.expression),
)
pmacct_egress_upsert = Function(
name="pmacct_traffic_egress_insert", arguments=[], language="plpgsql", rtype="trigger",
definition="""BEGIN
INSERT INTO traffic_volume ({tv_type}, {tv_ip_id}, "{tv_timestamp}", {tv_amount}, {tv_packets}, {tv_user_id})
SELECT
'Egress',
{ip_id},
date_trunc('day', NEW.stamp_inserted),
NEW.bytes,
NEW.packets,
{host_owner_id}
FROM {ip_tname}
JOIN {interface_tname} ON {ip_interface_id} = {interface_id}
JOIN {host_tname} ON {interface_host_id} = {host_id}
WHERE NEW.ip_src = {ip_address}
ON CONFLICT ({tv_ip_id}, {tv_type}, "{tv_timestamp}")
DO UPDATE SET ({tv_amount}, {tv_packets}) = ({tv_tname}.{tv_amount} + NEW.bytes,
{tv_tname}.{tv_packets} + NEW.packets);
RETURN NULL;
END;""".format(**pmacct_expression_replacements),
)
pmacct_egress_upsert_trigger = Trigger(
name='pmacct_traffic_egress_insert_trigger', table=pmacct_traffic_egress.table,
events=["INSERT"], function_call="pmacct_traffic_egress_insert()", when="INSTEAD OF"
)
ddl.add_function(TrafficVolume.__table__, pmacct_egress_upsert)
ddl.add_trigger(TrafficVolume.__table__, pmacct_egress_upsert_trigger)
pmacct_traffic_ingress = View(
name='pmacct_traffic_ingress',
query=(
Query([])
.add_columns(TrafficVolume.packets.label('packets'),
TrafficVolume.amount.label('bytes'),
TrafficVolume.timestamp.label('stamp_inserted'),
TrafficVolume.timestamp.label('stamp_updated'),
IP.address.label('ip_dst'))
.select_from(TrafficVolume)
.filter_by(type='Ingress')
.join(IP)
.statement # turns our `Selectable` into something compilable
),
)
ddl.add_view(TrafficVolume.__table__, pmacct_traffic_ingress)
pmacct_ingress_upsert = Function(
name="pmacct_traffic_ingress_insert", arguments=[], language="plpgsql", rtype="trigger",
definition="""BEGIN
INSERT INTO traffic_volume ({tv_type}, {tv_ip_id}, "{tv_timestamp}", {tv_amount}, {tv_packets}, {tv_user_id})
SELECT
'Ingress',
{ip_id},
date_trunc('day', NEW.stamp_inserted),
NEW.bytes,
NEW.packets,
{host_owner_id}
FROM {ip_tname}
JOIN {interface_tname} ON {ip_interface_id} = {interface_id}
JOIN {host_tname} ON {interface_host_id} = {host_id}
WHERE NEW.ip_dst = {ip_address}
ON CONFLICT ({tv_ip_id}, {tv_type}, "{tv_timestamp}")
DO UPDATE SET ({tv_amount}, {tv_packets}) = ({tv_tname}.{tv_amount} + NEW.bytes,
{tv_tname}.{tv_packets} + NEW.packets);
RETURN NULL;
END;""".format(**pmacct_expression_replacements),
)
pmacct_ingress_upsert_trigger = Trigger(
name='pmacct_traffic_ingress_insert_trigger', table=pmacct_traffic_ingress.table,
events=["INSERT"], function_call="pmacct_traffic_ingress_insert()", when="INSTEAD OF"
)
ddl.add_function(TrafficVolume.__table__, pmacct_ingress_upsert)
ddl.add_trigger(TrafficVolume.__table__, pmacct_ingress_upsert_trigger)
def traffic_history_query():
events = (select(func.sum(TrafficVolume.amount).label('amount'),
literal_column('day'),
cast(TrafficVolume.type, TEXT).label('type')
)
.select_from(
func.generate_series(
func.date_trunc('day', literal_column('arg_start')),
func.date_trunc('day', literal_column('arg_end')),
'1 day'
).alias('day')
.outerjoin(TrafficVolume.__table__, and_(
func.date_trunc('day', TrafficVolume.timestamp) == literal_column('day'),
TrafficVolume.user_id == literal_column('arg_user_id'))
)
)
.group_by(literal_column('day'), literal_column('type'))
).cte()
events_ingress = select(events).where(or_(events.c.type == 'Ingress', events.c.type == None)).cte()
events_egress = select(events).where(or_(events.c.type == 'Egress', events.c.type == None)).cte()
hist = (select(func.coalesce(events_ingress.c.day, events_egress.c.day).label('timestamp'),
events_ingress.c.amount.label('ingress'),
events_egress.c.amount.label('egress'))
.select_from(events_ingress.join(events_egress,
events_ingress.c.day == events_egress.c.day,
full=true))
.order_by(literal_column('timestamp'))
)
return hist
traffic_history_function = Function(
'traffic_history', ['arg_user_id int', 'arg_start timestamptz', 'arg_end timestamptz'],
'TABLE ("timestamp" timestamptz, ingress numeric, egress numeric)',
definition=traffic_history_query(),
volatility='stable',
)
ddl.add_function(
TrafficVolume.__table__,
traffic_history_function
)
class TrafficHistoryEntry:
def __init__(self, timestamp, ingress, egress):
self.timestamp = timestamp
self.ingress = ingress or 0
self.egress = egress or 0
def __repr__(self):
return str(self.__dict__)
ddl.register()
|
agdsn/pycroft
|
pycroft/model/traffic.py
|
Python
|
apache-2.0
| 8,996 |
# Copyright (c) 2013 MaestroDev. All rights reserved.
require 'maestro_plugin'
require 'maestro_shell'
require 'open-uri'
require 'xmlsimple'
module MaestroDev
module Plugin
class MavenWorker < Maestro::MaestroWorker
def execute
validate_execute_parameters
Maestro.log.info "Inputs: goals = #{@goals}"
Maestro.log.debug "Using Maven version #{@mvn_version}" if !@mvn_version.empty?
shell = Maestro::Util::Shell.new
command = create_command
shell.create_script(command)
write_output("\nRunning command:\n----------\n#{command.chomp}\n----------\n")
exit_code = shell.run_script_with_delegate(self, :on_output)
if !exit_code.success?
# Error executing maven
# Lets see if we can make the error a little more specific.
# Maven thoughtfully prefixes all lines with [ERROR] that might be useful to us...
# so lets iunclude them in the error
error_lines = shell.output.split(/\r\n|\n/).select { |line| line.start_with?('[ERROR]') }
raise PluginError, "Maven failed executing goal list '#{@goals.empty? ? '[default]' : @goals}'\n" + error_lines.join("\n")
end
end
def wget_latest_snapshot
validate_snapshot_parameters
Maestro.log.info "Inputs: path = #{@path}," \
" url = #{@base_url}," \
" packaging = #{@packaging}"
maven_metadata_xml = get_maven_metadata_xml
artifactId = maven_metadata_xml["artifactId"][0]
unless maven_metadata_xml["versioning"].nil? or maven_metadata_xml["versioning"][0]["snapshot"][0]["timestamp"].nil?
buildNumber = maven_metadata_xml["versioning"][0]["snapshot"][0]["buildNumber"][0]
timestamp = maven_metadata_xml["versioning"][0]["snapshot"][0]["timestamp"][0]
version = maven_metadata_xml["version"][0].gsub(/\-SNAPSHOT/,'')
file = "#{artifactId}-#{version}-#{timestamp}-#{buildNumber}.#{@packaging}"
else
version = maven_metadata_xml["version"][0]
file = "#{artifactId}-#{version}.#{@packaging}"
end
url = @base_url + "/#{file}"
Maestro.log.debug "Removing Existing File At #{@path}/#{artifactId}.#{@packaging}"
begin
FileUtils.rm "#{@path}/#{artifactId}.#{@packaging}"
rescue Exception
end
write_output("\nDownloading File From #{url}", :buffer => true)
wget = Maestro::Util::Shell.new
command = "LANG=C #{@wget_executable} --progress=dot #{url} -O #{@path}/#{artifactId}.#{@packaging} --user=#{@username} --password=#{@password}"
wget.create_script(command)
write_output("\nRunning command:\n----------\n#{command.chomp}\n----------\n")
exit_code = wget.run_script_with_delegate(self, :on_output)
write_output("\nDownloaded File #{url} To #{@path}/#{artifactId}.#{@packaging}", :buffer => true) if File.exists? "#{@path}/#{artifactId}.#{@packaging}"
raise PluginError, "Failed to download #{url} to #{@path}/#{artifactId}.#{@packaging}" unless exit_code.success?
end
def on_output(text)
write_output(text, :buffer => true)
end
###########
# PRIVATE #
###########
private
# because we want to be able to string stuff together with &&
# can't really test the executable.
def valid_executable?(executable)
Maestro::Util::Shell.run_command("#{executable} --version")[0].success?
end
def get_version
result = Maestro::Util::Shell.run_command("#{@mvn_executable} -version")
result[1].split("\n")[0].split(' (')[0].split(' ')[2] if result[0].success?
end
def validate_execute_parameters
errors = []
@mvn_executable = get_field('maven_executable', 'mvn')
@mvn_version = get_field('maven_version', '')
@path = get_field('path') || get_field('scm_path')
@goals = get_field('goals', '')
@settingsfile = get_field('settingsfile', '')
@profiles = get_field('profiles', '')
@properties = get_field('properties', '')
@environment = get_field('environment', '')
@env = @environment.empty? ? "" : "#{Maestro::Util::Shell::ENV_EXPORT_COMMAND} #{@environment.gsub(/(&&|[;&])\s*$/, '')} && "
if valid_executable?(@mvn_executable)
if !@mvn_version.empty?
version = get_version
errors << "maven is the wrong version: #{version}. Expected: #{@mvn_version}" if version != @mvn_version
end
else
errors << 'maven not installed'
end
errors << 'missing field path' if @path.nil?
errors << "not found path '#{@path}'" if !@path.nil? && !File.exist?(@path)
if !@settingsfile.empty?
if !File.exists?(@settingsfile)
errors << "specified settings file (#{@settingsfile}) not found"
end
end
process_goals_field
process_profiles_field
process_properties_field
if !errors.empty?
raise ConfigError, "Configuration errors: #{errors.join(', ')}"
end
end
def validate_snapshot_parameters
errors = []
@base_url = get_field('url', '')
@path = get_field('path', '')
@username = get_field('username', '')
@password = get_field('password', '')
@packaging = get_field('packaging', '')
@wget_executable = get_field('wget_executable', 'wget')
errors << 'missing field url' if @base_url.empty?
errors << 'missing field path' if @path.empty?
errors << "path not found '#{@path}'" if !@path.empty? && !File.exist?(@path)
errors << 'missing field username' if @username.empty?
errors << 'missing field password' if @password.empty?
errors << 'missing field packaging' if @packaging.empty?
errors << 'wget not installed' unless valid_executable?(@wget_executable)
if !errors.empty?
raise ConfigError, "Configuration errors: #{errors.join(', ')}"
end
end
def process_goals_field
begin
if is_json(@goals)
@goals = JSON.parse(@goals) if @goals.is_a? String
end
rescue Exception
end
if @goals.is_a? Array
@goals = @goals.join(' ')
end
end
def process_profiles_field
begin
if is_json(@profiles)
@profiles = JSON.parse(@profiles) if @profiles.is_a? String
end
rescue Exception
end
if @profiles.is_a? Array
@profiles.delete_if{ |profile| profile.empty? }
@profiles = @profiles.join(',')
end
Maestro.log.debug "Enabling Maven profiles: #{@profiles}"
@profiles = " -P#{@profiles}" unless @profiles.empty?
end
def process_properties_field
begin
if is_json(@properties)
@properties = JSON.parse(@properties) if @properties.is_a? String
end
rescue Exception
end
if @properties.is_a? Array
@properties.delete_if{ |property| property.empty? }
@properties = @properties.map{|x| "-D#{x}"}.join(' ')
end
Maestro.log.debug "Using Maven properties: #{@properties}"
end
def create_command
settings = "--settings #{@settingsfile} " if !@settingsfile.empty?
shell_command = "#{@env}cd #{@path} && #{@mvn_executable} -B #{settings}#{@goals}#{@profiles} #{@properties}"
set_field('command', shell_command)
Maestro.log.debug("Running #{shell_command}")
shell_command
end
def get_maven_metadata_xml
write_output "\nRequesting maven-metadata.xml With Username #{@username} And Password"
begin
response = open(@base_url + "/maven-metadata.xml", :http_basic_authentication => [@username, @password])
raise PluginError, 'Failed To Retrieve maven-metadata.xml (no response from server)' unless response
case response.status[0]
when "200"
maven_metadata_xml = XmlSimple.xml_in(response.read)
Maestro.log.debug "\nResponse Received #{response.status[0]}\n#{maven_metadata_xml}"
else
raise PluginError, "Failed To Retrieve maven-metadata.xml #{response}"
end
raise PluginError, "Missing Version Or ArtifactID " if maven_metadata_xml["artifactId"].nil? or maven_metadata_xml["version"].nil?
rescue Timeout::Error
raise PluginError, 'Failed To Retrieve maven-metadata.xml (timeout)'
rescue
raise PluginError, 'Failed To Retrieve maven-metadata.xml (unable to connect to server)'
end
maven_metadata_xml
end
end
end
end
|
maestrodev/maestro-maven-plugin
|
src/maven_worker.rb
|
Ruby
|
apache-2.0
| 8,897 |
var nbinput = 1;
var $collectionHolder;
$(function() {
var $alreadyUsed = $("#alreadyExistVar").html();
if ($alreadyUsed) {
showDialog("#some-exists-dialog");
}
// Get the ul that holds the collection of tags
$collectionHolder = $('#inputBlock');
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find('.fileInput').length);
$('#newInputButton').on('click', function(e) {
if (nbinput < 5) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// add a new tag form (see next code block)
addTagForm($collectionHolder);
} else {
showDialog("#limitFileDialog");
}
});
});
$("#confirmOverride").click(function(){
$("#upload-block form").submit();
});
function changeInputFile(element) {
var lineInput = $(element).parent().parent().parent();
var filename = $(element).val();
var n = filename.lastIndexOf('.');
var format = filename.substring(n + 1);
$('.input-format', lineInput).val(format);
$(element).parent().addClass("bg-green");
$(element).parent().removeClass("bg-gray");
}
function addTagForm($collectionHolder) {
// Get the data-prototype explained earlier
var prototype = $collectionHolder.data('prototype');
// get the new index
var index = $collectionHolder.data('index');
// Replace '__name__' in the prototype's HTML to
// instead be a number based on how many items we have
var newForm = prototype.replace(/__name__/g, index);
// increase the index with one for the next item
$collectionHolder.data('index', index + 1);
var $newFormLi = $('<div></div>').append(newForm);
var newBlock =$('<div id="lineInput_' + (index+1) + '" class="row cells12 fileInput"></div>');
$('input', $newFormLi).each(function(index, element){
var name = element.name;
var $block = $('<div class="input-control text full-size"></div>').append(element);
if (contains(name, 'category') || contains(name, 'creator') || contains(name, 'nameAlreadyUsed'))
return;
if (contains(name, 'initials') || contains(name, 'date')) {
$block = $('<div class="cell colspan2"></div>').append($block);
if(contains(name, 'initials')) {
$('input', $block).val("AM");
}
if(contains(name, 'date')) {
$('input', $block).val($('#sw_docmanagerbundle_uploadsession_documents_0_date').val());
}
} else if (contains(name, 'name')) {
$block = $('<div class="cell colspan4"></div>').append($block);
} else if (contains(name, 'format') || contains(name, 'code')) {
$block = $('<div class="cell colspan1"></div>').append($block);
if(contains(name, 'code')) {
$('input', $block).val($('#sw_docmanagerbundle_uploadsession_documents_0_code').val());
$('input', $block).attr("readonly","readonly");
}
if(contains(name, 'format')) {
$('input', $block).attr("class",'input-format');
}
} else if (contains(name, 'file')) {
$('input', $block).attr("onchange",'changeInputFile(this)');
$block = $('<div class="input-control full-size input-file-custom button full-size bg-gray fg-white">Datei</div>').append(element);
$block = $('<div class="cell colspan1"></div>').append($block);
} else {
return true;
}
newBlock.append($block);
});
var $blockRemove = '<div class="cell colspan1 v-align-middle padding10">';
$blockRemove += '<button onclick="removeLine(lineInput_' + (index+1) + ')" class="removeInputButton button mini-button cycle-button">-</button>';
$blockRemove += '</div>';
newBlock.append($blockRemove);
newBlock.hide();
newBlock.appendTo($("#inputBlock")).show("slow");
$("#sw_docmanagerbundle_uploadsession_weiter").prop(
'disabled', ($("#inputBlock").children().length < 1));
}
function contains(text, chartext) {
return text.indexOf(chartext) > -1;
}
function removeLine(id) {
$(id).remove();
$("#sw_docmanagerbundle_uploadsession_weiter").prop(
'disabled', ($("#inputBlock").children().length < 1));
}
|
adrienManikon/docmanager
|
src/SW/DocManagerBundle/Resources/public/js/upload.js
|
JavaScript
|
apache-2.0
| 4,586 |
package org.jfrog.hudson.pipeline.scripted.steps.conan;
import com.google.inject.Inject;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.util.ArgumentListBuilder;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.workflow.steps.AbstractStepDescriptorImpl;
import org.jenkinsci.plugins.workflow.steps.AbstractStepImpl;
import org.jenkinsci.plugins.workflow.steps.AbstractSynchronousStepExecution;
import org.jenkinsci.plugins.workflow.steps.StepContextParameter;
import org.jfrog.hudson.pipeline.common.Utils;
import org.jfrog.hudson.pipeline.common.types.ConanClient;
import org.jfrog.hudson.util.ExtractorUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.File;
import java.util.Calendar;
public class InitConanClientStep extends AbstractStepImpl {
private ConanClient client;
@DataBoundConstructor
public InitConanClientStep(ConanClient client) {
this.client = client;
}
public ConanClient getClient() {
return client;
}
public static class Execution extends AbstractSynchronousStepExecution<Boolean> {
private static final long serialVersionUID = 1L;
@StepContextParameter
private transient Run build;
@StepContextParameter
private transient TaskListener listener;
@StepContextParameter
private transient Launcher launcher;
@Inject(optional = true)
private transient InitConanClientStep step;
@StepContextParameter
private transient FilePath ws;
@StepContextParameter
private transient EnvVars env;
@Override
protected Boolean run() throws Exception {
ConanClient conanClient = getConanClient();
EnvVars extendedEnv = new EnvVars(env);
extendedEnv.put(Utils.CONAN_USER_HOME, conanClient.getUserPath());
ArgumentListBuilder args = new ArgumentListBuilder();
String logFilePath = conanClient.getLogFilePath();
args.addTokenized("conan config set");
// We need to add quotation marks before we save the log file path
args.add("log.trace_file=\"" + StringUtils.trim(logFilePath) + "\"");
Utils.exeConan(args, ws, launcher, listener, build, extendedEnv);
return true;
}
private ConanClient getConanClient() throws Exception {
ConanClient conanClient = step.getClient();
conanClient.setUnixAgent(launcher.isUnix());
FilePath conanHomeDirectory;
if (StringUtils.isEmpty(conanClient.getUserPath())) {
conanHomeDirectory = env.containsKey(Utils.CONAN_USER_HOME) ? new FilePath(new File(env.get(Utils.CONAN_USER_HOME))) : createConanTempHome();
} else {
conanHomeDirectory = new FilePath(launcher.getChannel(), conanClient.getUserPath());
if (!conanHomeDirectory.exists()) {
conanHomeDirectory.mkdirs();
}
}
conanClient.setUserPath(conanHomeDirectory.getRemote());
conanHomeDirectory.child(ConanClient.CONAN_LOG_FILE).touch(Calendar.getInstance().getTimeInMillis());
return conanClient;
}
private FilePath createConanTempHome() throws Exception {
// Create the @tmp directory
FilePath tempDir = ExtractorUtils.createAndGetTempDir(ws);
// Create the conan directory
return tempDir.createTempDir("conan", "");
}
}
@Extension
public static final class DescriptorImpl extends AbstractStepDescriptorImpl {
public DescriptorImpl() {
super(InitConanClientStep.Execution.class);
}
@Override
public String getFunctionName() {
return "initConanClient";
}
@Override
public String getDisplayName() {
return "Create Conan Client";
}
@Override
public boolean isAdvanced() {
return true;
}
}
}
|
AlexeiVainshtein/jenkins-artifactory-plugin
|
src/main/java/org/jfrog/hudson/pipeline/scripted/steps/conan/InitConanClientStep.java
|
Java
|
apache-2.0
| 4,174 |
package it.unibz.inf.ontop.ontology.impl;
/*
* #%L
* ontop-obdalib-core
* %%
* Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano
* %%
* 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 it.unibz.inf.ontop.ontology.DataPropertyExpression;
import it.unibz.inf.ontop.ontology.DataSomeValuesFrom;
import it.unibz.inf.ontop.ontology.Datatype;
/**
* DataSomeValuesFrom in OWL 2 QL Specification
* <p>
* DataSomeValuesFrom := 'DataSomeValuesFrom' '(' DataPropertyExpression DataRange ')'
* <p>
* Implements (partially) rule [D5] in methods isTop and isBottom<br>
* - the class expression is equivalent to top if the property is top (the data range cannot be empty)<br>
* - the class expression is equivalent to bot if the property is bot
*
* @author Roman Kontchakov
*
*/
public class DataSomeValuesFromImpl implements DataSomeValuesFrom {
private static final long serialVersionUID = 593821958539751283L;
private final DataPropertyExpression property;
private final Datatype filler;
private final String string;
DataSomeValuesFromImpl(DataPropertyExpression property, Datatype filler) {
this.property = property;
this.filler = filler;
this.string = new StringBuilder().append("E ").append(property.toString()).append(".")
.append(filler.toString()).toString();
}
@Override
public DataPropertyExpression getProperty() {
return property;
}
@Override
public Datatype getDatatype() {
return filler;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj instanceof DataSomeValuesFromImpl) {
DataSomeValuesFromImpl other = (DataSomeValuesFromImpl) obj;
return property.equals(other.property) && filler.equals(other.filler);
}
return false;
}
@Override
public int hashCode() {
return string.hashCode();
}
@Override
public String toString() {
return string;
}
@Override
public boolean isBottom() {
return property.isBottom();
}
@Override
public boolean isTop() {
return property.isTop();
}
}
|
srapisarda/ontop
|
obdalib-core/src/main/java/it/unibz/inf/ontop/ontology/impl/DataSomeValuesFromImpl.java
|
Java
|
apache-2.0
| 2,538 |
package org.deepjava.runtime.mpc555;
import org.deepjava.runtime.ppc32.Ippc32;
// Auto generated file (2021-02-17 13:57:50)
public interface Impc555 extends Ippc32 {
// System constants of CPU mpc555
public static final int SRR1init = 0x3802;
public static final int stackSize = 0x2000;
public static final int sysTabBaseAddr = 0x4000;
public static final int excpCodeSize = 0x4000;
public static final int excpCodeBase = 0x0;
public static final int CMFB_Size = 0x30000;
public static final int CMFB_BaseAddr = 0x40000;
public static final int CMFA_Size = 0x40000;
public static final int CMFA_BaseAddr = 0x0;
public static final int SRAMB_Size = 0x4000;
public static final int SRAMB_BaseAddr = 0x3fc000;
public static final int SRAMA_Size = 0x2800;
public static final int SRAMA_BaseAddr = 0x3f9800;
public static final int IMB = 0x0;
// Specific registers of CPU mpc555
public static final int SPR80 = 0x50;
public static final int EIE = 0x50;
public static final int SPR81 = 0x51;
public static final int EID = 0x51;
public static final int SPR82 = 0x52;
public static final int NRI = 0x52;
public static final int SPR144 = 0x90;
public static final int CMPA = 0x90;
public static final int SPR145 = 0x91;
public static final int CMPB = 0x91;
public static final int SPR146 = 0x92;
public static final int CMPC = 0x92;
public static final int SPR147 = 0x93;
public static final int CMPD = 0x93;
public static final int SPR148 = 0x94;
public static final int ECR = 0x94;
public static final int SPR149 = 0x95;
public static final int DER = 0x95;
public static final int SPR150 = 0x96;
public static final int COUNTA = 0x96;
public static final int SPR151 = 0x97;
public static final int COUNTB = 0x97;
public static final int SPR152 = 0x98;
public static final int CMPE = 0x98;
public static final int SPR153 = 0x99;
public static final int CMPF = 0x99;
public static final int SPR154 = 0x9a;
public static final int CMPG = 0x9a;
public static final int SPR155 = 0x9b;
public static final int CMPH = 0x9b;
public static final int SPR156 = 0x9c;
public static final int LCTRL1 = 0x9c;
public static final int SPR157 = 0x9d;
public static final int LCTRL2 = 0x9d;
public static final int SPR158 = 0x9e;
public static final int ICTRL = 0x9e;
public static final int SPR159 = 0x9f;
public static final int BAR = 0x9f;
public static final int PVR = 0x11f;
public static final int SPR528 = 0x210;
public static final int MI_GRA = 0x210;
public static final int SPR536 = 0x218;
public static final int L2U_GRA = 0x218;
public static final int SPR560 = 0x230;
public static final int BBCMCR = 0x230;
public static final int SPR568 = 0x238;
public static final int L2U_MCR = 0x238;
public static final int SPR638 = 0x27e;
public static final int IMMR = 0x27e;
public static final int SPR784 = 0x310;
public static final int MI_RBA0 = 0x310;
public static final int SPR785 = 0x311;
public static final int MI_RBA1 = 0x311;
public static final int SPR786 = 0x312;
public static final int MI_RBA2 = 0x312;
public static final int SPR787 = 0x313;
public static final int MI_RBA3 = 0x313;
public static final int SPR792 = 0x318;
public static final int L2U_RBA0 = 0x318;
public static final int SPR793 = 0x319;
public static final int L2U_RBA1 = 0x319;
public static final int SPR794 = 0x31a;
public static final int L2U_RBA2 = 0x31a;
public static final int SPR795 = 0x31b;
public static final int L2U_RBA3 = 0x31b;
public static final int SPR816 = 0x330;
public static final int MI_RA0 = 0x330;
public static final int SPR817 = 0x331;
public static final int MI_RA1 = 0x331;
public static final int SPR818 = 0x332;
public static final int MI_RA2 = 0x332;
public static final int SPR819 = 0x333;
public static final int MI_RA3 = 0x333;
public static final int SPR824 = 0x338;
public static final int L2U_RA0 = 0x338;
public static final int SPR825 = 0x339;
public static final int L2U_RA1 = 0x339;
public static final int SPR826 = 0x33a;
public static final int L2U_RA2 = 0x33a;
public static final int SPR827 = 0x33b;
public static final int L2U_RA3 = 0x33b;
public static final int SPR1022 = 0x3fe;
public static final int FPECR = 0x3fe;
public static final int SIUMCR = 0x2fc000;
public static final int SYPCR = 0x2fc004;
public static final int SWSR = 0x2fc00e;
public static final int SIPEND = 0x2fc010;
public static final int SIMASK = 0x2fc014;
public static final int SIEL = 0x2fc018;
public static final int SIVEC = 0x2fc01c;
public static final int TESR = 0x2fc020;
public static final int SGPIODT1 = 0x2fc024;
public static final int SGPIODT2 = 0x2fc028;
public static final int SGPIOCR = 0x2fc02c;
public static final int EMCR = 0x2fc030;
public static final int PDMCR = 0x2fc03c;
public static final int BR0 = 0x2fc100;
public static final int OR0 = 0x2fc104;
public static final int BR1 = 0x2fc108;
public static final int OR1 = 0x2fc10c;
public static final int BR2 = 0x2fc110;
public static final int OR2 = 0x2fc114;
public static final int BR3 = 0x2fc118;
public static final int OR3 = 0x2fc11c;
public static final int DMBR = 0x2fc140;
public static final int DMOR = 0x2fc144;
public static final int MSTAT = 0x2fc178;
public static final int TBSCR = 0x2fc200;
public static final int TBREF0 = 0x2fc204;
public static final int TBREF1 = 0x2fc208;
public static final int RTCSC = 0x2fc220;
public static final int RTC = 0x2fc224;
public static final int RTSEC = 0x2fc228;
public static final int RTCAL = 0x2fc22c;
public static final int PISCR = 0x2fc240;
public static final int PITC = 0x2fc244;
public static final int PITR = 0x2fc248;
public static final int SCCR = 0x2fc280;
public static final int PLPRCR = 0x2fc284;
public static final int RSR = 0x2fc288;
public static final int COLIR = 0x2fc28c;
public static final int VSRMCR = 0x2fc290;
public static final int TBSCRK = 0x2fc300;
public static final int TBREF0K = 0x2fc304;
public static final int TBREF1K = 0x2fc308;
public static final int TBK = 0x2fc30c;
public static final int RTCSCK = 0x2fc320;
public static final int RTCK = 0x2fc324;
public static final int RTSECK = 0x2fc328;
public static final int RTCALK = 0x2fc32c;
public static final int PISCRIK = 0x2fc340;
public static final int PITCK = 0x2fc344;
public static final int SCCRK = 0x2fc380;
public static final int PLPRCRK = 0x2fc384;
public static final int RSRK = 0x2fc388;
public static final int CMFMCR_A = 0x2fc800;
public static final int CMFTST_A = 0x2fc804;
public static final int CMFCTL_A = 0x2fc808;
public static final int CMFMCR_B = 0x2fc840;
public static final int CMFTST_B = 0x2fc844;
public static final int CMFCTL_B = 0x2fc848;
public static final int DPTMCR = 0x300000;
public static final int RAMBAR = 0x300004;
public static final int MISRH = 0x300006;
public static final int MISRL = 0x300008;
public static final int MISCNT = 0x30000a;
public static final int TPUMCR_A = 0x304000;
public static final int DSCR_A = 0x304004;
public static final int DSSR_A = 0x304006;
public static final int TICR_A = 0x304008;
public static final int CIER_A = 0x30400a;
public static final int CFSR0_A = 0x30400c;
public static final int CFSR1_A = 0x30400e;
public static final int CFSR2_A = 0x304010;
public static final int CFSR3_A = 0x304012;
public static final int HSQR0_A = 0x304014;
public static final int HSQR1_A = 0x304016;
public static final int HSRR0_A = 0x304018;
public static final int HSRR1_A = 0x30401a;
public static final int CPR0_A = 0x30401c;
public static final int CPR1_A = 0x30401e;
public static final int CISR_A = 0x304020;
public static final int TPUMCR2_A = 0x304028;
public static final int TPUMCR3_A = 0x30402a;
public static final int TPURAM0_A = 0x304100;
public static final int TPURAM1_A = 0x304110;
public static final int TPURAM2_A = 0x304120;
public static final int TPURAM3_A = 0x304130;
public static final int TPURAM4_A = 0x304140;
public static final int TPURAM5_A = 0x304150;
public static final int TPURAM6_A = 0x304160;
public static final int TPURAM7_A = 0x304170;
public static final int TPURAM8_A = 0x304180;
public static final int TPURAM9_A = 0x304190;
public static final int TPURAM10_A = 0x3041a0;
public static final int TPURAM11_A = 0x3041b0;
public static final int TPURAM12_A = 0x3041c0;
public static final int TPURAM13_A = 0x3041d0;
public static final int TPURAM14_A = 0x3041e0;
public static final int TPURAM15_A = 0x3041f0;
public static final int TPUMCR_B = 0x304400;
public static final int DSCR_B = 0x304404;
public static final int DSSR_B = 0x304406;
public static final int TICR_B = 0x304408;
public static final int CIER_B = 0x30440a;
public static final int CFSR0_B = 0x30440c;
public static final int CFSR1_B = 0x30440e;
public static final int CFSR2_B = 0x304410;
public static final int CFSR3_B = 0x304412;
public static final int HSQR0_B = 0x304414;
public static final int HSQR1_B = 0x304416;
public static final int HSRR0_B = 0x304418;
public static final int HSRR1_B = 0x30441a;
public static final int CPR0_B = 0x30441c;
public static final int CPR1_B = 0x30441e;
public static final int CISR_B = 0x304420;
public static final int TPUMCR2_B = 0x304428;
public static final int TPUMCR3_B = 0x30442a;
public static final int TPURAM0_B = 0x304500;
public static final int TPURAM1_B = 0x304510;
public static final int TPURAM2_B = 0x304520;
public static final int TPURAM3_B = 0x304530;
public static final int TPURAM4_B = 0x304540;
public static final int TPURAM5_B = 0x304550;
public static final int TPURAM6_B = 0x304560;
public static final int TPURAM7_B = 0x304570;
public static final int TPURAM8_B = 0x304580;
public static final int TPURAM9_B = 0x304590;
public static final int TPURAM10_B = 0x3045a0;
public static final int TPURAM11_B = 0x3045b0;
public static final int TPURAM12_B = 0x3045c0;
public static final int TPURAM13_B = 0x3045d0;
public static final int TPURAM14_B = 0x3045e0;
public static final int TPURAM15_B = 0x3045f0;
public static final int QADC64MCR_A = 0x304800;
public static final int QADC64INT_A = 0x304804;
public static final int PORTQA_A = 0x304806;
public static final int PORTQB_A = 0x304807;
public static final int DDRQA_A = 0x304808;
public static final int QACR0_A = 0x30480a;
public static final int QACR1_A = 0x30480c;
public static final int QACR2_A = 0x30480e;
public static final int QASR0_A = 0x304810;
public static final int QASR1_A = 0x304812;
public static final int CCW_A = 0x304a00;
public static final int RJURR_A = 0x304a80;
public static final int LJSRR_A = 0x304b00;
public static final int LJURR_A = 0x304b80;
public static final int QADC64MCR_B = 0x304c00;
public static final int QADC64INT_B = 0x304c04;
public static final int PORTQA_B = 0x304c06;
public static final int PORTQB_B = 0x304c07;
public static final int DDRQA_B = 0x304c08;
public static final int QACR0_B = 0x304c0a;
public static final int QACR1_B = 0x304c0c;
public static final int QACR2_B = 0x304c0e;
public static final int QASR0_B = 0x304c10;
public static final int QASR1_B = 0x304c12;
public static final int CCW_B = 0x304e00;
public static final int RJURR_B = 0x304e80;
public static final int LJSRR_B = 0x304f00;
public static final int LJURR_B = 0x304f80;
public static final int QSMCMMCR = 0x305000;
public static final int QDSCI_IL = 0x305004;
public static final int QSPI_IL = 0x305007;
public static final int SCC1R0 = 0x305008;
public static final int SCC1R1 = 0x30500a;
public static final int SC1SR = 0x30500c;
public static final int SC1DR = 0x30500e;
public static final int PORTQS = 0x305014;
public static final int PQSPAR = 0x305016;
public static final int DDRQS = 0x305017;
public static final int SPCR0 = 0x305018;
public static final int SPCR1 = 0x30501a;
public static final int SPCR2 = 0x30501c;
public static final int SPCR3 = 0x30501e;
public static final int SPSR = 0x30501f;
public static final int SCC2R0 = 0x305020;
public static final int SCC2R1 = 0x305022;
public static final int SC2SR = 0x305024;
public static final int SC2DR = 0x305026;
public static final int QSCI1CR = 0x305028;
public static final int QSCI1SR = 0x30502a;
public static final int SCTQ = 0x30502c;
public static final int SCRQ = 0x30504c;
public static final int RECRAM = 0x305140;
public static final int TRANRAM = 0x305180;
public static final int COMDRAM = 0x3051c0;
public static final int MPWMSM0PERR = 0x306000;
public static final int MPWMSM0PULR = 0x306002;
public static final int MPWMSM0CNTR = 0x306004;
public static final int MPWMSM0SCR = 0x306006;
public static final int MPWMSM1PERR = 0x306008;
public static final int MPWMSM1PULR = 0x30600a;
public static final int MPWMSM1CNTR = 0x30600c;
public static final int MPWMSM1SCR = 0x30600e;
public static final int MPWMSM2PERR = 0x306010;
public static final int MPWMSM2PULR = 0x306012;
public static final int MPWMSM2CNTR = 0x306014;
public static final int MPWMSM2SCR = 0x306016;
public static final int MPWMSM3PERR = 0x306018;
public static final int MPWMSM3PULR = 0x30601a;
public static final int MPWMSM3CNTR = 0x30601c;
public static final int MPWMSM3SCR = 0x30601e;
public static final int MMCSM6CNT = 0x306030;
public static final int MMCSM6ML = 0x306032;
public static final int MMCSM6SCRD = 0x306034;
public static final int MMCSM6SCR = 0x306036;
public static final int MDASM11AR = 0x306058;
public static final int MDASM11BR = 0x30605a;
public static final int MDASM11SCRD = 0x30605c;
public static final int MDASM11SCR = 0x30605e;
public static final int MDASM12AR = 0x306060;
public static final int MDASM12BR = 0x306062;
public static final int MDASM12SCRD = 0x306064;
public static final int MDASM12SCR = 0x306066;
public static final int MDASM13AR = 0x306068;
public static final int MDASM13BR = 0x30606a;
public static final int MDASM13SCRD = 0x30606c;
public static final int MDASM13SCR = 0x30606e;
public static final int MDASM14AR = 0x306070;
public static final int MDASM14BR = 0x306072;
public static final int MDASM14SCRD = 0x306074;
public static final int MDASM14SCR = 0x306076;
public static final int MDASM15AR = 0x306078;
public static final int MDASM15BR = 0x30607a;
public static final int MDASM15SCRD = 0x30607c;
public static final int MDASM15SCR = 0x30607e;
public static final int MPWMSM16PERR = 0x306080;
public static final int MPWMSM16PULR = 0x306082;
public static final int MPWMSM16CNTR = 0x306084;
public static final int MPWMSM16SCR = 0x306086;
public static final int MPWMSM17PERR = 0x306088;
public static final int MPWMSM17PULR = 0x30608a;
public static final int MPWMSM17CNTR = 0x30608c;
public static final int MPWMSM17SCR = 0x30608e;
public static final int MPWMSM18PERR = 0x306090;
public static final int MPWMSM18PULR = 0x306092;
public static final int MPWMSM18CNTR = 0x306094;
public static final int MPWMSM18SCR = 0x306096;
public static final int MPWMSM19PERR = 0x306098;
public static final int MPWMSM19PULR = 0x30609a;
public static final int MPWMSM19CNTR = 0x30609c;
public static final int MPWMSM19SCR = 0x30609e;
public static final int MMCSM22CNT = 0x3060b0;
public static final int MMCSM22ML = 0x3060b2;
public static final int MMCSM22SCRD = 0x3060b4;
public static final int MMCSM22SCR = 0x3060b6;
public static final int MDASM27AR = 0x3060d8;
public static final int MDASM27BR = 0x3060da;
public static final int MDASM27SCRD = 0x3060dc;
public static final int MDASM27SCR = 0x3060de;
public static final int MDASM28AR = 0x3060e0;
public static final int MDASM28BR = 0x3060e2;
public static final int MDASM28SCRD = 0x3060e4;
public static final int MDASM28SCR = 0x3060e6;
public static final int MDASM29AR = 0x3060e8;
public static final int MDASM29BR = 0x3060ea;
public static final int MDASM29SCRD = 0x3060ec;
public static final int MDASM29SCR = 0x3060ee;
public static final int MDASM30AR = 0x3060f0;
public static final int MDASM30BR = 0x3060f2;
public static final int MDASM30SCRD = 0x3060f4;
public static final int MDASM30SCR = 0x3060f6;
public static final int MDASM31AR = 0x3060f8;
public static final int MDASM31BR = 0x3060fa;
public static final int MDASM31SCRD = 0x3060fc;
public static final int MDASM31SCR = 0x3060fe;
public static final int MPIOSMDR = 0x306100;
public static final int MPIOSMDDR = 0x306102;
public static final int MIOS1TPCR = 0x306800;
public static final int MIOS1VNR = 0x306804;
public static final int MIOS1MCR = 0x306806;
public static final int MCPSMSCR = 0x306816;
public static final int MIOS1SR0 = 0x306c00;
public static final int MIOS1ER0 = 0x306c04;
public static final int MIOS1RPR0 = 0x306c06;
public static final int MIOS1LVL0 = 0x306c30;
public static final int MIOS1SR1 = 0x306c40;
public static final int MIOS1ER1 = 0x306c44;
public static final int MIOS1RPR1 = 0x306c46;
public static final int MIOS1LVL1 = 0x306c70;
public static final int UMCR = 0x307f80;
public static final int UTSTCREG = 0x307f90;
public static final int UIPEND = 0x307fa0;
public static final int SRAMMCR_A = 0x380000;
public static final int SRAMMCR_B = 0x380008;
}
|
deepjava/runtime-library
|
src/org/deepjava/runtime/mpc555/Impc555.java
|
Java
|
apache-2.0
| 17,248 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This class stores several source parsing related options and offers access to their values.
/// </summary>
public sealed class CSharpParseOptions : ParseOptions, IEquatable<CSharpParseOptions>
{
/// <summary>
/// The default parse options.
/// </summary>
public static CSharpParseOptions Default { get; } = new CSharpParseOptions();
private ImmutableDictionary<string, string> _features;
/// <summary>
/// Gets the language version.
/// </summary>
public LanguageVersion LanguageVersion { get; private set; }
internal ImmutableArray<string> PreprocessorSymbols { get; private set; }
/// <summary>
/// Gets the names of defined preprocessor symbols.
/// </summary>
public override IEnumerable<string> PreprocessorSymbolNames
{
get { return PreprocessorSymbols; }
}
public CSharpParseOptions(
LanguageVersion languageVersion = LanguageVersion.CSharp6,
DocumentationMode documentationMode = DocumentationMode.Parse,
SourceCodeKind kind = SourceCodeKind.Regular,
IEnumerable<string> preprocessorSymbols = null)
: this(languageVersion, documentationMode, kind, preprocessorSymbols.ToImmutableArrayOrEmpty())
{
if (!languageVersion.IsValid())
{
throw new ArgumentOutOfRangeException(nameof(languageVersion));
}
if (!kind.IsValid())
{
throw new ArgumentOutOfRangeException(nameof(kind));
}
if (preprocessorSymbols != null)
{
foreach (var preprocessorSymbol in preprocessorSymbols)
{
if (!SyntaxFacts.IsValidIdentifier(preprocessorSymbol))
{
throw new ArgumentException("preprocessorSymbols");
}
}
}
}
internal CSharpParseOptions(
LanguageVersion languageVersion,
DocumentationMode documentationMode,
SourceCodeKind kind,
IEnumerable<string> preprocessorSymbols,
ImmutableDictionary<string, string> features)
: this(languageVersion, documentationMode, kind, preprocessorSymbols)
{
if (features == null)
{
throw new ArgumentNullException(nameof(features));
}
_features = features;
}
private CSharpParseOptions(CSharpParseOptions other) : this(
languageVersion: other.LanguageVersion,
documentationMode: other.DocumentationMode,
kind: other.Kind,
preprocessorSymbols: other.PreprocessorSymbols,
features: other.Features.ToImmutableDictionary())
{
}
// No validation
internal CSharpParseOptions(
LanguageVersion languageVersion,
DocumentationMode documentationMode,
SourceCodeKind kind,
ImmutableArray<string> preprocessorSymbols)
: base(kind, documentationMode)
{
Debug.Assert(!preprocessorSymbols.IsDefault);
this.LanguageVersion = languageVersion;
this.PreprocessorSymbols = preprocessorSymbols;
_features = ImmutableDictionary<string, string>.Empty;
}
public new CSharpParseOptions WithKind(SourceCodeKind kind)
{
if (kind == this.Kind)
{
return this;
}
if (!kind.IsValid())
{
throw new ArgumentOutOfRangeException(nameof(kind));
}
return new CSharpParseOptions(this) { Kind = kind };
}
public CSharpParseOptions WithLanguageVersion(LanguageVersion version)
{
if (version == this.LanguageVersion)
{
return this;
}
if (!version.IsValid())
{
throw new ArgumentOutOfRangeException(nameof(version));
}
return new CSharpParseOptions(this) { LanguageVersion = version };
}
public CSharpParseOptions WithPreprocessorSymbols(IEnumerable<string> preprocessorSymbols)
{
return WithPreprocessorSymbols(preprocessorSymbols.AsImmutableOrNull());
}
public CSharpParseOptions WithPreprocessorSymbols(params string[] preprocessorSymbols)
{
return WithPreprocessorSymbols(ImmutableArray.Create(preprocessorSymbols));
}
public CSharpParseOptions WithPreprocessorSymbols(ImmutableArray<string> symbols)
{
if (symbols.IsDefault)
{
symbols = ImmutableArray<string>.Empty;
}
if (symbols.Equals(this.PreprocessorSymbols))
{
return this;
}
return new CSharpParseOptions(this) { PreprocessorSymbols = symbols };
}
public new CSharpParseOptions WithDocumentationMode(DocumentationMode documentationMode)
{
if (documentationMode == this.DocumentationMode)
{
return this;
}
if (!documentationMode.IsValid())
{
throw new ArgumentOutOfRangeException(nameof(documentationMode));
}
return new CSharpParseOptions(this) { DocumentationMode = documentationMode };
}
public override ParseOptions CommonWithKind(SourceCodeKind kind)
{
return WithKind(kind);
}
protected override ParseOptions CommonWithDocumentationMode(DocumentationMode documentationMode)
{
return WithDocumentationMode(documentationMode);
}
protected override ParseOptions CommonWithFeatures(IEnumerable<KeyValuePair<string, string>> features)
{
return WithFeatures(features);
}
/// <summary>
/// Enable some experimental language features for testing.
/// </summary>
public new CSharpParseOptions WithFeatures(IEnumerable<KeyValuePair<string, string>> features)
{
if (features == null)
{
throw new ArgumentNullException(nameof(features));
}
return new CSharpParseOptions(this) { _features = features.ToImmutableDictionary(StringComparer.OrdinalIgnoreCase) };
}
public override IReadOnlyDictionary<string, string> Features
{
get
{
return _features;
}
}
internal bool IsFeatureEnabled(MessageID feature)
{
switch (feature)
{
case MessageID.IDS_FeatureBinaryLiteral:
case MessageID.IDS_FeatureDigitSeparator:
case MessageID.IDS_FeatureLocalFunctions:
case MessageID.IDS_FeatureRefLocalsReturns:
case MessageID.IDS_FeaturePatternMatching:
case MessageID.IDS_FeatureTuples:
case MessageID.IDS_FeatureReplace:
// in "demo" mode enable proposed new C# 7 language features.
if (PreprocessorSymbols.Contains("__DEMO__"))
{
return true;
}
break;
default:
break;
}
string featureFlag = feature.RequiredFeature();
if (featureFlag != null)
{
return Features.ContainsKey(featureFlag);
}
LanguageVersion availableVersion = LanguageVersion;
LanguageVersion requiredVersion = feature.RequiredVersion();
return availableVersion >= requiredVersion;
}
public override bool Equals(object obj)
{
return this.Equals(obj as CSharpParseOptions);
}
public bool Equals(CSharpParseOptions other)
{
if (object.ReferenceEquals(this, other))
{
return true;
}
if (!base.EqualsHelper(other))
{
return false;
}
return this.LanguageVersion == other.LanguageVersion;
}
public override int GetHashCode()
{
return
Hash.Combine(base.GetHashCodeHelper(),
Hash.Combine((int)this.LanguageVersion, 0));
}
}
}
|
ericfe-ms/roslyn
|
src/Compilers/CSharp/Portable/CSharpParseOptions.cs
|
C#
|
apache-2.0
| 8,998 |
/* */
"format esm";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { isPresent, isBlank, CONST } from 'angular2/src/facade/lang';
import { ListWrapper, StringMapWrapper } from 'angular2/src/facade/collection';
import { ViewType } from './view_type';
export let StaticNodeDebugInfo = class StaticNodeDebugInfo {
constructor(providerTokens, componentToken, refTokens) {
this.providerTokens = providerTokens;
this.componentToken = componentToken;
this.refTokens = refTokens;
}
};
StaticNodeDebugInfo = __decorate([
CONST(),
__metadata('design:paramtypes', [Array, Object, Object])
], StaticNodeDebugInfo);
export class DebugContext {
constructor(_view, _nodeIndex, _tplRow, _tplCol) {
this._view = _view;
this._nodeIndex = _nodeIndex;
this._tplRow = _tplRow;
this._tplCol = _tplCol;
}
get _staticNodeInfo() {
return isPresent(this._nodeIndex) ? this._view.staticNodeDebugInfos[this._nodeIndex] : null;
}
get context() { return this._view.context; }
get component() {
var staticNodeInfo = this._staticNodeInfo;
if (isPresent(staticNodeInfo) && isPresent(staticNodeInfo.componentToken)) {
return this.injector.get(staticNodeInfo.componentToken);
}
return null;
}
get componentRenderElement() {
var componentView = this._view;
while (isPresent(componentView.declarationAppElement) &&
componentView.type !== ViewType.COMPONENT) {
componentView = componentView.declarationAppElement.parentView;
}
return isPresent(componentView.declarationAppElement) ?
componentView.declarationAppElement.nativeElement :
null;
}
get injector() { return this._view.injector(this._nodeIndex); }
get renderNode() {
if (isPresent(this._nodeIndex) && isPresent(this._view.allNodes)) {
return this._view.allNodes[this._nodeIndex];
}
else {
return null;
}
}
get providerTokens() {
var staticNodeInfo = this._staticNodeInfo;
return isPresent(staticNodeInfo) ? staticNodeInfo.providerTokens : null;
}
get source() {
return `${this._view.componentType.templateUrl}:${this._tplRow}:${this._tplCol}`;
}
get locals() {
var varValues = {};
// TODO(tbosch): right now, the semantics of debugNode.locals are
// that it contains the variables of all elements, not just
// the given one. We preserve this for now to not have a breaking
// change, but should change this later!
ListWrapper.forEachWithIndex(this._view.staticNodeDebugInfos, (staticNodeInfo, nodeIndex) => {
var refs = staticNodeInfo.refTokens;
StringMapWrapper.forEach(refs, (refToken, refName) => {
var varValue;
if (isBlank(refToken)) {
varValue = isPresent(this._view.allNodes) ? this._view.allNodes[nodeIndex] : null;
}
else {
varValue = this._view.injectorGet(refToken, nodeIndex, null);
}
varValues[refName] = varValue;
});
});
StringMapWrapper.forEach(this._view.locals, (localValue, localName) => { varValues[localName] = localValue; });
return varValues;
}
}
|
tzerb/Learning
|
WebApplication3/src/WebApplication3/jspm_packages/npm/angular2@2.0.0-beta.17/es6/prod/src/core/linker/debug_context.js
|
JavaScript
|
apache-2.0
| 4,102 |
<?php
class Radios_FormItem_Core extends FormItem {
protected function options() {
return $this->options;
}
protected function inputType() {
return "radio";
}
};
|
erichoglander/qf
|
core/form_item/radios_form_item.php
|
PHP
|
apache-2.0
| 193 |
/*
Copyright 2015 Jenna Hatchard
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.mycompany.assignment1;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Me on 2015-10-03.
*/
public class SortStats {
//initializes all of them to zero
Long max10 = Long.valueOf(0);
Long min10 = Long.valueOf(0);
Long avg10= Long.valueOf(0);
Long med10 = Long.valueOf(0);
Long max100= Long.valueOf(0);
Long min100= Long.valueOf(0);
Long avg100= Long.valueOf(0);
Long med100 = Long.valueOf(0);
Long maxAll= Long.valueOf(0);
Long minAll= Long.valueOf(0);
Long avgAll= Long.valueOf(0);
Long medAll= Long.valueOf(0);
ArrayList<Long> results = new ArrayList<>();
//sort the stats so that they can be displayed later
public ArrayList sortIt(ArrayList stats) {
ArrayList statsCopy = (ArrayList)stats.clone(); //need to do this otherwise it can mess up later stats
//just for all
if(statsCopy.size() < 10) {
sortAll(statsCopy);
}
//have to do for 10 and all
else if(statsCopy.size() <= 100){
sort10(statsCopy);
sortAll(statsCopy);
}
//for everything!
else if(statsCopy.size() >= 100) {
sort10(statsCopy);
sort100(statsCopy);
sortAll(statsCopy);
} else {}
//add the new sorted results in
results.add(min10);
results.add(max10);
results.add(avg10);
results.add(med10);
results.add(min100);
results.add(max100);
results.add(avg100);
results.add(med100);
results.add(minAll);
results.add(maxAll);
results.add(avgAll);
results.add(medAll);
return results;
}
public void sortAll(ArrayList all) {
Long zeros = Long.valueOf(0);
Collections.sort(all);
ArrayList subAll = new ArrayList();
// get rid of the zero place holders
//checks that there are not zeros messing with the stats
int zeroFrequency = Collections.frequency(all, zeros);
if(zeroFrequency != 0) {
for(Object i:all){
if(i.equals(zeros)){}
else {
subAll.add(i);
}
}
//if the entire list was empty
if(subAll.isEmpty()) {
maxAll = zeros;
minAll = zeros;
medAll = zeros;
avgAll = zeros;
}
else {
int midIndex = (subAll.size() / 2);
maxAll = (Long) Collections.max(subAll);
minAll = (Long) Collections.min(subAll);
medAll = (Long) all.get(midIndex); //get middle number
avgAll = calculateAverage(subAll);
}
} else {
int midIndex = (all.size() / 2);
maxAll = (Long) Collections.max(all);
minAll = (Long) Collections.min(all);
medAll = (Long) all.get(midIndex); //get middle number
avgAll = calculateAverage(all);
}
}
public void sort100(ArrayList last100) {
int end = last100.size();
int start = end - 100;
List miniList = last100.subList(start, end);
Collections.sort(miniList);
max100 = (Long)Collections.max(miniList);
min100 = (Long)Collections.min(miniList);
med100 = (Long)miniList.get(49); //get middle number
avg100 = calculateAverage(miniList);
}
public void sort10(ArrayList last10) {
int end = last10.size();
int start = end - 10;
List miniList = last10.subList(start, end);
Collections.sort(miniList);
max10 = (Long)Collections.max(miniList);
min10 = (Long)Collections.min(miniList);
med10 = (Long)miniList.get(4); //get middle number
avg10 = calculateAverage(miniList);
}
//http://stackoverflow.com/questions/10791568/calculating-average-of-an-array-list Jesherun 10-03-2015
public Long calculateAverage(List <Long>list) {
Long sum = new Long(0);
if(!list.isEmpty()) {
for (Long i: list) {
sum += i;
}
return sum / list.size();
}
return sum;
}
}
|
hatchard/Assignment1-CMPUT301
|
app/src/main/java/com/mycompany/assignment1/SortStats.java
|
Java
|
apache-2.0
| 4,882 |
/**
*
*/
/**
* @author Vladimir Kornienko
*
*/
package org.openntf.red.security.authorization;
|
hyarthi/project-red
|
src/java/org.openntf.red.main/src/org/openntf/red/security/authorization/package-info.java
|
Java
|
apache-2.0
| 100 |
package io.fabric8.kubernetes.api.model;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.sundr.builder.annotations.Buildable;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"apiVersion",
"kind",
"metadata",
"audience",
"expirationSeconds",
"path"
})
@ToString
@EqualsAndHashCode
@Setter
@Accessors(prefix = {
"_",
""
})
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = true, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder")
public class ServiceAccountTokenProjection implements KubernetesResource
{
@JsonProperty("audience")
private String audience;
@JsonProperty("expirationSeconds")
private Long expirationSeconds;
@JsonProperty("path")
private String path;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
* No args constructor for use in serialization
*
*/
public ServiceAccountTokenProjection() {
}
/**
*
* @param path
* @param audience
* @param expirationSeconds
*/
public ServiceAccountTokenProjection(String audience, Long expirationSeconds, String path) {
super();
this.audience = audience;
this.expirationSeconds = expirationSeconds;
this.path = path;
}
@JsonProperty("audience")
public String getAudience() {
return audience;
}
@JsonProperty("audience")
public void setAudience(String audience) {
this.audience = audience;
}
@JsonProperty("expirationSeconds")
public Long getExpirationSeconds() {
return expirationSeconds;
}
@JsonProperty("expirationSeconds")
public void setExpirationSeconds(Long expirationSeconds) {
this.expirationSeconds = expirationSeconds;
}
@JsonProperty("path")
public String getPath() {
return path;
}
@JsonProperty("path")
public void setPath(String path) {
this.path = path;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
|
fabric8io/kubernetes-client
|
kubernetes-model-generator/kubernetes-model-core/src/generated/java/io/fabric8/kubernetes/api/model/ServiceAccountTokenProjection.java
|
Java
|
apache-2.0
| 2,936 |
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var di_1 = require('angular2/src/core/di');
var di_2 = require('angular2/src/core/di');
var collection_1 = require('angular2/src/facade/collection');
var lang_1 = require('angular2/src/facade/lang');
var exceptions_1 = require('angular2/src/facade/exceptions');
var metadata_1 = require('../core/metadata');
var view_resolver_1 = require('angular2/src/compiler/view_resolver');
var MockViewResolver = (function (_super) {
__extends(MockViewResolver, _super);
function MockViewResolver() {
_super.call(this);
/** @internal */
this._views = new collection_1.Map();
/** @internal */
this._inlineTemplates = new collection_1.Map();
/** @internal */
this._viewCache = new collection_1.Map();
/** @internal */
this._directiveOverrides = new collection_1.Map();
}
/**
* Overrides the {@link ViewMetadata} for a component.
*
* @param {Type} component
* @param {ViewDefinition} view
*/
MockViewResolver.prototype.setView = function (component, view) {
this._checkOverrideable(component);
this._views.set(component, view);
};
/**
* Overrides the inline template for a component - other configuration remains unchanged.
*
* @param {Type} component
* @param {string} template
*/
MockViewResolver.prototype.setInlineTemplate = function (component, template) {
this._checkOverrideable(component);
this._inlineTemplates.set(component, template);
};
/**
* Overrides a directive from the component {@link ViewMetadata}.
*
* @param {Type} component
* @param {Type} from
* @param {Type} to
*/
MockViewResolver.prototype.overrideViewDirective = function (component, from, to) {
this._checkOverrideable(component);
var overrides = this._directiveOverrides.get(component);
if (lang_1.isBlank(overrides)) {
overrides = new collection_1.Map();
this._directiveOverrides.set(component, overrides);
}
overrides.set(from, to);
};
/**
* Returns the {@link ViewMetadata} for a component:
* - Set the {@link ViewMetadata} to the overridden view when it exists or fallback to the default
* `ViewResolver`,
* see `setView`.
* - Override the directives, see `overrideViewDirective`.
* - Override the @View definition, see `setInlineTemplate`.
*
* @param component
* @returns {ViewDefinition}
*/
MockViewResolver.prototype.resolve = function (component) {
var view = this._viewCache.get(component);
if (lang_1.isPresent(view))
return view;
view = this._views.get(component);
if (lang_1.isBlank(view)) {
view = _super.prototype.resolve.call(this, component);
}
var directives = [];
var overrides = this._directiveOverrides.get(component);
if (lang_1.isPresent(overrides) && lang_1.isPresent(view.directives)) {
flattenArray(view.directives, directives);
overrides.forEach(function (to, from) {
var srcIndex = directives.indexOf(from);
if (srcIndex == -1) {
throw new exceptions_1.BaseException("Overriden directive " + lang_1.stringify(from) + " not found in the template of " + lang_1.stringify(component));
}
directives[srcIndex] = to;
});
view = new metadata_1.ViewMetadata({ template: view.template, templateUrl: view.templateUrl, directives: directives });
}
var inlineTemplate = this._inlineTemplates.get(component);
if (lang_1.isPresent(inlineTemplate)) {
view = new metadata_1.ViewMetadata({ template: inlineTemplate, templateUrl: null, directives: view.directives });
}
this._viewCache.set(component, view);
return view;
};
/**
* @internal
*
* Once a component has been compiled, the AppProtoView is stored in the compiler cache.
*
* Then it should not be possible to override the component configuration after the component
* has been compiled.
*
* @param {Type} component
*/
MockViewResolver.prototype._checkOverrideable = function (component) {
var cached = this._viewCache.get(component);
if (lang_1.isPresent(cached)) {
throw new exceptions_1.BaseException("The component " + lang_1.stringify(component) + " has already been compiled, its configuration can not be changed");
}
};
MockViewResolver = __decorate([
di_2.Injectable(),
__metadata('design:paramtypes', [])
], MockViewResolver);
return MockViewResolver;
}(view_resolver_1.ViewResolver));
exports.MockViewResolver = MockViewResolver;
function flattenArray(tree, out) {
for (var i = 0; i < tree.length; i++) {
var item = di_1.resolveForwardRef(tree[i]);
if (lang_1.isArray(item)) {
flattenArray(item, out);
}
else {
out.push(item);
}
}
}
//# sourceMappingURL=view_resolver_mock.js.map
|
tzerb/Learning
|
WebApplication3/src/WebApplication3/jspm_packages/npm/dist/js/cjs/src/mock/view_resolver_mock.js
|
JavaScript
|
apache-2.0
| 6,175 |
// ===========================================================================================================
//
// Class/Library: ListBox Control - Main Script
// Author: Michael Marzilli ( http://www.linkedin.com/in/michaelmarzilli , http://www.develteam.com/Developer/Rowell/Portfolio )
// Created: Jun 10, 2016
//
// VERS 1.0.000 : Jun 10, 2016 : Original File Created. Released for Unity 3D.
// 1.0.001 : Jun 11, 2016 : Added a SubText field/element to the ListBox Control.
// The SubText field is a right justified field that can add additional information.
// Such as displaying a price for an item in and item list for a shop.
// 1.0.002 : May 04, 2017 : Added delegates for AddListItem and RemoveListItem.
//
// ===========================================================================================================
#if UNITY_EDITOR
#define IS_DEBUGGING
#else
#undef IS_DEBUGGING
#endif
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public delegate void OnListBoxSelectChanged( GameObject go, int intSelected);
public delegate void OnListBoxDoubleClick( GameObject go, int intSelected);
public delegate void OnAddListItemEvent( GameObject go, int intAddedIndex);
public delegate void OnRemoveListItemEvent( GameObject go, int intRemovedIndex);
[System.Serializable]
public class ListBoxControl : MonoBehaviour
{
#region "PRIVATE CONSTANTS"
// IF DROPDOWN LIST SELECTION IS NOT BEING PROPERLY SCROLLED TO WHEN THE DROPDOWN LIST IS SELECTED,
// TRY INCREASING THE CONSTANT BELOW UNTIL THE SELECTED ITEM SCROLLS INTO VIEW PROPERLY
// (THIS CONSTANT IS USED IN THE SetScroll(float fValue) IENUMERATOR
private const float SCROLL_DELAY = 0.002f; // BEST DEFAULT: 0.12f ??
#endregion
#region "STARTING LIST ITEM CLASS"
[System.Serializable]
public class StartingListItem
{
public string Value = "";
public string Text = "";
public string SubText = "";
public Sprite Icon = null;
public int Index = -1;
public StartingListItem(string strValue, string strText, Sprite imgSprite = null, string strSub = "")
{
Value = strValue;
Text = strText;
SubText = strSub;
Icon = imgSprite;
}
}
#endregion
#region "PRIVATE VARIABLES"
// SERIALIZED FIELDS
[SerializeField]
protected List<StartingListItem> _startArray = new List<StartingListItem>();
[SerializeField]
private string _strTitle = "";
[SerializeField]
private bool _blnBestFit = false;
[SerializeField]
private bool _blnAllowDblClick = false;
[SerializeField]
private bool _blnPartOfDDL = false;
private ListBoxModes _lbMode = ListBoxModes.ListBox;
private List<ListBoxLineItem> _items = new List<ListBoxLineItem>();
private RectTransform _rtContainer = null;
private RectTransform _rtScrollRect = null;
private int _intItemCount = 0;
private int _intSelectedItem = -1;
private List<int> _intSelectedList = new List<int>();
protected bool _blnInitialized = false;
#endregion
#region "PRIVATE PROPERTIES"
private RectTransform ContainerRect
{
get
{
if (_rtContainer == null)
if (ScrollContainerObject != null)
_rtContainer = ScrollContainerObject.GetComponent<RectTransform>();
return _rtContainer;
}
}
private RectTransform ScrollRect
{
get
{
if (_rtScrollRect == null)
if (ScrollRectObject != null)
_rtScrollRect = ScrollRectObject.GetComponent<RectTransform>();
return _rtScrollRect;
}
}
#endregion
#region "PUBLIC EDITOR PROPERTIES"
public GameObject ScrollBarObject;
public GameObject ScrollRectObject;
public GameObject ScrollContainerObject;
public Text ListBoxTitle;
public GameObject ListBoxLineItemPrefabObject;
[SerializeField]
public Color ItemNormalColor;
[SerializeField]
public Color ItemHighlightColor;
[SerializeField]
public Color ItemSelectedColor;
[SerializeField]
public Color ItemDisabledColor;
[SerializeField]
public bool CanMultiSelect = false;
[SerializeField]
public bool AutoMultiSelect = false;
[SerializeField]
public float Height = 36;
[SerializeField]
public float Spacing = 4;
[SerializeField]
public char SeparatorChar = '|';
#endregion
#region "PUBLIC PROPERTIES"
public enum ListBoxModes : int { ListBox = 0, DropDownList = 1 }
public ListBoxModes ListBoxMode
{
get
{
return _lbMode;
}
set
{
_lbMode = value;
}
}
// HANDLE LISTBOX TITLE
public string Title
{
get
{
return _strTitle;
}
set
{
_strTitle = value.Trim();
if (ListBoxMode == ListBoxModes.ListBox && ListBoxTitle != null)
{
ListBoxTitle.gameObject.SetActive(_strTitle != "");
ListBoxTitle.text = _strTitle;
} else
if (ListBoxTitle != null)
ListBoxTitle.gameObject.SetActive(false);
}
}
public bool TitleBestFit
{
get
{
return _blnBestFit;
}
set
{
_blnBestFit = value;
if (ListBoxMode == ListBoxModes.ListBox && ListBoxTitle != null)
ListBoxTitle.resizeTextForBestFit = _blnBestFit;
}
}
public bool AllowDoubleClick
{
get
{
return _blnAllowDblClick && !_blnPartOfDDL && ListBoxMode == ListBoxModes.ListBox;
}
set
{
_blnAllowDblClick = value;
}
}
public bool PartOfDDL
{
get
{
return _blnPartOfDDL;
}
set
{
_blnPartOfDDL = value;
}
}
// HANDLE STARTING LIST ITEMS
public List<StartingListItem> StartArray
{
get
{
return _startArray;
}
}
// HANDLE SELECTION (GET)
public virtual List<ListBoxLineItem> Items
{
get
{
if (_items == null)
_items = new List<ListBoxLineItem>();
return _items;
}
}
public virtual List<int> SelectedIndexes
{
get
{
if (_intSelectedList == null)
_intSelectedList = new List<int>();
return _intSelectedList;
}
}
public virtual List<string> SelectedValues
{
get
{
if (_intSelectedItem < 0 || _intSelectedList == null || _intSelectedList.Count < 0)
return null;
List<string> st = new List<string>();
for (int i = 0; i < _intSelectedList.Count; i++)
st.Add(Items[_intSelectedList[i]].Value);
return st;
}
}
public virtual string SelectedValuesString
{
get
{
List<string> st = SelectedValues;
if (st == null || st.Count < 1)
return "";
string strOut = "";
for (int i = 0; i < st.Count; i++)
{
if (st[i].Trim() != "")
strOut += SeparatorChar + st[i];
}
if (strOut.Length > 1)
strOut = strOut.Substring(1);
return strOut;
}
}
public virtual string SelectedValue
{
get
{
if (_intSelectedItem < 0 || _intSelectedList == null || _intSelectedList.Count < 0)
return null;
return Items[_intSelectedList[0]].Value;
}
}
public virtual string SelectedArrayValue(int intIndex)
{
if (intIndex > Items[_intSelectedList[0]].Value.Split(SeparatorChar).Length - 1)
return "";
return Items[_intSelectedList[0]].Value.Split(SeparatorChar)[intIndex];
}
public virtual int SelectedValueInt
{
get
{
if (_intSelectedItem < 0 || _intSelectedList == null || _intSelectedList.Count < 0)
return -1;
return Util.ConvertToInt(Items[_intSelectedList[0]].Value);
}
}
public virtual int SelectedArrayValueInt(int intIndex)
{
return Util.ConvertToInt(SelectedArrayValue(intIndex));
}
public virtual int SelectedIndex
{
get
{
return _intSelectedItem;
}
set
{
_intSelectedItem = value;
}
}
public virtual string SelectedText
{
get
{
if (_intSelectedItem < 0 || _intSelectedList == null || _intSelectedList.Count < 0)
return "";
return Items[_intSelectedList[0]].Text;
}
}
public bool IsInitialized
{
get
{
return _blnInitialized;
}
}
#endregion
#region "PRIVATE FUNCTIONS"
private void Awake()
{
// INITIALIZE THE ITEM LIST
_intSelectedItem = -1;
_items = new List<ListBoxLineItem>();
_intSelectedList = new List<int>();
// EXIT IF THIS IS A DROPDOWN LIST
if (ListBoxMode == ListBoxModes.DropDownList)
return;
// RE-SIZE THE SCROLL CONTAINER
// REMOVE ANY GAMEOBJECTS IN THE CONTAINER
if (ScrollContainerObject != null)
{
// RESIZE THE WIDTH OF THE CONTAINER TO MATCH THE CONTROL
Vector2 v2 = ScrollContainerObject.GetComponent<RectTransform>().sizeDelta;
v2.x = ScrollContainerObject.transform.parent.GetComponent<RectTransform>().sizeDelta.x;
ScrollContainerObject.GetComponent<RectTransform>().sizeDelta = v2;
// REMOVE GAMEOBJECTS IN THE CONTAINER
if (ScrollContainerObject.transform.childCount > 0)
{
for (int i = ScrollContainerObject.transform.childCount - 1; i >= 0; i--)
Destroy(ScrollContainerObject.transform.GetChild(i).gameObject);
}
}
}
private void Start()
{
if (!gameObject.activeInHierarchy) // && !_blnInitialized)
return;
// RESIZE THE ITEM CONTAINER TO THE WIDTH OF THE SCROLL RECT
if (ContainerRect != null)
ContainerRect.sizeDelta = new Vector2(ScrollRect.rect.width, ContainerRect.rect.height);
// SET SCROLLBAR SENSITIVITY
if (ScrollRectObject != null)
ScrollRectObject.GetComponent<ScrollRect>().scrollSensitivity = Height - Spacing;
if (ScrollBarObject != null)
ScrollBarObject.GetComponent<Scrollbar>().numberOfSteps = 1;
// EXIT IF THIS IS A DROPDOWN LIST
if (ListBoxMode == ListBoxModes.DropDownList)
return;
// SET TITLE
if (ListBoxTitle != null)
Title = _strTitle;
// CHECK FOR LINE ITEM PREFAB
if (ListBoxLineItemPrefabObject == null)
Debug.LogError(gameObject.name + " is Missing the Line Item Prefab. Please add the Prefab.");
else if (ListBoxLineItemPrefabObject.GetComponent<ListBoxLineItem>() == null)
Debug.LogError(gameObject.name + " is Missing the Line Item Prefab. Please add the Prefab.");
// ADD INITIAL LIST ITEMS (IF THERE ARE ANY)
if (StartArray.Count > 0)
{
for (int i = 0; i < StartArray.Count; i++)
{
AddItem(StartArray[i].Value, StartArray[i].Text, StartArray[i].Icon);
}
}
// MARK CONTROL AS INITIALIZED
_blnInitialized = true;
}
private void OnEnable()
{
if (!_blnInitialized && gameObject.activeInHierarchy)
Start();
// MAKE SURE THAT THE LIST BOX ITEM CONTAINER IS PROPERLY SIZED (HEIGHT)
if (ListBoxMode == ListBoxModes.ListBox)
UpdateListBoxContainerSize();
}
private void ResizeContainer()
{
if (!Application.isPlaying || ListBoxMode == ListBoxModes.DropDownList)
return;
float fScroll = 1;
if (ScrollBarObject != null)
fScroll = ScrollBarObject.GetComponent<Scrollbar>().value;
Vector2 v2 = ContainerRect.sizeDelta;
v2.y = ((this.Height + this.Spacing) * Items.Count) + this.Spacing;
ContainerRect.sizeDelta = v2;
try
{
if (gameObject.activeInHierarchy)
StartCoroutine(SetScroll(fScroll));
} catch { }
}
private void SelectByRange( int intEnd)
{
// SELECTS A RANGE OF ITEMS STARTING AT _intSelectedItem, EXTENDING TO intEnd
int s = (int)Mathf.Sign(intEnd - _intSelectedItem);
int i = _intSelectedItem;
int e = intEnd;
while (e >= 0 && i >= 0 && i < Items.Count &&
((s > 0 && i <= e) || (s < 0 && i >= e)))
{
if (Items[i].Enabled && Items[i].Shown)
{
Items[i].Select();
_intSelectedList.Add(i);
}
i += s;
}
}
private void UnSelectItem( int intIndex)
{
if (ListBoxMode == ListBoxModes.DropDownList)
return;
// UNSELECT SINGLE ITEM
if (intIndex >= 0 && intIndex == _intSelectedItem && Items[intIndex] != null)
{
Items[_intSelectedItem].UnSelect();
int i = _intSelectedList.FindIndex(x => x == intIndex);
_intSelectedList.RemoveAt(i);
if (_intSelectedList.Count > 0)
_intSelectedItem = _intSelectedList[0];
else
_intSelectedItem = -1;
} else
// UNSELECT THE ITEM FROM THE LIST
if (_intSelectedList.Count > 0)
{
int i = _intSelectedList.FindIndex(x => x == intIndex);
if (i >= 0)
{
Items[_intSelectedList[i]].UnSelect();
_intSelectedList.RemoveAt(i);
}
}
}
private void UnSelectByRange(int intEnd)
{
if (ListBoxMode == ListBoxModes.DropDownList)
return;
int s = (int)Mathf.Sign(intEnd - _intSelectedItem);
int i = _intSelectedItem;
int e = intEnd;
while (e >= 0 && i >= 0 && i < Items.Count &&
((s > 0 && i <= e) || (s < 0 && i >= e)))
{
Items[_intSelectedList[i]].UnSelect();
_intSelectedList.RemoveAt(i);
i += s;
}
}
private void UnSelectAllItems()
{
if (ListBoxMode == ListBoxModes.DropDownList)
return;
// UNSELECT SINGLE ITEM
if (_intSelectedItem >= 0 && Items[_intSelectedItem] != null)
Items[_intSelectedItem].UnSelect();
// UNSELECT MULTIPLY SELECTED ITEMS
if (_intSelectedList.Count > 0)
{
for (int i = _intSelectedList.Count - 1; i >= 0; i--)
{
Items[_intSelectedList[i]].UnSelect();
_intSelectedList.RemoveAt(i);
}
}
}
private IEnumerator SetScroll(float fValue)
{
yield return new WaitForSeconds(0.001f);
if (gameObject.activeInHierarchy && ScrollBarObject != null && ScrollBarObject.activeSelf && ListBoxMode == ListBoxModes.ListBox)
{
yield return new WaitForSeconds(SCROLL_DELAY);
ScrollBarObject.GetComponent<Scrollbar>().value = 0;
yield return new WaitForSeconds(0.0001f);
ScrollBarObject.GetComponent<Scrollbar>().value = fValue;
}
}
private void PrivAddItem( string strValue, string strText, string strIcon = "", string strSub = "")
{
// CHECK IF LINE ITEM PREFAB EXISTS
if (ListBoxLineItemPrefabObject == null)
{
Debug.LogError(gameObject.name + " is Missing the Line Item Prefab. Please add the Prefab.");
return;
} else if (ListBoxLineItemPrefabObject.GetComponent<ListBoxLineItem>() == null) {
Debug.LogError(gameObject.name + " is Missing the Line Item Prefab. Please add the Prefab.");
return;
}
// CALCULATE ICON SPRITE
Sprite sprIcon = null;
if (strIcon != "")
{
sprIcon = Resources.Load<Sprite>(strIcon);
}
int i = Items.FindIndex(x => x.Value.ToLower() == strValue.ToLower() || x.Text.ToLower() == strText.ToLower());
if (i >= 0)
{
// ITEM ALREADY EXISTS -- UPDATE IT
Items[i].Value = strValue;
Items[i].Text = strText;
Items[i].SubText = strSub;
Items[i].SetIcon(sprIcon);
} else {
// ITEM DOES NOT EXIST -- CREATE IT
_intItemCount++;
i = Items.Count;
GameObject go = (GameObject)Instantiate(ListBoxLineItemPrefabObject);
PrivAddItem(go, i, strValue, strText, sprIcon, strSub);
}
}
private void PrivAddItem( string strValue, string strText, Sprite sprIcon, string strSub = "")
{
// CHECK IF LINE ITEM PREFAB EXISTS
if (ListBoxLineItemPrefabObject == null)
{
Debug.LogError(gameObject.name + " is Missing the Line Item Prefab. Please add the Prefab.");
return;
} else if (ListBoxLineItemPrefabObject.GetComponent<ListBoxLineItem>() == null) {
Debug.LogError(gameObject.name + " is Missing the Line Item Prefab. Please add the Prefab.");
return;
}
int i = Items.FindIndex(x => x.Value.ToLower() == strValue.ToLower() || x.Text.ToLower() == strText.ToLower());
if (i >= 0)
{
// ITEM ALREADY EXISTS -- UPDATE IT
Items[i].Value = strValue;
Items[i].Text = strText;
Items[i].SubText = strSub;
Items[i].SetIcon(sprIcon);
} else {
// ITEM DOES NOT EXIST -- CREATE IT
_intItemCount++;
i = Items.Count;
GameObject go = (GameObject)Instantiate(ListBoxLineItemPrefabObject);
PrivAddItem(go, i, strValue, strText, sprIcon, strSub);
}
}
private void PrivAddItem(GameObject go, int intIndex, string strValue, string strText, Sprite sprIcon, string strSub = "")
{
go.transform.SetParent(ScrollContainerObject.transform, false);
CanvasScaler scaler = go.transform.GetComponentInParent<CanvasScaler>();
if (scaler != null && scaler.uiScaleMode == CanvasScaler.ScaleMode.ScaleWithScreenSize)
{
// If the parent Canvas Scaler has UI Scale Mode set to "ScaleWithScreenSize", it messes up the item's scale, so we reset it to 1
go.GetComponent<RectTransform>().localScale = Vector3.one;
go.transform.localScale = Vector3.one;
}
go.GetComponent<ListBoxLineItem>().ListBoxControlObject = this.gameObject;
go.GetComponent<ListBoxLineItem>().Index = intIndex;
go.GetComponent<ListBoxLineItem>().Spacing = this.Spacing;
go.GetComponent<ListBoxLineItem>().Width = ContainerRect.sizeDelta.x - (this.Spacing * 2);
if (this.Height > 0)
go.GetComponent<ListBoxLineItem>().Height = this.Height;
else
this.Height = go.GetComponent<ListBoxLineItem>().Height;
go.GetComponent<ListBoxLineItem>().ItemNormalColor = ItemNormalColor;
go.GetComponent<ListBoxLineItem>().ItemHighlightColor = ItemHighlightColor;
go.GetComponent<ListBoxLineItem>().ItemSelectedColor = ItemSelectedColor;
go.GetComponent<ListBoxLineItem>().ItemDisabledColor = ItemDisabledColor;
go.GetComponent<ListBoxLineItem>().Value = strValue;
go.GetComponent<ListBoxLineItem>().Text = strText;
go.GetComponent<ListBoxLineItem>().SubText = strSub;
go.GetComponent<ListBoxLineItem>().SetIcon(sprIcon);
if (OnAddListItem != null)
OnAddListItem(go, intIndex);
go.GetComponent<ListBoxLineItem>().AutoSize();
Items.Add(go.GetComponent<ListBoxLineItem>());
ResizeContainer();
}
#endregion
#region "PUBLIC FUNCTIONS"
#region "LIST BOX STARTING ITEMS"
// -- CLEAR STARTING LIST
public void ClearStartItems()
{
_startArray = new List<StartingListItem>();
}
public void InitStartItems(List<StartingListItem> sli)
{
ClearStartItems();
foreach (StartingListItem s in sli)
{
_startArray.Add(s);
}
}
// -- ADD ITEM TO STARTING LIST
public virtual void AddStartItem(string strValue, string strText, Sprite sprIcon = null, string strSub = "")
{
int i = StartArray.FindIndex(x => x.Value.ToLower() == strValue.ToLower() || x.Text.ToLower() == strText.ToLower());
if (i >= 0)
{
// OVERWRITE EXISTING ITEM
StartArray[i].Value = strValue;
StartArray[i].Text = strText;
StartArray[i].Icon = sprIcon;
StartArray[i].SubText = strSub;
StartArray[i].Index = i;
} else {
StartArray.Add(new StartingListItem(strValue, strText, sprIcon, strSub));
StartArray[StartArray.Count - 1].Index = StartArray.Count - 1;
}
}
// -- REMOVE ITEM FROM STARTING LIST
public virtual void RemoveStartItemByIndex(int intIndex)
{
if (intIndex < 0 || intIndex >= StartArray.Count)
return;
for (int i = StartArray.Count - 1; i >= intIndex; i--)
{
if (i > intIndex)
{
// MOVE THE ITEM UP ONE SLOT
StartArray[i].Index = i - 1;
} else {
// REMOVE THE ITEM
StartArray.RemoveAt(i);
}
}
}
public virtual void RemoveStartItemByValue(string strValue)
{
int i = StartArray.FindIndex(x => x.Value.ToLower() == strValue.ToLower());
if (i >= 0)
RemoveStartItemByIndex(i);
}
public virtual void RemoveStartItemByText( string strText)
{
int i = StartArray.FindIndex(x => x.Text.ToLower() == strText.ToLower());
if (i >= 0)
RemoveStartItemByIndex(i);
}
// -- SORT ITEMS IN STARTING LIST
public virtual void SortStartByValue()
{
StartArray.Sort((p1, p2) => p1.Text.CompareTo(p2.Value));
for (int i = 0; i < StartArray.Count; i++)
{
StartArray[i].Index = i;
}
}
public virtual void SortStartByText()
{
StartArray.Sort((p1, p2) => p1.Text.CompareTo(p2.Text));
for (int i = 0; i < StartArray.Count; i++)
{
StartArray[i].Index = i;
}
}
public virtual void SortStartBySub()
{
StartArray.Sort((p1, p2) => p1.SubText.CompareTo(p2.SubText));
for (int i = 0; i < StartArray.Count; i++)
{
StartArray[i].Index = i;
}
}
#endregion
#region "LIST BOX ITEMS"
// HANDLE LISTBOX ITEMS
public virtual void Clear()
{
// INITIALIZE THE ITEM LIST
_intItemCount = 0;
_intSelectedItem = -1;
_items = new List<ListBoxLineItem>();
_intSelectedList = new List<int>();
// REMOVE ANY GAMEOBJECTS IN THE CONTAINER
if (ScrollContainerObject.transform.childCount > 0)
{
for (int i = ScrollContainerObject.transform.childCount - 1; i >= 0; i--)
Destroy(ScrollContainerObject.transform.GetChild(i).gameObject);
}
}
// -- ADD ITEM TO LISTBOX
public virtual void AddItem(string strValue, string strText, string strIcon = "", string strSub = "")
{
PrivAddItem(strValue, strText, strIcon, strSub);
}
public virtual void AddItem(string strValue, string strText, Sprite sprIcon, string strSub = "")
{
PrivAddItem(strValue, strText, sprIcon, strSub);
}
public virtual void AddItem(string strValue, string strText, string strIcon, int intSub)
{
AddItem(strValue, strText, strIcon, intSub.ToString());
}
public virtual void AddItem(string strValue, string strText, string strIcon, float fSub)
{
AddItem(strValue, strText, strIcon, fSub.ToString());
}
public virtual void AddItem(string strValue, string strText, Sprite sprIcon, int intSub)
{
AddItem(strValue, strText, sprIcon, intSub.ToString());
}
public virtual void AddItem(string strValue, string strText, Sprite sprIcon, float fSub)
{
AddItem(strValue, strText, sprIcon, fSub.ToString());
}
public virtual void AddItem(string[] strValue, string strText)
{
if (strValue != null && strValue.Length > 0 && strText.Trim() != "")
{
string strNewVal = "";
for (int i = 0; i < strValue.Length; i++)
strNewVal += SeparatorChar + strValue[i];
strNewVal = strNewVal.Substring(1);
AddItem(strNewVal, strText);
}
}
public virtual void AddItem(string[] strValue, string strText, string strIcon)
{
if (strValue != null && strValue.Length > 0 && strText.Trim() != "")
{
string strNewVal = "";
for (int i = 0; i < strValue.Length; i++)
strNewVal += SeparatorChar + strValue[i];
strNewVal = strNewVal.Substring(1);
AddItem(strNewVal, strText, strIcon);
}
}
public virtual void AddItem(string[] strValue, string strText, string strIcon, string strSub)
{
if (strValue != null && strValue.Length > 0 && strText.Trim() != "")
{
string strNewVal = "";
for (int i = 0; i < strValue.Length; i++)
strNewVal += SeparatorChar + strValue[i];
strNewVal = strNewVal.Substring(1);
AddItem(strNewVal, strText, strIcon, strSub);
}
}
public virtual void AddItem(string[] strValue, string strText, string strIcon, int intSub)
{
if (strValue != null && strValue.Length > 0 && strText.Trim() != "")
{
string strNewVal = "";
for (int i = 0; i < strValue.Length; i++)
strNewVal += SeparatorChar + strValue[i];
strNewVal = strNewVal.Substring(1);
AddItem(strNewVal, strText, strIcon, intSub.ToString());
}
}
public virtual void AddItem(string[] strValue, string strText, string strIcon, float fSub)
{
if (strValue != null && strValue.Length > 0 && strText.Trim() != "")
{
string strNewVal = "";
for (int i = 0; i < strValue.Length; i++)
strNewVal += SeparatorChar + strValue[i];
strNewVal = strNewVal.Substring(1);
AddItem(strNewVal, strText, strIcon, fSub.ToString());
}
}
public virtual void AddItem(string[] strValue, string strText, Sprite sprIcon)
{
if (strValue != null && strValue.Length > 0 && strText.Trim() != "")
{
string strNewVal = "";
for (int i = 0; i < strValue.Length; i++)
strNewVal += SeparatorChar + strValue[i];
strNewVal = strNewVal.Substring(1);
AddItem(strNewVal, strText, sprIcon);
}
}
public virtual void AddItem(string[] strValue, string strText, Sprite sprIcon, string strSub)
{
if (strValue != null && strValue.Length > 0 && strText.Trim() != "")
{
string strNewVal = "";
for (int i = 0; i < strValue.Length; i++)
strNewVal += SeparatorChar + strValue[i];
strNewVal = strNewVal.Substring(1);
AddItem(strNewVal, strText, sprIcon, strSub);
}
}
public virtual void AddItem(string[] strValue, string strText, Sprite sprIcon, int intSub)
{
if (strValue != null && strValue.Length > 0 && strText.Trim() != "")
{
string strNewVal = "";
for (int i = 0; i < strValue.Length; i++)
strNewVal += SeparatorChar + strValue[i];
strNewVal = strNewVal.Substring(1);
AddItem(strNewVal, strText, sprIcon, intSub.ToString());
}
}
public virtual void AddItem(string[] strValue, string strText, Sprite sprIcon, float fSub)
{
if (strValue != null && strValue.Length > 0 && strText.Trim() != "")
{
string strNewVal = "";
for (int i = 0; i < strValue.Length; i++)
strNewVal += SeparatorChar + strValue[i];
strNewVal = strNewVal.Substring(1);
AddItem(strNewVal, strText, sprIcon, fSub.ToString());
}
}
public virtual void AddItem(int intValue, string strText)
{
AddItem(intValue.ToString(), strText);
}
public virtual void AddItem(int intValue, string strText, string strIcon)
{
AddItem(intValue.ToString(), strText, strIcon);
}
public virtual void AddItem(int intValue, string strText, string strIcon, string strSub)
{
AddItem(intValue.ToString(), strText, strIcon, strSub);
}
public virtual void AddItem(int intValue, string strText, string strIcon, int intSub)
{
AddItem(intValue.ToString(), strText, strIcon, intSub.ToString());
}
public virtual void AddItem(int intValue, string strText, string strIcon, float fSub)
{
AddItem(intValue.ToString(), strText, strIcon, fSub.ToString());
}
public virtual void AddItem(int intValue, string strText, Sprite sprIcon)
{
AddItem(intValue.ToString(), strText, sprIcon);
}
public virtual void AddItem(int intValue, string strText, Sprite sprIcon, string strSub)
{
AddItem(intValue.ToString(), strText, sprIcon, strSub);
}
public virtual void AddItem(int intValue, string strText, Sprite sprIcon, int intSub)
{
AddItem(intValue.ToString(), strText, sprIcon, intSub.ToString());
}
public virtual void AddItem(int intValue, string strText, Sprite sprIcon, float fSub)
{
AddItem(intValue.ToString(), strText, sprIcon, fSub.ToString());
}
// -- REMOVE ITEM FROM LISTBOX
public virtual void RemoveItemByIndex(int intIndex)
{
if (intIndex < 0 || intIndex >= Items.Count)
return;
if (OnRemoveListItem != null)
OnRemoveListItem(Items[intIndex].gameObject, intIndex);
for (int i = Items.Count - 1; i >= intIndex; i--)
{
if (i > intIndex)
{
// MOVE THE ITEM UP ONE SLOT
Items[i].Index = i - 1;
Items[i].AutoSize();
} else {
// REMOVE THE ITEM
Items[i].Destroy();
Items.RemoveAt(i);
}
}
_intItemCount--;
_intSelectedItem = -1;
_intSelectedList = new List<int>();
ResizeContainer();
}
public virtual void RemoveItemByValue(string strValue)
{
int i = Items.FindIndex(x => x.Value.ToLower() == strValue.ToLower());
if (i >= 0)
RemoveItemByIndex(i);
}
public virtual void RemoveItemByText( string strText)
{
int i = Items.FindIndex(x => x.Text.ToLower() == strText.ToLower());
if (i >= 0)
RemoveItemByIndex(i);
}
// -- SORT LISTBOX ITEMS
public virtual void Sort()
{
SortByText();
}
public virtual void SortByText()
{
Items.Sort((p1, p2) => p1.Text.CompareTo(p2.Text));
for (int i = 0; i < Items.Count; i++)
{
Items[i].Index = i;
Items[i].AutoSize();
}
}
public virtual void SortByValue()
{
Items.Sort((p1, p2) => p1.Value.CompareTo(p2.Value));
for (int i = 0; i < Items.Count; i++)
{
Items[i].Index = i;
Items[i].AutoSize();
}
}
public virtual void SortBySubText()
{
Items.Sort((p1, p2) => p1.SubText.CompareTo(p2.SubText));
for (int i = 0; i < Items.Count; i++)
{
Items[i].Index = i;
Items[i].AutoSize();
}
}
// -- SET LISTBOX SCROLLBAR POSITION
public virtual void SetToTop()
{
if (gameObject.activeInHierarchy)
StartCoroutine(SetScroll(1));
}
public virtual void SetToBottom()
{
if (gameObject.activeInHierarchy)
StartCoroutine(SetScroll(0));
}
public virtual void SetToIndex(int intIndex)
{
// SET THE SCROLLBAR TO MAKE THE SELECTED INDEX (intIndex) VISIBLE IN THE SCROLL CONTAINER
float c = ContainerRect.rect.height; // THE HEIGHT OF THE LISTBOX CONTAINER (VISIBLE TO THE USER)
float h = Height + Spacing; // THE HEIGHT OF AN INDIVIDUAL LIST ITEM
float t = ((((float) _items.Count - 2) * h) + Spacing); // THE TOTAL HEIGHT OF CONTAINER OF ALL LIST ITEMS
float p = (((float) intIndex) * h); // THE Y-POS OF AN INDIVIDUAL LIST ITEM
float f = 1.00f;
if (p >= t - c )
f = 1.00f - (p / t);
else
f = 1.00f - (p / (t - c));
if (intIndex < 1)
f = 1;
if (gameObject.activeInHierarchy)
StartCoroutine(SetScroll(f));
}
// -- CHECK FOR LISTBOX ITEM WITH VALUE
public virtual bool HasItemWithValue(string strValue)
{
return Items.FindIndex(x => x.Value.Trim().ToLower() == strValue.Trim().ToLower()) >= 0;
}
public virtual bool HasItemWithValue(int intValue)
{
return HasItemWithValue(intValue.ToString());
}
public virtual bool HasItemWithValue(float fValue)
{
return HasItemWithValue(fValue.ToString());
}
// -- ENABLE ONCLICK FOR LISTBOX ITEM (ALSO ADJUSTS ITEM STYLE)
public virtual void EnableByIndex(int intIndex)
{
if (intIndex >= 0 && intIndex < Items.Count)
Items[intIndex].Enabled = true;
}
public virtual void EnableByValue(string strValue)
{
EnableByIndex(Items.FindIndex(x => x.Value.ToLower() == strValue.ToLower()));
}
public virtual void EnableByValue(int intValue)
{
EnableByIndex(Items.FindIndex(x => x.Value.ToLower() == intValue.ToString().ToLower()));
}
public virtual void EnableByText(string strText)
{
EnableByIndex(Items.FindIndex(x => x.Text.ToLower() == strText.ToLower()));
}
// -- DISABLE ONCLICK FOR LISTBOX ITEM (ALSO ADJUSTS ITEM STYLE)
public virtual void DisableByIndex(int intIndex)
{
if (intIndex >= 0 && intIndex < Items.Count)
Items[intIndex].Enabled = false;
}
public virtual void DisableByValue(string strValue)
{
DisableByIndex(Items.FindIndex(x => x.Value.ToLower() == strValue.ToLower()));
}
public virtual void DisableByValue(int intValue)
{
DisableByIndex(Items.FindIndex(x => x.Value.ToLower() == intValue.ToString().ToLower()));
}
public virtual void DisableByText(string strText)
{
DisableByIndex(Items.FindIndex(x => x.Text.ToLower() == strText.ToLower()));
}
// -- SET LISTBOX ITEM TEXT
public virtual void SetItemTextByIndex(int intIndex, string strNewText)
{
Items[intIndex].Text = strNewText;
}
public virtual void SetItemTextByValue(string strValue, string strNewText)
{
int i = Items.FindIndex(x => x.Value == strValue);
if (i >= 0)
SetItemTextByIndex(i, strNewText);
}
public virtual void SetItemTextByValue(int intValue, string strNewText)
{
SetItemTextByValue(intValue.ToString(), strNewText);
}
// -- SET LISTBOX ITEM SUBTEXT
public virtual void SetItemSubTextByIndex(int intIndex, string strNewText)
{
Items[intIndex].SubText = strNewText;
}
public virtual void SetItemSubTextByValue(string strValue, string strNewText)
{
int i = Items.FindIndex(x => x.Value == strValue);
if (i >= 0)
SetItemSubTextByIndex(i, strNewText);
}
public virtual void SetItemSubTextByValue(int intValue, string strNewText)
{
SetItemSubTextByValue(intValue.ToString(), strNewText);
}
// -- CHANGE ITEM ORDER
public virtual bool MoveItemUp( int intIndex)
{
if (intIndex < 1)
return false;
// UNSELECT BOTH ITEMS
bool blnOrig = IsSelectedByIndex(intIndex);
bool blnTrgt = IsSelectedByIndex(intIndex - 1);
UnSelectItem(intIndex);
UnSelectItem(intIndex - 1);
// MOVE THE ITEM
ListBoxLineItem liOrig = _items[intIndex];
ListBoxLineItem liTrgt = _items[intIndex - 1];
liOrig.Index--;
liTrgt.Index++;
_items[intIndex] = liTrgt;
_items[intIndex - 1] = liOrig;
_items[intIndex].AutoSize();
_items[intIndex - 1].AutoSize();
// UPDATE SELECTION
if (blnTrgt)
SelectByIndex(intIndex);
if (blnOrig)
SelectByIndex(intIndex - 1);
if (_intSelectedItem == intIndex)
_intSelectedItem--;
return true;
}
public virtual bool MoveItemDown( int intIndex)
{
if (intIndex < 0 || intIndex >= _items.Count - 1)
return false;
// UNSELECT BOTH ITEMS
bool blnOrig = IsSelectedByIndex(intIndex);
bool blnTrgt = IsSelectedByIndex(intIndex + 1);
UnSelectItem(intIndex);
UnSelectItem(intIndex + 1);
// MOVE THE ITEM
ListBoxLineItem liOrig = _items[intIndex];
ListBoxLineItem liTrgt = _items[intIndex + 1];
liOrig.Index++;
liTrgt.Index--;
_items[intIndex] = liTrgt;
_items[intIndex + 1] = liOrig;
_items[intIndex].AutoSize();
_items[intIndex + 1].AutoSize();
// UPDATE SELECTION
if (blnTrgt)
SelectByIndex(intIndex);
if (blnOrig)
SelectByIndex(intIndex + 1);
if (_intSelectedItem == intIndex)
_intSelectedItem++;
return true;
}
// -- GET LISTBOX ITEM VALUE
public virtual string GetValueByText(string strText)
{
int i = Items.FindIndex(x => x.Text.ToLower() == strText.Trim().ToLower());
if (i < 0)
return "";
else
return Items[i].Value;
}
public virtual string GetValueByIndex(int intIndex)
{
if (intIndex < 0 || intIndex >= Items.Count)
return "";
return Items[intIndex].Value;
}
public virtual int GetIntValueByIndex(int intIndex)
{
if (intIndex < 0 || intIndex >= Items.Count)
return -1;
return Util.ConvertToInt(Items[intIndex].Value);
}
// -- GET LISTBOX ITEM TEXT
public virtual string GetTextByValue(string strvalue)
{
int i = Items.FindIndex(x => x.Value.ToLower() == strvalue.Trim().ToLower());
if (i < 0)
return "";
else
return Items[i].Text;
}
public virtual string GetTextByValue(int intValue)
{
return GetTextByValue(intValue.ToString());
}
public virtual string GetTextByValue(float fValue)
{
return GetTextByValue(fValue.ToString());
}
public virtual string GetTextByIndex(int intIndex)
{
if (intIndex < 0 || intIndex >= Items.Count)
return "";
return Items[intIndex].Text;
}
// -- GET LISTBOX ITEM SUBTEXT
public virtual string GetSubTextByValue(string strvalue)
{
int i = Items.FindIndex(x => x.Value.ToLower() == strvalue.Trim().ToLower());
if (i < 0)
return "";
else
return Items[i].SubText;
}
public virtual string GetSubTextByValue(int intValue)
{
return GetSubTextByValue(intValue.ToString());
}
public virtual string GetSubTextByValue(float fValue)
{
return GetSubTextByValue(fValue.ToString());
}
public virtual string GetSubTextByIndex(int intIndex)
{
if (intIndex < 0 || intIndex >= Items.Count)
return "";
return Items[intIndex].SubText;
}
// -- HANDLE SELECTION (SET LISTBOX ITEM SELECTED)
public virtual void SelectByIndex(int intIndex, bool blnShifted = false, bool blnCtrled = false)
{
// DATA INTEGRITY CHECK
if (intIndex < -1 || intIndex >= Items.Count)
return;
// MULTI-SELECT OVERRIDE
blnShifted = blnShifted && CanMultiSelect;
blnCtrled = blnCtrled && CanMultiSelect;
// UNSHIFTED/UNCONTROLLED/UNSELECTED CLICK -- (CLICKING FOR THE FIRST TIME)
if ((!blnShifted && !blnCtrled) || _intSelectedItem < 0)
{
UnSelectAllItems();
_intSelectedItem = intIndex;
if (_intSelectedItem >= 0 && Items[_intSelectedItem].Enabled)
{
Items[_intSelectedItem].Select();
_intSelectedList.Add(intIndex);
}
// CONTROLLED CLICK -- (ADD ITEM TO SELECTED LIST)
} else if (blnCtrled) {
if (intIndex >= 0 && intIndex < Items.Count && Items[intIndex].Enabled)
{
if (IsSelectedByIndex(intIndex))
UnSelectItem( intIndex);
else
{
Items[intIndex].Select();
_intSelectedList.Add(intIndex);
}
}
// SHIFT-CLICK -- (ADD RANGE OF ITEMS TO SELECTED LIST)
} else if (blnShifted) {
UnSelectAllItems();
SelectByRange(intIndex);
}
if (_intSelectedItem >= -1)
{
if (this.OnChange != null)
OnChange(this.gameObject, _intSelectedItem);
}
}
public virtual void SelectByValue(string strValue)
{
int i = Items.FindIndex(x => x.Value.ToLower() == strValue.ToLower());
SelectByIndex(i);
}
public virtual void SelectByText( string strText)
{
int i = Items.FindIndex(x => x.Text.ToLower() == strText.ToLower());
SelectByIndex(i);
}
public virtual void Unselect()
{
UnSelectAllItems();
_intSelectedItem = -1;
_intSelectedList = new List<int>();
}
public virtual void HandleDoubleClick(int intIndex)
{
// DATA INTEGRITY CHECK
if (!AllowDoubleClick)
return;
if (intIndex < -1 || intIndex >= Items.Count)
return;
// SELECT THE ITEM
UnSelectAllItems();
_intSelectedItem = intIndex;
if (_intSelectedItem >= 0 && Items[_intSelectedItem].Enabled)
{
Items[_intSelectedItem].Select();
_intSelectedList.Add(intIndex);
}
// PASS THE DOUBLE-CLICK EVENT TO THE ONDOUBLECLICK EVeNT
if (_intSelectedItem >= 0)
{
if (this.OnDoubleClick != null)
OnDoubleClick(this.gameObject, _intSelectedItem);
}
}
// -- HANDLE SELECTED INDEXES
public virtual bool IsSelectedByIndex(int intIndex)
{
return (_intSelectedItem == intIndex || _intSelectedList.FindIndex(x => x == intIndex) >= 0);
}
// -- RESIZE THE CONTAINER (IF NECESSARY)
public virtual void UpdateListBoxContainerSize()
{
Vector2 v2 = ContainerRect.sizeDelta;
v2.y = ((this.Height + this.Spacing) * Items.Count) + this.Spacing;
ContainerRect.sizeDelta = v2;
ResizeContainer();
}
// -- SHOW/HIDE THE LISTBOX CONTROL
public virtual void Hide()
{
gameObject.SetActive(true);
if (ListBoxMode == ListBoxModes.ListBox)
{
GetComponent<Image>().enabled = false;
if (ScrollBarObject != null)
ScrollBarObject.SetActive(false);
if (ScrollRectObject != null)
ScrollRectObject.SetActive(false);
if (ListBoxTitle != null)
ListBoxTitle.gameObject.SetActive(false);
}
}
public virtual void Show()
{
gameObject.SetActive(true);
if (ListBoxMode == ListBoxModes.ListBox)
{
GetComponent<Image>().enabled = true;
if (ScrollBarObject != null)
ScrollBarObject.SetActive(true);
if (ScrollRectObject != null)
ScrollRectObject.SetActive(true);
if (ListBoxTitle != null)
ListBoxTitle.gameObject.SetActive(true);
}
}
public virtual bool IsShown
{
get
{
if (ListBoxMode == ListBoxModes.ListBox)
{
return GetComponent<Image>().enabled && ScrollBarObject.activeSelf && ScrollRectObject.activeSelf;
}
return false;
}
}
#endregion
#endregion
#region "EVENT FUNCTIONS"
public event OnListBoxSelectChanged OnChange;
public event OnListBoxDoubleClick OnDoubleClick;
public event OnAddListItemEvent OnAddListItem;
public event OnRemoveListItemEvent OnRemoveListItem;
#endregion
}
|
RowellKataan/Unity-List-Box
|
Assets/Unity UI Controls/Scripts/ListBox Scripts/ListBoxControl.cs
|
C#
|
apache-2.0
| 40,922 |
package org.docksidestage.dockside.dbflute.whitebox.cbean.bigartist.innerjoin;
import org.dbflute.cbean.result.ListResultBean;
import org.docksidestage.dockside.dbflute.bsentity.dbmeta.MemberAddressDbm;
import org.docksidestage.dockside.dbflute.bsentity.dbmeta.MemberDbm;
import org.docksidestage.dockside.dbflute.bsentity.dbmeta.MemberServiceDbm;
import org.docksidestage.dockside.dbflute.bsentity.dbmeta.MemberStatusDbm;
import org.docksidestage.dockside.dbflute.bsentity.dbmeta.MemberWithdrawalDbm;
import org.docksidestage.dockside.dbflute.bsentity.dbmeta.ProductDbm;
import org.docksidestage.dockside.dbflute.bsentity.dbmeta.ProductStatusDbm;
import org.docksidestage.dockside.dbflute.bsentity.dbmeta.ServiceRankDbm;
import org.docksidestage.dockside.dbflute.bsentity.dbmeta.SummaryProductDbm;
import org.docksidestage.dockside.dbflute.bsentity.dbmeta.WithdrawalReasonDbm;
import org.docksidestage.dockside.dbflute.exbhv.PurchaseBhv;
import org.docksidestage.dockside.dbflute.exentity.Member;
import org.docksidestage.dockside.dbflute.exentity.Product;
import org.docksidestage.dockside.dbflute.exentity.ProductStatus;
import org.docksidestage.dockside.dbflute.exentity.Purchase;
import org.docksidestage.dockside.unit.UnitContainerTestCase;
/**
* @author jflute
* @since 0.6.0 (2008/01/16 Wednesday)
*/
public class WxCBInnerJoinStructuralPossibleTest extends UnitContainerTestCase {
// ===================================================================================
// Attribute
// =========
private PurchaseBhv purchaseBhv;
// ===================================================================================
// Basic
// =====
public void test_StructuralPossible_without_Query() {
// ## Arrange ##
ListResultBean<Purchase> purchaseList = purchaseBhv.selectList(cb -> {
/* ## Act ## */
cb.enableInnerJoinAutoDetect();
cb.setupSelect_Member().withMemberStatus();
cb.setupSelect_Member().withMemberAddressAsValid(currentLocalDate());
cb.setupSelect_Member().withMemberServiceAsOne().withServiceRank();
cb.setupSelect_Member().withMemberWithdrawalAsOne().withWithdrawalReason();
cb.setupSelect_Product().withProductStatus();
cb.setupSelect_SummaryProduct();
cb.query().addOrderBy_MemberId_Asc().addOrderBy_PurchaseDatetime_Desc();
pushCB(cb);
});
// ## Assert ##
assertNotSame(0, purchaseList.size());
for (Purchase purchase : purchaseList) {
Product product = purchase.getProduct().get();
ProductStatus productStatus = product.getProductStatus().get();
assertNotNull(product);
assertNotNull(productStatus);
log("[PURCHASE]: " + purchase.getPurchaseId() + ", " + product.getProductName() + ", " + productStatus);
Member member = purchase.getMember().get();
assertNotNull(member);
assertNotNull(member.getMemberStatus());
member.getMemberWithdrawalAsOne().ifPresent(withdrawal -> {
withdrawal.getWithdrawalReason().ifPresent(reason -> {
String reasonText = reason.getWithdrawalReasonText();
log(" [WDL-MEMBER]: " + member.getMemberId() + ", " + member.getMemberName() + ", " + reasonText);
assertNotNull(reasonText);
markHere("existsWithdrawal");
});
});
}
String sql = popCB().toDisplaySql();
assertTrue(sql.contains("inner join " + MemberDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + MemberStatusDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + MemberAddressDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + MemberServiceDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + ServiceRankDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + MemberWithdrawalDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + WithdrawalReasonDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + ProductDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + ProductStatusDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + SummaryProductDbm.getInstance().getTableDbName()));
assertMarked("existsWithdrawal");
}
public void test_StructuralPossible_trace_is_ManualInnerJoin() {
// ## Arrange ##
ListResultBean<Purchase> purchaseList = purchaseBhv.selectList(cb -> {
/* ## Act ## */
cb.enableInnerJoinAutoDetect();
cb.setupSelect_Member().withMemberStatus();
cb.setupSelect_Member().withMemberAddressAsValid(currentLocalDate());
cb.setupSelect_Member().withMemberServiceAsOne().withServiceRank();
cb.setupSelect_Member().withMemberWithdrawalAsOne().withWithdrawalReason();
cb.setupSelect_Product().withProductStatus();
cb.setupSelect_SummaryProduct();
cb.query().queryMember().queryMemberServiceAsOne().innerJoin();
cb.query().addOrderBy_MemberId_Asc().addOrderBy_PurchaseDatetime_Desc();
pushCB(cb);
});
// ## Assert ##
assertNotSame(0, purchaseList.size());
for (Purchase purchase : purchaseList) {
Product product = purchase.getProduct().get();
ProductStatus productStatus = product.getProductStatus().get();
assertNotNull(product);
assertNotNull(productStatus);
log("[PURCHASE]: " + purchase.getPurchaseId() + ", " + product.getProductName() + ", " + productStatus);
Member member = purchase.getMember().get();
assertNotNull(member);
assertNotNull(member.getMemberStatus());
member.getMemberWithdrawalAsOne().ifPresent(withdrawal -> {
withdrawal.getWithdrawalReason().ifPresent(reason -> {
String reasonText = reason.getWithdrawalReasonText();
log(" [WDL-MEMBER]: " + member.getMemberId() + ", " + member.getMemberName() + ", " + reasonText);
assertNotNull(reasonText);
markHere("existsWithdrawal");
});
});
}
String sql = popCB().toDisplaySql();
assertTrue(sql.contains("inner join " + MemberDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + MemberStatusDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + MemberAddressDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + MemberServiceDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + ServiceRankDbm.getInstance().getTableDbName())); // point
assertTrue(sql.contains("left outer join " + MemberWithdrawalDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + WithdrawalReasonDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + ProductDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + ProductStatusDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + SummaryProductDbm.getInstance().getTableDbName()));
assertMarked("existsWithdrawal");
}
public void test_StructuralPossible_trace_is_WhereUsedInnerJoin() {
// ## Arrange ##
ListResultBean<Purchase> purchaseList = purchaseBhv.selectList(cb -> {
/* ## Act ## */
cb.enableInnerJoinAutoDetect();
cb.setupSelect_Member().withMemberStatus();
cb.setupSelect_Member().withMemberAddressAsValid(currentLocalDate());
cb.setupSelect_Member().withMemberServiceAsOne().withServiceRank();
cb.setupSelect_Member().withMemberWithdrawalAsOne().withWithdrawalReason();
cb.setupSelect_Product().withProductStatus();
cb.setupSelect_SummaryProduct();
cb.query().queryMember().queryMemberServiceAsOne().setServiceRankCode_Equal_Gold();
cb.query().addOrderBy_MemberId_Asc().addOrderBy_PurchaseDatetime_Desc();
pushCB(cb);
});
// ## Assert ##
assertHasAnyElement(purchaseList);
for (Purchase purchase : purchaseList) {
purchase.getProduct().alwaysPresent(product -> {
assertTrue(product.getProductStatus().isPresent());
log("[PURCHASE]: " + purchase.getPurchaseId() + ", " + product.getProductName() + ", " + product.getProductStatus());
});
purchase.getMember().alwaysPresent(member -> {
assertTrue(member.getMemberStatus().isPresent());
member.getMemberWithdrawalAsOne().ifPresent(withdrawal -> {
withdrawal.getWithdrawalReason().ifPresent(reason -> {
String reasonText = reason.getWithdrawalReasonText();
log(" [WDL-MEMBER]: " + member.getMemberId() + ", " + member.getMemberName() + ", " + reasonText);
assertNotNull(reasonText);
markHere("existsWithdrawal");
});
});
});
}
String sql = popCB().toDisplaySql();
assertTrue(sql.contains("inner join " + MemberDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + MemberStatusDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + MemberAddressDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + MemberServiceDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + ServiceRankDbm.getInstance().getTableDbName())); // point
assertTrue(sql.contains("left outer join " + MemberWithdrawalDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + WithdrawalReasonDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + ProductDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("inner join " + ProductStatusDbm.getInstance().getTableDbName()));
assertTrue(sql.contains("left outer join " + SummaryProductDbm.getInstance().getTableDbName()));
assertMarked("existsWithdrawal");
}
}
|
dbflute-test/dbflute-test-active-dockside
|
src/test/java/org/docksidestage/dockside/dbflute/whitebox/cbean/bigartist/innerjoin/WxCBInnerJoinStructuralPossibleTest.java
|
Java
|
apache-2.0
| 10,990 |
package com.mx.dic.holder;
import javax.sql.DataSource;
public class DataSourceHolder {
public static DataSource dataSource=null;
public static DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
DataSourceHolder.dataSource = dataSource;
}
}
|
minxinjituan/micro
|
dicServiceBean/src/main/java/com/mx/dic/holder/DataSourceHolder.java
|
Java
|
apache-2.0
| 314 |
/*
* Copyright (c) 2017 by E. A. Graham, Jr.
*
* 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.thevortex.lighting.jinks.devices.hubs;
import org.thevortex.lighting.jinks.devices.ConnectionReading;
import org.thevortex.lighting.jinks.devices.FirmwareReading;
import org.thevortex.lighting.jinks.devices.Reading;
/**
* Hub last reading states.
*
* @author E. A. Graham Jr.
*/
public class HubLastReading extends Reading implements FirmwareReading, ConnectionReading {
public Value<String> getAgentSessionId() {
return getFor("agent_session_id");
}
public Value<Long> getDesiredKiddeRadioCode() {
return getFor("desired_kidde_radio_code");
}
public Value<String> getDesiredPairingMode() {
return getFor("desired_pairing_mode");
}
public Value<String> getDesiredPairingModeDuration() {
return getFor("desired_pairing_mode_duration");
}
public Value<String> getDesiredPairingPrefix() {
return getFor("desired_pairing_mode_prefix");
}
public Value<String> getHubVersion() {
return getFor("hub_version");
}
public Value<String> getIpAddress() {
return getFor("ip_address");
}
public Value<Long> getKiddeRadioCode() {
return getFor("kidde_radio_code");
}
public Value<String> getLocalControlId() {
return getFor("local_control_id");
}
public Value<String> getLocalControlPublicKey() {
return getFor("local_control_public_key");
}
public Value<String> getLocalControlPublicKeyHash() {
return getFor("local_control_public_key_hash");
}
public Value<String> getMacAddress() {
return getFor("mac_address");
}
public Value<String> getPairingMode() {
return getFor("pairing_mode");
}
public Value<Integer> getPairingModeDuration() {
return getFor("pairing_mode_duration");
}
public Value<String> getPairingPrefix() {
return getFor("pairing_prefix");
}
public Value<Boolean> getRemotePairable() {
return getFor("remote_pairable");
}
public Value<Boolean> getUpdateNeeded() {
return getFor("update_needed");
}
public Value<Boolean> getUpdatingFirmware() {
return getFor("updating_firmware");
}
}
|
EAGrahamJr/jinks
|
src/main/java/org/thevortex/lighting/jinks/devices/hubs/HubLastReading.java
|
Java
|
apache-2.0
| 2,817 |
package com.planet_ink.coffee_mud.Items.Basic;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2014 Bo Zimmerman
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.
*/
public class Chair extends StdRideable
{
@Override public String ID(){ return "Chair";}
protected String readableText="";
public Chair()
{
super();
setName("a chair");
basePhyStats.setWeight(150);
setDisplayText("a chair is here.");
setDescription("Looks like a nice comfortable wooden chair");
material=RawMaterial.RESOURCE_OAK;
baseGoldValue=5;
basePhyStats().setLevel(1);
setRideBasis(Rideable.RIDEABLE_SIT);
setRiderCapacity(1);
recoverPhyStats();
}
}
|
vjanmey/EpicMudfia
|
com/planet_ink/coffee_mud/Items/Basic/Chair.java
|
Java
|
apache-2.0
| 1,893 |
/*
* Copyright 2017 Young Digital Planet S.A.
*
* 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 eu.ydp.empiria.player.client.module.sourcelist.view;
import static org.fest.assertions.api.Assertions.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import com.google.gwt.event.dom.client.DragDropEventBase;
import com.google.gwt.junit.GWTMockUtilities;
import com.google.inject.Provider;
import eu.ydp.empiria.player.client.controller.body.InlineBodyGeneratorSocket;
import eu.ydp.empiria.player.client.gin.factory.TouchReservationFactory;
import eu.ydp.empiria.player.client.module.dragdrop.*;
import eu.ydp.empiria.player.client.module.sourcelist.presenter.SourceListPresenter;
import eu.ydp.empiria.player.client.ui.drop.FlowPanelWithDropZone;
import eu.ydp.empiria.player.client.util.dom.drag.DragDataObject;
import eu.ydp.empiria.player.client.util.events.internal.dragdrop.DragDropEventTypes;
import eu.ydp.gwtutil.client.util.geom.HasDimensions;
import org.junit.*;
import org.junit.runner.RunWith;
import org.mockito.*;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
@RunWith(MockitoJUnitRunner.class)
public class SourceListViewImplTest {
@InjectMocks
private SourceListViewImpl testObj;
@Mock
private SourceListPresenter sourceListPresenter;
@Mock
private TouchReservationFactory touchReservationFactory;
@Mock
private Provider<SourceListViewItem> sourceListViewItemProvider;
@Mock
private SourceListViewItem viewItem;
@Mock
private InlineBodyGeneratorSocket inlineBodyGeneratorSocket;
@Mock
private FlowPanelWithDropZone items;
private final int sourceListViewItemHeight = 11;
private final int sourceListViewItemWidth = 12;
@BeforeClass
public static void disarm() {
GWTMockUtilities.disarm();
}
@AfterClass
public static void rearm() {
GWTMockUtilities.restore();
}
@Before
public void before() {
when(sourceListViewItemProvider.get()).then(new Answer<SourceListViewItem>() {
@Override
public SourceListViewItem answer(InvocationOnMock invocation) throws Throwable {
doReturn(sourceListViewItemHeight).when(viewItem).getHeight();
doReturn(sourceListViewItemWidth).when(viewItem).getWidth();
return viewItem;
}
});
testObj.items = items;
}
@Test
public void testOnDragEventDragStart() throws Exception {
// given
String itemContent = "itemContent";
String itemId = "item";
SourceListPresenter sourceListPresenter = mock(SourceListPresenter.class);
String json = "{}";
DragDataObject dataObject = mock(DragDataObject.class);
doReturn(json).when(dataObject).toJSON();
when(sourceListPresenter.getDragDataObject(anyString())).thenReturn(dataObject);
DragDropEventBase event = mock(DragDropEventBase.class);
// when
testObj.createItem(new SourcelistItemValue(SourcelistItemType.TEXT, itemContent, itemId), inlineBodyGeneratorSocket);
testObj.setSourceListPresenter(sourceListPresenter);
testObj.onDragEvent(DragDropEventTypes.DRAG_START, viewItem, event);
// then
verify(event).setData(eq("json"), eq(json));
verify(sourceListPresenter).onDragEvent(eq(DragDropEventTypes.DRAG_START), eq(itemId));
}
@Test
public void shouldNotSetData_whenNotDragStartEvent() throws Exception {
// given
String itemContent = "itemContent";
String itemId = "item";
DragDropEventBase event = mock(DragDropEventBase.class);
// when
testObj.createItem(new SourcelistItemValue(SourcelistItemType.TEXT, itemContent, itemId), inlineBodyGeneratorSocket);
testObj.setSourceListPresenter(sourceListPresenter);
testObj.onDragEvent(DragDropEventTypes.DRAG_CANCEL, viewItem, event);
// then
verify(event, never()).setData(eq("json"), anyString());
verify(sourceListPresenter).onDragEvent(eq(DragDropEventTypes.DRAG_CANCEL), eq(itemId));
}
@Test
public void shouldGetItemValue() {
// given
testObj.createItem(new SourcelistItemValue(SourcelistItemType.TEXT, "a", "a"), inlineBodyGeneratorSocket);
// when
testObj.getItemValue("a");
// then
verify(viewItem).getItemContent();
}
@Test
public void shouldCreateItem() {
// given
String itemContent = "itemContent";
String itemId = "item";
doReturn(viewItem).when(sourceListViewItemProvider).get();
// when
SourcelistItemValue sourcelistItemValue = new SourcelistItemValue(SourcelistItemType.TEXT, itemId, itemContent);
testObj.createItem(sourcelistItemValue, inlineBodyGeneratorSocket);
// then
verify(sourceListViewItemProvider).get();
verify(items).add(eq(sourceListViewItemProvider.get()));
verify(sourceListViewItemProvider.get()).setSourceListView(eq(testObj));
verify(sourceListViewItemProvider.get()).createAndBindUi(eq(sourcelistItemValue), eq(inlineBodyGeneratorSocket));
}
@Test
public void shouldHideItem() {
// given
testObj.createItem(new SourcelistItemValue(SourcelistItemType.TEXT, "a", "a"), inlineBodyGeneratorSocket);
// when
testObj.hideItem("a");
// then
verify(viewItem).hide();
}
@Test
public void shouldNotHideItem_whenIdNotPresent() {
// given
testObj.createItem(new SourcelistItemValue(SourcelistItemType.TEXT, "a", "a"), inlineBodyGeneratorSocket);
// when
testObj.hideItem("aa");
// then
verify(viewItem, never()).show();
}
@Test
public void shouldShowItem() {
// given
testObj.createItem(new SourcelistItemValue(SourcelistItemType.TEXT, "a", "a"), inlineBodyGeneratorSocket);
// when
testObj.showItem("a");
// then
verify(viewItem).show();
}
@Test
public void shouldNotShowItem_whenIdNotPresent() {
// given
testObj.createItem(new SourcelistItemValue(SourcelistItemType.TEXT, "a", "a"), inlineBodyGeneratorSocket);
// when
testObj.showItem("aa");
// then
verify(viewItem, never()).show();
}
@Test
public void shouldLockItemForDrag() {
// given
testObj.createItem(new SourcelistItemValue(SourcelistItemType.TEXT, "a", "a"), inlineBodyGeneratorSocket);
// when
testObj.lockItemForDragDrop("a");
// then
verify(viewItem).lockForDragDrop();
}
@Test
public void shouldUnlockItemForDrag() {
// given
testObj.createItem(new SourcelistItemValue(SourcelistItemType.TEXT, "a", "a"), inlineBodyGeneratorSocket);
// when
testObj.unlockItemForDragDrop("a");
// then
verify(viewItem).unlockForDragDrop();
}
@Test
public void shouldGetMaxItemSize() {
// given
testObj.createItem(new SourcelistItemValue(SourcelistItemType.TEXT, "a", "a"), inlineBodyGeneratorSocket);
// when
HasDimensions maxItemSize = testObj.getMaxItemSize();
// then
assertThat(maxItemSize.getHeight()).isEqualTo(sourceListViewItemHeight);
assertThat(maxItemSize.getWidth()).isEqualTo(sourceListViewItemWidth);
}
}
|
YoungDigitalPlanet/empiria.player
|
src/test/java/eu/ydp/empiria/player/client/module/sourcelist/view/SourceListViewImplTest.java
|
Java
|
apache-2.0
| 8,356 |
// Copyright (c) Martin Costello, 2017. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using Alexa.NET.Request;
using Alexa.NET.Request.Type;
using Alexa.NET.Response;
using Amazon.Lambda.Core;
namespace MartinCostello.LondonTravel.Skill;
public class AlexaFunctionTests : FunctionTests
{
public AlexaFunctionTests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
[Fact]
public async Task Cannot_Invoke_Function_If_Application_Id_Incorrect()
{
// Arrange
AlexaFunction function = await CreateFunctionAsync();
SkillRequest request = CreateIntentRequest("AMAZON.HelpIntent");
request.Session.Application.ApplicationId = "not-my-skill-id";
ILambdaContext context = CreateContext();
// Act
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(
async () => await function.HandlerAsync(request, context));
// Assert
exception.Message.ShouldBe("Request application Id 'not-my-skill-id' and configured skill Id 'my-skill-id' mismatch.");
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("____")]
[InlineData("qps-Ploc")]
public async Task Can_Invoke_Function_If_Locale_Is_Invalid(string locale)
{
// Arrange
AlexaFunction function = await CreateFunctionAsync();
SkillRequest request = CreateIntentRequest("AMAZON.HelpIntent");
request.Request.Locale = locale;
ILambdaContext context = CreateContext();
// Act
SkillResponse actual = await function.HandlerAsync(request, context);
// Assert
ResponseBody response = AssertResponse(actual, shouldEndSession: false);
response.OutputSpeech.ShouldNotBeNull();
response.OutputSpeech.Type.ShouldBe("SSML");
}
[Fact]
public async Task Cannot_Invoke_Function_With_System_Failure()
{
// Arrange
AlexaFunction function = await CreateFunctionAsync();
ILambdaContext context = CreateContext();
var error = new SystemExceptionRequest()
{
Error = new Error()
{
Message = "Internal error.",
Type = ErrorType.InternalError,
},
ErrorCause = new ErrorCause()
{
requestId = "my-request-id",
},
};
var request = CreateRequest(error);
// Act
SkillResponse actual = await function.HandlerAsync(request, context);
// Assert
ResponseBody response = AssertResponse(actual);
response.Card.ShouldBeNull();
response.Reprompt.ShouldBeNull();
response.OutputSpeech.ShouldNotBeNull();
response.OutputSpeech.Type.ShouldBe("SSML");
var ssml = response.OutputSpeech.ShouldBeOfType<SsmlOutputSpeech>();
ssml.Ssml.ShouldBe("<speak>Sorry, something went wrong.</speak>");
}
}
|
martincostello/alexa-london-travel
|
test/LondonTravel.Skill.Tests/AlexaFunctionTests.cs
|
C#
|
apache-2.0
| 3,076 |
package com.cloudera.sa.hcu.io.utils;
import java.io.File;
import java.util.ArrayList;
public class LocalFileUtils
{
public static File[] createFileArray(String[] filePathArray)
{
ArrayList<File> fileList = new ArrayList<File>();
File[] tempFileArray;
for (String filePath: filePathArray)
{
File origFile = new File(filePath);
if (origFile.isDirectory())
{
tempFileArray = origFile.listFiles();
for (File file: tempFileArray)
{
fileList.add(file);
}
}else
{
fileList.add(origFile);
}
}
return fileList.toArray(new File[0]);
}
public static String[] createStringArrayOfFiles(String[] filePathArray)
{
ArrayList<String> filePathList = new ArrayList<String>();
File[] tempFileArray;
for (String filePath: filePathArray)
{
File origFile = new File(filePath);
if (origFile.isDirectory())
{
tempFileArray = origFile.listFiles();
for (File file: tempFileArray)
{
filePathList.add(file.getAbsolutePath());
}
}else
{
filePathList.add(origFile.getAbsolutePath());
}
}
return filePathList.toArray(new String[0]);
}
}
|
tmalaska/hadcom.utils
|
src/main/java/com/cloudera/sa/hcu/io/utils/LocalFileUtils.java
|
Java
|
apache-2.0
| 1,160 |
require 'ffi'
require_relative '../sodium/utils'
require_relative '../random_bytes'
require_relative '../sodium/secret_buffer'
require_relative '../sodium'
module Crypto
module SecretBox
extend FFI::Library
extend Sodium::Utils
ffi_lib :libsodium
attach_function :primitive, :crypto_secretbox_primitive, [], :string
attach_function :keybytes, :crypto_secretbox_keybytes, [], :size_t
attach_function :noncebytes, :crypto_secretbox_noncebytes, [], :size_t
attach_function :macbytes, :crypto_secretbox_macbytes, [], :size_t
PRIMITIVE = primitive.freeze
KEYBYTES = keybytes.freeze
NONCEBYTES = noncebytes.freeze
MACBYTES = macbytes.freeze
attach_function :crypto_secretbox_easy, [:buffer_out, :buffer_in, :ulong_long, :buffer_in, :buffer_in], :int
attach_function :crypto_secretbox_open_easy, [:buffer_out, :buffer_in, :ulong_long, :buffer_in, :buffer_in], :int
attach_function :crypto_secretbox_detached, [:buffer_out, :buffer_out, :buffer_in, :ulong_long, :buffer_in, :buffer_in], :int
attach_function :crypto_secretbox_open_detached, [:buffer_out, :buffer_out, :buffer_in, :ulong_long, :buffer_in, :buffer_in], :int
module_function
def nonce
RandomBytes.buf(NONCEBYTES)
end
def secretbox(message, nonce, key)
message_len = get_size(message)
check_length(nonce, NONCEBYTES, :Nonce)
check_length(key, KEYBYTES, :SecretKey)
ciphertext = zeros(message_len + MACBYTES)
key.readonly if key.is_a?(Sodium::SecretBuffer)
crypto_secretbox_easy(ciphertext, message, message_len, nonce, key)
ciphertext
ensure
key.noaccess if key.is_a?(Sodium::SecretBuffer)
end
def open(ciphertext, nonce, key, encoding = nil)
ciphertext_len = get_size(ciphertext)
check_length(nonce, NONCEBYTES, :Nonce)
check_length(key, KEYBYTES, :SecretKey)
decrypted = zeros(ciphertext_len - MACBYTES)
key.readonly if key.is_a?(Sodium::SecretBuffer)
if crypto_secretbox_open_easy(decrypted, ciphertext, ciphertext_len, nonce, key) == -1
raise Sodium::CryptoError, "Message forged", caller
end
if encoding
decrypted.force_encoding(encoding)
end
decrypted
ensure
key.noaccess if key.is_a?(Sodium::SecretBuffer)
end
def secretbox!(data, nonce, key)
message = String(data)
check_length(nonce, NONCEBYTES, :Nonce)
check_length(key, KEYBYTES, :SecretKey)
message_len = message.bytesize
message << zeros(MACBYTES)
key.readonly if key.is_a?(Sodium::SecretBuffer)
crypto_secretbox_easy(message, message, message_len, nonce, key)
message.force_encoding(Encoding::ASCII_8BIT)
ensure
key.noaccess if key.is_a?(Sodium::SecretBuffer)
end
def open!(data, nonce, key, encoding = nil)
ciphertext = String(data)
if (message_len = (ciphertext_len = ciphertext.bytesize) - MACBYTES) < 0
fail Sodium::LengthError, "Ciphertext is too short", caller
end
check_length(nonce, NONCEBYTES, :Nonce)
check_length(key, KEYBYTES, :SecretKey)
key.readonly if key.is_a?(Sodium::SecretBuffer)
if crypto_secretbox_open_easy(ciphertext, ciphertext, ciphertext_len, nonce, key) == -1
raise Sodium::CryptoError, "Message forged", caller
end
ciphertext.slice!(message_len..-1)
if encoding
ciphertext.force_encoding(encoding)
end
ciphertext
ensure
key.noaccess if key.is_a?(Sodium::SecretBuffer)
end
def detached(message, nonce, key)
message_len = get_size(message)
check_length(nonce, NONCEBYTES, :Nonce)
check_length(key, KEYBYTES, :SecretKey)
ciphertext = zeros(message_len)
mac = zeros(MACBYTES)
key.readonly if key.is_a?(Sodium::SecretBuffer)
crypto_secretbox_detached(ciphertext, mac, message, message_len, nonce, key)
[ciphertext, mac]
ensure
key.noaccess if key.is_a?(Sodium::SecretBuffer)
end
def open_detached(ciphertext, mac, nonce, key, encoding = nil)
ciphertext_len = get_size(ciphertext)
check_length(mac, MACBYTES, :Mac)
check_length(nonce, NONCEBYTES, :Nonce)
check_length(key, KEYBYTES, :SecretKey)
message = zeros(ciphertext_len)
key.readonly if key.is_a?(Sodium::SecretBuffer)
if crypto_secretbox_open_detached(message, ciphertext, mac, ciphertext_len, nonce, key) == -1
raise Sodium::CryptoError, "Message forged", caller
end
if encoding
message.force_encoding(encoding)
end
message
ensure
key.noaccess if key.is_a?(Sodium::SecretBuffer)
end
def detached!(message, nonce, key)
check_length(nonce, NONCEBYTES, :Nonce)
check_length(key, KEYBYTES, :SecretKey)
mac = zeros(MACBYTES)
key.readonly if key.is_a?(Sodium::SecretBuffer)
crypto_secretbox_detached(message, mac, message, get_size(message), nonce, key)
[message, mac]
ensure
key.noaccess if key.is_a?(Sodium::SecretBuffer)
end
def open_detached!(ciphertext, mac, nonce, key, encoding = nil)
check_length(mac, MACBYTES, :Mac)
check_length(nonce, NONCEBYTES, :Nonce)
check_length(key, KEYBYTES, :SecretKey)
key.readonly if key.is_a?(Sodium::SecretBuffer)
if crypto_secretbox_open_detached(ciphertext, ciphertext, mac, get_size(ciphertext), nonce, key) == -1
raise Sodium::CryptoError, "Message forged", caller
end
if encoding && ciphertext.respond_to?(:force_encoding)
ciphertext.force_encoding(encoding)
end
ciphertext
ensure
key.noaccess if key.is_a?(Sodium::SecretBuffer)
end
end
SecretBox.freeze
module_function
def secretbox(*args)
SecretBox.secretbox(*args)
end
def secretbox!(*args)
SecretBox.secretbox!(*args)
end
end
|
Asmod4n/ruby-ffi-libsodium
|
lib/crypto/secret_box.rb
|
Ruby
|
apache-2.0
| 5,944 |
/*
* Copyright 2014 Massachusetts General Hospital
*
* 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.mindinformatics.gwt.domeo.plugins.persistence.annotopia.serializers;
import java.util.List;
import org.mindinformatics.gwt.domeo.model.MAnnotation;
import org.mindinformatics.gwt.domeo.model.MAnnotationSet;
import org.mindinformatics.gwt.domeo.model.persistence.ontologies.IDomeoOntology;
import org.mindinformatics.gwt.domeo.model.persistence.ontologies.IPavOntology;
import org.mindinformatics.gwt.domeo.model.persistence.ontologies.IRdfsOntology;
import org.mindinformatics.gwt.domeo.plugins.persistence.annotopia.model.IAnnotopia;
import org.mindinformatics.gwt.framework.src.Utils;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
/**
* This class serializes the Annotation Set to Annotopia JSON format.
*
* @author Paolo Ciccarese <paolo.ciccarese@gmail.com>
*/
public class SAnnotationSetSerializer extends AAnnotopiaSerializer implements IAnnotopiaSerializer {
@Override
public JSONObject serialize(AnnotopiaSerializerManager manager, Object obj) {
MAnnotationSet annotationSet = (MAnnotationSet) obj;
JSONObject annotationSetJson = new JSONObject();
annotationSetJson.put(IRdfsOntology.type, new JSONString(IAnnotopia.ANNOTATION_SET));
// These have to exist and defined
// TODO HIGH track exception when any of these is null or blank
annotationSetJson.put("@context",new JSONString(Utils.getAnnotopiaContextPath( )));
annotationSetJson.put(IRdfsOntology.id, new JSONString(annotationSet.getIndividualUri()));
annotationSetJson.put(IDomeoOntology.transientLocalId, new JSONString(Long.toString(annotationSet.getLocalId())));
annotationSetJson.put("serializedBy",new JSONString("urn:application:domeo"));
//annotationSetJson.put(IDomeoOntology.annotates, new JSONString(annotationSet.getTargetResource().getUrl()));
//manager.addResourceToSerialize(annotationSet.getTargetResource());
// Creation
// --------------------------------------------------------------------
if(annotationSet.getCreatedBy()!=null) {
//manager.addAgentToSerialize(annotationSet.getCreatedBy());
annotationSetJson.put("createdBy", manager.serialize(annotationSet.getCreatedBy()));
//annotationSetJson.put(IPavOntology.createdBy, serializeAgent(manager, annotationSet.getCreatedBy()));
} else {
// Warning/Exception?
}
if(annotationSet.getCreatedOn()!=null) {
annotationSetJson.put("createdAt", new JSONString(Utils.fullfmt2.format(annotationSet.getCreatedOn())));
} else {
// Warning/Exception?
}
if(annotationSet.getCreatedWith()!=null) {
//manager.addAgentToSerialize(annotationSet.getCreatedWith());
annotationSetJson.put("createdWith", manager.serialize(annotationSet.getCreatedWith()));
//annotationSetJson.put(IPavOntology.createdWith, serializeAgent(manager, annotationSet.getCreatedWith()));
} else {
// Warning/Exception?
}
if(annotationSet.getLastSavedOn()!=null) {
annotationSetJson.put("lastUpdateOn", new JSONString(Utils.fullfmt2.format(annotationSet.getLastSavedOn())));
}
// Imports
// --------------------------------------------------------------------
if(annotationSet.getImportedFrom()!=null) {
//manager.addAgentToSerialize(annotationSet.getImportedFrom());
annotationSetJson.put(IPavOntology.importedFrom, new JSONString(annotationSet.getImportedFrom().getUri()));
//annotationSetJson.put(IPavOntology.importedFrom, serializeAgent(manager, annotationSet.getImportedFrom()));
}
if(annotationSet.getImportedBy()!=null) {
//manager.addAgentToSerialize(annotationSet.getImportedBy());
annotationSetJson.put(IPavOntology.importedBy, new JSONString(annotationSet.getImportedBy().getUri()));
//annotationSetJson.put(IPavOntology.importedBy, serializeAgent(manager, annotationSet.getImportedBy()));
}
if(annotationSet.getImportedOn()!=null) {
annotationSetJson.put(IPavOntology.importedOn, new JSONString(Utils.fullfmt2.format(annotationSet.getImportedOn())));
}
// These translate null values into blank strings
annotationSetJson.put("label", nullable(annotationSet.getLabel()));
annotationSetJson.put("description", nullable(annotationSet.getDescription()));
annotationSetJson.put("lineageUri", nullable(annotationSet.getLineageUri()));
annotationSetJson.put("version", nullable(annotationSet.getVersionNumber()));
annotationSetJson.put("previousVersion", nullable(annotationSet.getPreviousVersion()));
annotationSetJson.put("deleted", nullableBoolean(annotationSet.getIsDeleted()));
// Serialization of the annotation items that have changed
JSONArray annotations = new JSONArray();
List<MAnnotation> annotationsList = annotationSet.getAnnotations();
for(int i=0; i<annotationsList.size(); i++) {
//if(annotationsList.get(i).getHasChanged())
annotations.set(i, manager.serialize(annotationsList.get(i)));
}
annotationSetJson.put("annotations", annotations);
return annotationSetJson;
}
}
|
domeo/DomeoClient
|
src/org/mindinformatics/gwt/domeo/plugins/persistence/annotopia/serializers/SAnnotationSetSerializer.java
|
Java
|
apache-2.0
| 5,833 |
# Copyright © 2012 The Pennsylvania State University
#
# 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.
class BatchUpdateJob
include Hydra::AccessControlsEnforcement
include GenericFileHelper
include Rails.application.routes.url_helpers
def self.queue
:batch_update
end
def self.perform(*args)
new(*args)
end
def initialize(login, params, perms)
params = HashWithIndifferentAccess.new(params)
perms = HashWithIndifferentAccess.new(perms)
batch = Batch.find_or_create(params[:id])
user = User.find_by_login(login)
saved = []
denied = []
batch.generic_files.each do |gf|
unless user.can? :edit, get_permissions_solr_response_for_doc_id(gf.pid)[1]
logger.error "User #{user.login} DEEEENIED access to #{gf.pid}!"
denied << gf
next
end
gf.title = params[:title][gf.pid] if params[:title][gf.pid] rescue gf.label
gf.update_attributes(params[:generic_file])
gf.set_visibility(params)
save_tries = 0
begin
gf.save
rescue RSolr::Error::Http => error
save_tries += 1
logger.warn "BatchUpdateJob caught RSOLR error on #{gf.pid}: #{error.inspect}"
# fail for good if the tries is greater than 3
rescue_action_without_handler(error) if save_tries >=3
sleep 0.01
retry
end #
begin
Resque.enqueue(ContentUpdateEventJob, gf.pid, login)
rescue Redis::CannotConnectError
logger.error "Redis is down!"
end
saved << gf
end
batch.update_attributes({status:["Complete"]})
job_user = User.where(login:"batchuser").first
job_user = User.create(login:"batchuser", email:"batchmail") unless job_user
message = '<a class="batchid ui-helper-hidden">ss-'+batch.noid+'</a>The file(s) '+ file_list(saved)+ " have been saved." unless saved.empty?
job_user.send_message(user, message, 'Batch upload complete') unless saved.empty?
message = '<a class="batchid ui-helper-hidden">'+batch.noid+'</a>The file(s) '+ file_list(denied)+" could not be updated. You do not have sufficient privileges to edit it." unless denied.empty?
job_user.send_message(user, message, 'Batch upload permission denied') unless denied.empty?
end
def file_list ( files)
return files.map {|gf| '<a href="'+generic_files_path+'/'+gf.noid+'">'+display_title(gf)+'</a>'}.join(', ')
end
end
|
ndlib/scholarsphere
|
app/models/batch_update_job.rb
|
Ruby
|
apache-2.0
| 2,932 |
/*
* 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.
*/
namespace Apache.Ignite.Core.Impl.Transactions
{
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Transactions;
/// <summary>
/// Grid cache transaction implementation.
/// </summary>
internal sealed class TransactionImpl : IDisposable
{
/** Metadatas. */
private object[] _metas;
/** Unique transaction ID.*/
private readonly long _id;
/** Cache. */
private readonly TransactionsImpl _txs;
/** TX concurrency. */
private readonly TransactionConcurrency _concurrency;
/** TX isolation. */
private readonly TransactionIsolation _isolation;
/** Timeout. */
private readonly TimeSpan _timeout;
/** Start time. */
private readonly DateTime _startTime;
/** Owning thread ID. */
private readonly int _threadId;
/** Originating node ID. */
private readonly Guid _nodeId;
/** State holder. */
private StateHolder _state;
// ReSharper disable once InconsistentNaming
/** Transaction for this thread. */
[ThreadStatic]
private static TransactionImpl THREAD_TX;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="id">ID.</param>
/// <param name="txs">Transactions.</param>
/// <param name="concurrency">TX concurrency.</param>
/// <param name="isolation">TX isolation.</param>
/// <param name="timeout">Timeout.</param>
/// <param name="nodeId">The originating node identifier.</param>
public TransactionImpl(long id, TransactionsImpl txs, TransactionConcurrency concurrency,
TransactionIsolation isolation, TimeSpan timeout, Guid nodeId) {
_id = id;
_txs = txs;
_concurrency = concurrency;
_isolation = isolation;
_timeout = timeout;
_nodeId = nodeId;
_startTime = DateTime.Now;
_threadId = Thread.CurrentThread.ManagedThreadId;
THREAD_TX = this;
}
/// <summary>
/// Transaction assigned to this thread.
/// </summary>
public static Transaction Current
{
get
{
var tx = THREAD_TX;
if (tx == null)
return null;
if (tx.IsClosed)
{
THREAD_TX = null;
return null;
}
return new Transaction(tx);
}
}
/// <summary>
/// Executes prepare step of the two phase commit.
/// </summary>
public void Prepare()
{
lock (this)
{
ThrowIfClosed();
_txs.TxPrepare(this);
}
}
/// <summary>
/// Commits this tx and closes it.
/// </summary>
public void Commit()
{
lock (this)
{
ThrowIfClosed();
_state = new StateHolder(_txs.TxCommit(this));
}
}
/// <summary>
/// Rolls this tx back and closes it.
/// </summary>
public void Rollback()
{
lock (this)
{
ThrowIfClosed();
_state = new StateHolder(_txs.TxRollback(this));
}
}
/// <summary>
/// Sets the rollback only flag.
/// </summary>
public bool SetRollbackOnly()
{
lock (this)
{
ThrowIfClosed();
return _txs.TxSetRollbackOnly(this);
}
}
/// <summary>
/// Gets a value indicating whether this instance is rollback only.
/// </summary>
public bool IsRollbackOnly
{
get
{
lock (this)
{
var state0 = _state == null ? State : _state.State;
return state0 == TransactionState.MarkedRollback ||
state0 == TransactionState.RollingBack ||
state0 == TransactionState.RolledBack;
}
}
}
/// <summary>
/// Gets the state.
/// </summary>
public TransactionState State
{
get
{
lock (this)
{
return _state != null ? _state.State : _txs.TxState(this);
}
}
}
/// <summary>
/// Gets the isolation.
/// </summary>
public TransactionIsolation Isolation
{
get { return _isolation; }
}
/// <summary>
/// Gets the concurrency.
/// </summary>
public TransactionConcurrency Concurrency
{
get { return _concurrency; }
}
/// <summary>
/// Gets the timeout.
/// </summary>
public TimeSpan Timeout
{
get { return _timeout; }
}
/// <summary>
/// Gets the start time.
/// </summary>
public DateTime StartTime
{
get { return _startTime; }
}
/// <summary>
/// Gets the node identifier.
/// </summary>
public Guid NodeId
{
get { return _nodeId; }
}
/// <summary>
/// Gets the thread identifier.
/// </summary>
public long ThreadId
{
get { return _threadId; }
}
/// <summary>
/// Adds a new metadata.
/// </summary>
public void AddMeta<TV>(string name, TV val)
{
if (name == null)
throw new ArgumentException("Meta name cannot be null.");
lock (this)
{
if (_metas != null)
{
int putIdx = -1;
for (int i = 0; i < _metas.Length; i += 2)
{
if (name.Equals(_metas[i]))
{
_metas[i + 1] = val;
return;
}
if (_metas[i] == null && putIdx == -1)
// Preserve empty space index.
putIdx = i;
}
// No meta with the given name found.
if (putIdx == -1)
{
// Extend array.
putIdx = _metas.Length;
object[] metas0 = new object[putIdx + 2];
Array.Copy(_metas, metas0, putIdx);
_metas = metas0;
}
_metas[putIdx] = name;
_metas[putIdx + 1] = val;
}
else
_metas = new object[] { name, val };
}
}
/// <summary>
/// Gets metadata by name.
/// </summary>
public TV Meta<TV>(string name)
{
if (name == null)
throw new ArgumentException("Meta name cannot be null.");
lock (this)
{
if (_metas != null)
{
for (int i = 0; i < _metas.Length; i += 2)
{
if (name.Equals(_metas[i]))
return (TV)_metas[i + 1];
}
}
return default(TV);
}
}
/// <summary>
/// Removes metadata by name.
/// </summary>
public TV RemoveMeta<TV>(string name)
{
if (name == null)
throw new ArgumentException("Meta name cannot be null.");
lock (this)
{
if (_metas != null)
{
for (int i = 0; i < _metas.Length; i += 2)
{
if (name.Equals(_metas[i]))
{
TV val = (TV)_metas[i + 1];
_metas[i] = null;
_metas[i + 1] = null;
return val;
}
}
}
return default(TV);
}
}
/// <summary>
/// Commits tx in async mode.
/// </summary>
internal Task CommitAsync()
{
lock (this)
{
ThrowIfClosed();
return CloseWhenComplete(_txs.CommitAsync(this));
}
}
/// <summary>
/// Rolls tx back in async mode.
/// </summary>
internal Task RollbackAsync()
{
lock (this)
{
ThrowIfClosed();
return CloseWhenComplete(_txs.RollbackAsync(this));
}
}
/// <summary>
/// Transaction ID.
/// </summary>
internal long Id
{
get { return _id; }
}
/** <inheritdoc /> */
public void Dispose()
{
try
{
Close();
}
finally
{
GC.SuppressFinalize(this);
}
}
/// <summary>
/// Gets a value indicating whether this transaction is closed.
/// </summary>
private bool IsClosed
{
get { return _state != null; }
}
/// <summary>
/// Gets the closed exception.
/// </summary>
private InvalidOperationException GetClosedException()
{
return new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
"Transaction {0} is closed, state is {1}", Id, State));
}
/// <summary>
/// Creates a task via provided factory if IsClosed is false; otherwise, return a task with an error.
/// </summary>
internal Task GetTask(Func<Task> operationFactory)
{
lock (this)
{
return IsClosed ? GetExceptionTask() : operationFactory();
}
}
/// <summary>
/// Gets the task that throws an exception.
/// </summary>
private Task GetExceptionTask()
{
var tcs = new TaskCompletionSource<object>();
tcs.SetException(GetClosedException());
return tcs.Task;
}
/// <summary>
/// Closes the transaction and releases unmanaged resources.
/// </summary>
private void Close()
{
lock (this)
{
_state = _state ?? new StateHolder((TransactionState) _txs.TxClose(this));
}
}
/// <summary>
/// Throws and exception if transaction is closed.
/// </summary>
private void ThrowIfClosed()
{
if (IsClosed)
throw GetClosedException();
}
/// <summary>
/// Closes this transaction upon task completion.
/// </summary>
private Task CloseWhenComplete(Task task)
{
return task.ContWith(x => Close());
}
/** <inheritdoc /> */
~TransactionImpl()
{
Dispose();
}
/// <summary>
/// State holder.
/// </summary>
private class StateHolder
{
/** Current state. */
private readonly TransactionState _state;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="state">State.</param>
public StateHolder(TransactionState state)
{
_state = state;
}
/// <summary>
/// Current state.
/// </summary>
public TransactionState State
{
get { return _state; }
}
}
}
}
|
endian675/ignite
|
modules/platforms/dotnet/Apache.Ignite.Core/Impl/Transactions/TransactionImpl.cs
|
C#
|
apache-2.0
| 13,246 |
package com.nwea.dao;
import com.nwea.bean.Blogpost;
import java.sql.SQLException;
/**
* This interface will be used to invoke the database related operations.
*
*
* Created by tahmidchowdhury on 2/9/17.
*/
public interface BlogpostDAO {
//This method returns all the Blogposts from the database
public Blogpost[] getAllPosts() throws SQLException;
//This method inserts data into database table
public boolean insertBlogpost(String title, String body) throws SQLException;
}
|
tahmid29/blogpostapi
|
src/main/java/com/nwea/dao/BlogpostDAO.java
|
Java
|
apache-2.0
| 502 |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/api/quota.proto
require 'google/protobuf'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/api/quota.proto", :syntax => :proto3) do
add_message "google.api.Quota" do
repeated :limits, :message, 3, "google.api.QuotaLimit"
repeated :metric_rules, :message, 4, "google.api.MetricRule"
end
add_message "google.api.MetricRule" do
optional :selector, :string, 1
map :metric_costs, :string, :int64, 2
end
add_message "google.api.QuotaLimit" do
optional :name, :string, 6
optional :description, :string, 2
optional :default_limit, :int64, 3
optional :max_limit, :int64, 4
optional :free_tier, :int64, 7
optional :duration, :string, 5
optional :metric, :string, 8
optional :unit, :string, 9
map :values, :string, :int64, 10
optional :display_name, :string, 12
end
end
end
module Google
module Api
Quota = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.api.Quota").msgclass
MetricRule = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.api.MetricRule").msgclass
QuotaLimit = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.api.QuotaLimit").msgclass
end
end
|
googleapis/common-protos-ruby
|
googleapis-common-protos-types/lib/google/api/quota_pb.rb
|
Ruby
|
apache-2.0
| 1,330 |
<?php
/**
* Copyright 2015 yannick.
* 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
*/
/**
* Create HTML list of nav menu items.
*
* @since 3.0.0
* @uses Walker
*/
class Custom_walker_Nav_Menu extends Walker_Nav_Menu {
/**
* What the class handles.
*
* @see Walker::$tree_type
* @since 3.0.0
* @var string
*/
public $tree_type = array('post_type', 'taxonomy', 'custom');
/**
* Database fields to use.
*
* @see Walker::$db_fields
* @since 3.0.0
* @todo Decouple this.
* @var array
*/
public $db_fields = array('parent' => 'menu_item_parent', 'id' => 'db_id');
/**
* Starts the list before the elements are added.
*
* @see Walker::start_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function start_lvl(&$output, $depth = 0, $args = array()) {
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul class=\"dropdown-menu\" role=\"menu\">\n";
}
/**
* Ends the list of after the elements are added.
*
* @see Walker::end_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function end_lvl(&$output, $depth = 0, $args = array()) {
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul>\n";
}
/**
* Start the element output.
*
* @see Walker::start_el()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
* @param int $id Current item ID.
*/
public function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
$indent = ( $depth ) ? str_repeat("\t", $depth) : '';
/**
* Filter the ID applied to a menu item's list item element.
*
* @since 3.0.1
* @since 4.1.0 The `$depth` parameter was added.
*
* @param string $menu_id The ID that is applied to the menu item's `<li>` element.
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$id = apply_filters('nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth);
$id = $id ? ' id="' . esc_attr($id) . '"' : '';
$atts = array();
$atts['title'] = !empty($item->attr_title) ? $item->attr_title : '';
$atts['target'] = !empty($item->target) ? $item->target : '';
$atts['rel'] = !empty($item->xfn) ? $item->xfn : '';
$atts['href'] = !empty($item->url) ? $item->url : '';
/**
* Detect sub menu condition.
*/
if (!("$this->has_children" == "1")) {
$output .= $indent . '<li>';
if(is_object($args)) $args->link_after = '';
} else {
$output .= $indent . "<li class=\"dropdown\">";
$atts['class'] = 'dropdown-toggle';
$atts['data-toggle'] = 'dropdown';
$atts['role'] = 'button';
$atts['aria-expanded'] = 'false';
$args->link_after = ' <span class="caret"></span>';
}
/**
* Filter the HTML attributes applied to a menu item's anchor element.
*
* @since 3.6.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $atts {
* The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
*
* @type string $title Title attribute.
* @type string $target Target attribute.
* @type string $rel The rel attribute.
* @type string $href The href attribute.
* }
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$atts = apply_filters('nav_menu_link_attributes', $atts, $item, $args, $depth);
$attributes = '';
foreach ($atts as $attr => $value) {
if (!empty($value)) {
$value = ( 'href' === $attr ) ? esc_url($value) : esc_attr($value);
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
$item_output = $args->before;
$item_output .= '<a' . $attributes . '>';
/** This filter is documented in wp-includes/post-template.php */
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
/**
* Filter a menu item's starting output.
*
* The menu item's starting output only includes `$args->before`, the opening `<a>`,
* the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is
* no filter for modifying the opening and closing `<li>` for a menu item.
*
* @since 3.0.0
*
* @param string $item_output The menu item's starting HTML output.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of {@see wp_nav_menu()} arguments.
*/
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
/**
* Ends the element output, if needed.
*
* @see Walker::end_el()
*
* @since 3.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Page data object. Not used.
* @param int $depth Depth of page. Not Used.
* @param array $args An array of arguments. @see wp_nav_menu()
*/
public function end_el(&$output, $item, $depth = 0, $args = array()) {
/**
* Detect sub menu condition.
*/
if (!("$this->has_children" == "1")) {
$output .= "</li>\n";
}
}
}
// Walker_Nav_Menu
/**
* Description of boostrap
*
* @author yannick
*/
class bootstrap {
/**
* build menu
*/
public static function menu() {
$defaults = array(
'theme_location' => '',
'menu' => '',
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'bs-example-navbar-collapse-1',
'menu_class' => '',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'items_wrap' => '<ul id="%1$s" class="nav navbar-nav">%3$s</ul>',
'depth' => 0,
'walker' => new Custom_walker_Nav_Menu
);
?>
<nav class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><?php bloginfo('name') ?></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="container-fluid">
<?php
wp_nav_menu($defaults);
?>
</div>
</nav>
<?php
}
/**
* build menu
*/
public static function carousel() {
?>
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<?php $category_id = get_theme_mod('illeetzick_set_carousel', '0'); ?>
<?php $url_img = get_theme_mod('illeetzick_url_carousel', '0'); ?>
<?php $query = new WP_Query( 'cat='.$category_id ); $count = 0; ?>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); $active = ($count == 0)?>
<div class="item <?php if($active) {echo "active";} ?> fix-carousel">
<img class="img-responsive img-rounded" src="<?php echo $url_img; ?>" alt="Responsive image" />
<div class="carousel-caption">
<h3><?php the_title(); ?></h3>
<?php the_content(); ?>
</div>
</div>
<?php $count=$count+1; endwhile; endif; wp_reset_postdata();
?>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<?php
}
/**
* build menu
*/
public static function post() {
?>
<br>
<blockquote>
<em>Posted on:</em> <?php the_time('F jS, Y') ?>
<em>by</em> <?php the_author() ?>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
<?php the_tags('Tags: ', ', ', '<br />'); ?>
<p>Categories: <?php the_category( ' ' ); ?></p>
</blockquote>
<!-- Post <?php the_ID() ?> -->
<div class="panel-group" id="panel-the-post">
<div class="panel panel-default">
<div class="panel-heading">
<a class="panel-title" data-toggle="collapse" data-parent="#panel-the-post" href="#panel-element-content">
<?php the_title(); ?>
</a>
</div>
<div id="panel-element-content" class="panel-collapse in" style="height: auto;">
<div class="panel-body">
<!-- Post <?php the_ID() ?> content begin -->
<?php the_content(); ?>
<!-- Post <?php the_ID() ?> content end -->
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<a class="panel-title collapsed" data-toggle="collapse" data-parent="#panel-the-post" href="#panel-element-comments">
Comments
</a>
</div>
<div id="panel-element-comments" class="panel-collapse collapse" style="height: 0px;">
<div class="panel-body">
<?php comments_template(); ?>
</div>
</div>
</div>
</div>
<?php
}
}
|
yroffin/wordpress
|
themes/yrosimple/inc/bootstrap.php
|
PHP
|
apache-2.0
| 12,965 |
package io.github.tramchamploo.bufferslayer;
import io.github.tramchamploo.bufferslayer.Message.MessageKey;
import io.github.tramchamploo.bufferslayer.OverflowStrategy.Strategy;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
@Measurement(iterations = 5, time = 1)
@Warmup(iterations = 10, time = 1)
@Fork(3)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@State(Scope.Group)
public class ConcurrentSizeBoundedQueueBenchmark extends AbstractSizeBoundedQueueBenchmark {
@Override
protected AbstractSizeBoundedQueue newQueue(int maxSize, Strategy strategy, MessageKey key) {
return new ConcurrentSizeBoundedQueue(maxSize, strategy, key);
}
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(".*" + ConcurrentSizeBoundedQueueBenchmark.class.getSimpleName() + ".*")
.build();
new Runner(opt).run();
}
}
|
tramchamploo/buffer-slayer
|
benchmark/src/main/java/io/github/tramchamploo/bufferslayer/ConcurrentSizeBoundedQueueBenchmark.java
|
Java
|
apache-2.0
| 1,452 |
/*
* Copyright 2014 Red Hat, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rhq.simone.system;
import static jnr.ffi.Platform.getNativePlatform;
import jnr.ffi.Platform;
import jnr.posix.POSIX;
import jnr.posix.POSIXFactory;
import org.rhq.simone.system.linux.LinuxSystemService;
import org.rhq.simone.util.log.Log;
import org.rhq.simone.util.log.LogFactory;
/**
* @author Thomas Segismont
*/
public class SystemServiceFactory {
private static final Log LOG = LogFactory.getLog(SystemServiceFactory.class);
private SystemServiceFactory() {
// Factory
}
public static SystemService createSystemService() {
return createSystemService(POSIXFactory.getPOSIX());
}
public static SystemService createSystemService(POSIX posix) {
try {
Platform.OS os = getNativePlatform().getOS();
switch (os) {
case LINUX:
return createLinuxSystemService(posix);
default:
return null;
}
} catch (Throwable t) {
LOG.error("Failed to create SystemService", t);
return null;
}
}
public static SystemService createLinuxSystemService(POSIX posix) {
return new LinuxSystemService(posix);
}
}
|
tsegismont/simone
|
src/main/java/org/rhq/simone/system/SystemServiceFactory.java
|
Java
|
apache-2.0
| 1,715 |
// app/routes/form.js
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
willTransition: function(transition) {
// 如果是使用this.get('key')获取不了页面输入值,因为不是通过action提交表单的
var v = this.controller.get('firstName');
// 任意获取一个作为判断表单输入值
if (v && !confirm("你确定要离开这个页面吗??")) {
transition.abort();
} else {
return true;
}
}
}
});
|
ubuntuvim/my_emberjs_code
|
chapter3_routes/app/routes/form.js
|
JavaScript
|
apache-2.0
| 532 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi;
import com.intellij.model.SymbolResolveResult;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
/**
* Inherit this interface if you want the reference to resolve to more than one element,
* or if you want to provide resolve result(s) for a superset of valid resolve cases.
* e.g. in Java references in static context are resolved to non-static methods in case
* there is no valid candidate. isValidResult() in this case should return false
* for later analysis by highlighting pass.
*
* @see PsiPolyVariantReferenceBase
*/
public interface PsiPolyVariantReference extends PsiReference {
/**
* Returns the results of resolving the reference.
*
* @param incompleteCode if true, the code in the context of which the reference is
* being resolved is considered incomplete, and the method may return additional
* invalid results.
*
* @return the array of results for resolving the reference.
*/
ResolveResult @NotNull [] multiResolve(boolean incompleteCode);
@NotNull
@Override
default Collection<? extends SymbolResolveResult> resolveReference() {
ResolveResult[] results = multiResolve(false);
return ContainerUtil.filter(results, it -> it.getElement() != null);
}
}
|
leafclick/intellij-community
|
platform/core-api/src/com/intellij/psi/PsiPolyVariantReference.java
|
Java
|
apache-2.0
| 1,460 |
/* General Loops - Abstract Case - Free variable */
function f1() { return 1; }
function f2() { return 2; }
function f3() { return 3; }
var b = !Date.now(); // non-deterministic boolean value.
var o1 = {x: f1, y: f2, z: f3};
var o2 = {};
var arr = [];
if (b) {
arr.push("x");
arr.push("y");
} else {
arr.push("z");
arr.push("y");
arr.push("x");
}
// the array ’arr’ is not concrete when we assume the
// path-insensitive analysis.
var i = arr.length;
while (i--) { // the analysis cannot enumerate all the concrete iterations.
var t = arr[i];
var v = o1[t];
o2[t] = (function(v) {
return function() {
return v;
};
}(v));
}
var result = o2.x() !== f2;
TAJS_assert(result);
// TAJS-determinacy: BoolTop
// LSA: BoolTop
// CompAbs: true
|
cs-au-dk/TAJS
|
test-resources/src/micro-different-loop-kinds/AGHeap.js
|
JavaScript
|
apache-2.0
| 813 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ISAAR.MSolve.FEM.Entities
{
public class Cluster
{
private readonly IList<Subdomain> subdomains = new List<Subdomain>();
public IList<Subdomain> Subdomains
{
get { return subdomains; }
}
public int ID { get; set; }
}
}
|
GoatOfRafin/MSolve
|
ISAAR.MSolve.FEM/Entities/Cluster.cs
|
C#
|
apache-2.0
| 385 |
<?php
namespace Atos\MissionRecensementBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Mission
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Atos\MissionRecensementBundle\Entity\MissionRepository")
*/
class Mission
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nom", type="string", length=100)
*/
private $nom;
/**
* @var string
*
* @ORM\Column(name="descriptionProcessus", type="string", length=255, nullable=true)
*/
private $descriptionProcessus;
/**
* @var string
*
* @ORM\Column(name="descriptionTechnique", type="string", length=255, nullable=true)
*/
private $descriptionTechnique;
/**
* @var string
*
* @ORM\Column(name="descriptionFonction", type="string", length=255, nullable=true)
*/
private $descriptionFonction;
/**
* @var \Date
*
* @ORM\Column(name="dateDebut", type="date")
*/
private $dateDebut;
/**
* @var \Date
*
* @ORM\Column(name="dateFin", type="date", nullable=true)
*/
private $dateFin;
/**
* @ORM\ManyToOne(targetEntity="Atos\MissionRecensementBundle\Entity\Employe")
*/
private $employe;
/**
* @ORM\ManyToOne(targetEntity="Atos\MissionRecensementBundle\Entity\Client")
*/
private $client;
/**
* @ORM\ManyToOne(targetEntity="Atos\MissionRecensementBundle\Entity\Metier")
*/
private $metier;
/**
* @ORM\ManyToOne(targetEntity="Atos\MissionRecensementBundle\Entity\TypePrestation")
*/
private $typePrestation;
/**
* @ORM\ManyToOne(targetEntity="Atos\MissionRecensementBundle\Entity\Niveau")
*/
private $niveau;
/**
* @ORM\ManyToOne(targetEntity="Atos\MissionRecensementBundle\Entity\Type")
*/
private $type;
/**
* @ORM\ManyToOne(targetEntity="Atos\MissionRecensementBundle\Entity\Domaine")
*/
private $domaine;
/**
* @ORM\ManyToOne(targetEntity="Atos\MissionRecensementBundle\Entity\Domaine")
*/
private $sousDomaine;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set descriptionProcessus
*
* @param string $descriptionProcessus
* @return Mission
*/
public function setDescriptionProcessus($descriptionProcessus)
{
$this->descriptionProcessus = $descriptionProcessus;
return $this;
}
/**
* Get descriptionProcessus
*
* @return string
*/
public function getDescriptionProcessus()
{
return $this->descriptionProcessus;
}
/**
* Set descriptionTechnique
*
* @param string $descriptionTechnique
* @return Mission
*/
public function setDescriptionTechnique($descriptionTechnique)
{
$this->descriptionTechnique = $descriptionTechnique;
return $this;
}
/**
* Get descriptionTechnique
*
* @return string
*/
public function getDescriptionTechnique()
{
return $this->descriptionTechnique;
}
/**
* Set descriptionFonction
*
* @param string $descriptionFonction
* @return Mission
*/
public function setDescriptionFonction($descriptionFonction)
{
$this->descriptionFonction = $descriptionFonction;
return $this;
}
/**
* Get descriptionFonction
*
* @return string
*/
public function getDescriptionFonction()
{
return $this->descriptionFonction;
}
/**
* Set dateDebut
*
* @param \Date $dateDebut
* @return Mission
*/
public function setDateDebut($dateDebut)
{
$this->dateDebut = $dateDebut;
return $this;
}
/**
* Get dateDebut
*
* @return \Date
*/
public function getDateDebut()
{
return $this->dateDebut;
}
/**
* Set dateFin
*
* @param \Date $dateFin
* @return Mission
*/
public function setDateFin($dateFin)
{
$this->dateFin = $dateFin;
return $this;
}
/**
* Get dateFin
*
* @return \Date
*/
public function getDateFin()
{
return $this->dateFin;
}
/**
* Set employe
*
* @param \Atos\MissionRecensementBundle\Entity\Employe $employe
* @return Mission
*/
public function setEmploye(\Atos\MissionRecensementBundle\Entity\Employe $employe = null)
{
$this->employe = $employe;
return $this;
}
/**
* Get employe
*
* @return \Atos\MissionRecensementBundle\Entity\Employe
*/
public function getEmploye()
{
return $this->employe;
}
/**
* Set client
*
* @param \Atos\MissionRecensementBundle\Entity\Client $client
* @return Mission
*/
public function setClient(\Atos\MissionRecensementBundle\Entity\Client $client = null)
{
$this->client = $client;
return $this;
}
/**
* Get client
*
* @return \Atos\MissionRecensementBundle\Entity\Client
*/
public function getClient()
{
return $this->client;
}
/**
* Set metier
*
* @param \Atos\MissionRecensementBundle\Entity\Metier $metier
* @return Mission
*/
public function setMetier(\Atos\MissionRecensementBundle\Entity\Metier $metier = null)
{
$this->metier = $metier;
return $this;
}
/**
* Get metier
*
* @return \Atos\MissionRecensementBundle\Entity\Metier
*/
public function getMetier()
{
return $this->metier;
}
/**
* Set typePrestation
*
* @param \Atos\MissionRecensementBundle\Entity\TypePrestation $typePrestation
* @return Mission
*/
public function setTypePrestation(\Atos\MissionRecensementBundle\Entity\TypePrestation $typePrestation = null)
{
$this->typePrestation = $typePrestation;
return $this;
}
/**
* Get typePrestation
*
* @return \Atos\MissionRecensementBundle\Entity\TypePrestation
*/
public function getTypePrestation()
{
return $this->typePrestation;
}
/**
* Set niveau
*
* @param \Atos\MissionRecensementBundle\Entity\Niveau $niveau
* @return Mission
*/
public function setNiveau(\Atos\MissionRecensementBundle\Entity\Niveau $niveau = null)
{
$this->niveau = $niveau;
return $this;
}
/**
* Get niveau
*
* @return \Atos\MissionRecensementBundle\Entity\Niveau
*/
public function getNiveau()
{
return $this->niveau;
}
/**
* Set type
*
* @param \Atos\MissionRecensementBundle\Entity\Type $type
* @return Mission
*/
public function setType(\Atos\MissionRecensementBundle\Entity\Type $type = null)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* @return \Atos\MissionRecensementBundle\Entity\Type
*/
public function getType()
{
return $this->type;
}
/**
* Set nom
*
* @param string $nom
* @return Mission
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* @return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Get date interval.
*
* @return DateInterval
*/
public function getDateInterval()
{
$start = $this->getDateDebut();
$end = $this->getDateFin();
if($end)
{
return $start->diff($end);
}
return null;
}
/**
* Get duree annees.
*
* @return integer
*/
public function getDureeAnnees()
{
$interval = $this->getDateInterval();
if($interval)
{
return $interval->y;
}
}
/**
* Get duree mois.
*
* @return integer
*/
public function getDureeMois()
{
$interval = $this->getDateInterval();
if($interval)
{
return $interval->m;
}
}
/**
* Set domaine
*
* @param \Atos\MissionRecensementBundle\Entity\Domaine $domaine
* @return Mission
*/
public function setDomaine(\Atos\MissionRecensementBundle\Entity\Domaine $domaine = null)
{
$this->domaine = $domaine;
return $this;
}
/**
* Get domaine
*
* @return \Atos\MissionRecensementBundle\Entity\Domaine
*/
public function getDomaine()
{
return $this->domaine;
}
/**
* Set sousDomaine
*
* @param \Atos\MissionRecensementBundle\Entity\Domaine $sousDomaine
* @return Mission
*/
public function setSousDomaine(\Atos\MissionRecensementBundle\Entity\Domaine $sousDomaine = null)
{
$this->sousDomaine = $sousDomaine;
return $this;
}
/**
* Get sousDomaine
*
* @return \Atos\MissionRecensementBundle\Entity\Domaine
*/
public function getSousDomaine()
{
return $this->sousDomaine;
}
}
|
kfrapin/mission-recensement
|
src/Atos/MissionRecensementBundle/Entity/Mission.php
|
PHP
|
apache-2.0
| 9,462 |
function f() { return 42}
TAJS_assert(f.call.call.call(f) === 42)
TAJS_assert(f.apply.apply.apply(f) === 42)
TAJS_assert(Function.prototype.apply.apply(f) == 42)
TAJS_dumpValue(f.apply.apply.apply(f))
function g(x) { return x + 1}
TAJS_assert(Function.prototype.call(g,45) === undefined)
TAJS_assert(isNaN(g.call.call(g,45)))
TAJS_dumpValue(g.call.call(g,45))
TAJS_assert(Function.prototype.call.call(g, null, 87), 'isMaybeNumUInt||isMaybeNaN');
TAJS_dumpValue(Function.prototype.call.call(g,null,87));
|
cs-au-dk/TAJS
|
test-resources/src/micro/test109.js
|
JavaScript
|
apache-2.0
| 514 |
#-*- coding: utf-8 -*-
'''
Created on Jul 4, 2013
@author: jin
'''
from django.contrib import admin
from apps.agent.models import Client, RecommendRecord
class ClientAdmin(admin.ModelAdmin):
search_fields = ('username','user_username','IDCard')
class RecommendRecordAdmin(admin.ModelAdmin):
search_fields = ('user_username','client_username')
admin.site.register(Client,ClientAdmin)
admin.site.register(RecommendRecord,RecommendRecordAdmin)
|
SnailJin/house
|
apps/agent/admin.py
|
Python
|
apache-2.0
| 461 |
package com.ibuildapp.romanblack.CustomFormPlugin.xmlparser;
/**
* Entity class that form submit button.
*/
public class FormButton {
private String label = "";
/**
* Returns the button label.
* @return the label
*/
public String getLabel() {
return label;
}
/**
* Sets the button label.
* @param label the label to set
*/
public void setLabel(String label) {
this.label = label;
}
}
|
iBuildApp/android_module_CustomForm
|
src/main/java/com/ibuildapp/romanblack/CustomFormPlugin/xmlparser/FormButton.java
|
Java
|
apache-2.0
| 464 |
/*
* Copyright (c) Created by Cody.yi on 2016/8/26.
*/
package com.cody.app.framework.fragment;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.cody.handler.framework.presenter.Presenter;
import com.cody.handler.framework.viewmodel.HeaderViewModel;
import com.cody.handler.framework.viewmodel.IWithHeaderViewModel;
/**
* A simple {@link Fragment} subclass.
*/
public abstract class WithHeaderFragment<P extends Presenter<VM>, VM extends IWithHeaderViewModel, B extends
ViewDataBinding> extends BaseBindingFragment<P, VM, B> {
/**
* 创建标题
* 返回空或者默认的HeaderViewModel不会显示头部,必须设置头部的visible
*
* @see HeaderViewModel#setVisible
*/
protected abstract void initHeader(HeaderViewModel header);
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
initHeader(getViewModel().getHeaderViewModel());
return view;
}
}
|
codyer/CleanFramework
|
app/src/main/java/com/cody/app/framework/fragment/WithHeaderFragment.java
|
Java
|
apache-2.0
| 1,317 |
<?php
/*
mod_siokara : Pixmicat! siokara management subset (Alpha)
by: scribe
*/
class mod_siokara extends ModuleHelper {
private $mypage;
private $LANGUAGE=array(
'zh_TW' => array(
'siokara_admin_fsage' => '強制sage',
'siokara_admin_ufsage' => '解除強制sage',
'siokara_admin_htmb' => '替換縮圖',
'siokara_admin_uhtmb' => '解除替換縮圖',
'siokara_admin_agif' => '替換縮圖為靜態縮圖',
'siokara_admin_uagif' => '解除替換靜態縮圖',
'siokara_extra_opt' => '附加選項',
'siokara_anigif' => '動態GIF',
'siokara_warn_sage' => '此討論串已被強制sage。',
'siokara_warn_hidethumb' => '縮圖已被替換。'
),
'ja_JP' => array(
'siokara_admin_fsage' => '強制sage',
'siokara_admin_ufsage' => '強制sage解除',
'siokara_admin_htmb' => 'サムネイル差替',
'siokara_admin_uhtmb' => 'サムネイル差替解除',
'siokara_admin_agif' => 'GIFをサムネイル化する',
'siokara_admin_uagif' => 'GIFサムネイル化解除',
'siokara_extra_opt' => '余分なオプション',
'siokara_anigif' => 'GIFアニメ',
'siokara_warn_sage' => 'このスレは管理者によりsage指定されています。理由はお察しください。',
'siokara_warn_hidethumb' => 'この記事の画像は管理者によりサムネイルが差し替えられています。理由はお察しください。<br/>サムネイルをクリックすると元の画像を表示します。'
),
'en_US' => array(
'siokara_admin_fsage' => 'Force sage',
'siokara_admin_ufsage' => 'unForce sage',
'siokara_admin_htmb' => 'Replace thumbnail with nothumb image',
'siokara_admin_uhtmb' => 'Use orginal thumbnail',
'siokara_admin_agif' => 'Use still image of GIF image',
'siokara_admin_uagif' => 'Use Animated GIF',
'siokara_extra_opt' => 'Extra Options',
'siokara_anigif' => 'Animated GIF',
'siokara_warn_sage' => 'This thread was forced sage by administrator.',
'siokara_warn_hidethumb' => 'The thumbnail was replaced by administrator.'
)
);
public function __construct($PMS) {
parent::__construct($PMS);
$this->mypage = $this->getModulePageURL();
$this->attachLanguage( $this->LANGUAGE); // 載入語言檔
}
/* Get the name of module */
public function getModuleName(){
return 'mod_siokara : しおから式管理擴充套件';
}
/* Get the module version infomation */
public function getModuleVersionInfo(){
return 'v140531';
}
public function autoHookAdminList(&$modFunc, $post, $isres){
$FileIO = PMCLibrary::getFileIOInstance();
extract($post);
$fh=new FlagHelper($status);
if(!$isres) $modFunc .= '[<a href="'.$this->mypage.'&no='.$no.'&action=sage"'.($fh->value('asage')?' title="'.$this->_T('siokara_admin_ufsage').'">s':' title="'.$this->_T('siokara_admin_fsage').'">S').'</a>]';
if($ext && $FileIO->imageExists($tim.$ext)) {
$modFunc .= '[<a href="'.$this->mypage.'&no='.$no.'&action=thumb"'.($fh->value('htmb')?' title="'.$this->_T('siokara_admin_uhtmb').'">t':' title="'.$this->_T('siokara_admin_htmb').'">T').'</a>]';
if($ext == '.gif') $modFunc .= '[<a href="'.$this->mypage.'&no='.$no.'&action=agif"'.($fh->value('agif')?' title="'.$this->_T('siokara_admin_agif').'">g':' title="'.$this->_T('siokara_admin_uagif').'">G').'</a>]';
}
}
public function autoHookPostForm(&$form){
$form .= '<tr><td class="Form_bg"><b>'.$this->_T('siokara_extra_opt').'</b></td><td>[<input type="checkbox" name="anigif" id="anigif" value="on" /><label for="anigif">'.$this->_T('siokara_anigif').'</label>]</td></tr>';
}
public function autoHookThreadPost(&$arrLabels, $post, $isReply){
$PIO = PMCLibrary::getPIOInstance();
$FileIO = PMCLibrary::getFileIOInstance();
$fh = new FlagHelper($post['status']);
if($fh->value('asage')) { // 強制sage
if($arrLabels['{$COM}']) $arrLabels['{$WARN_ENDREPLY}'].='<br/><span class="warn_txt"><small>'.$this->_T('siokara_warn_sage').'<br/></small></span>';
else $arrLabels['{$WARN_ENDREPLY}'] = '<span class="warn_txt"><small>'.$this->_T('siokara_warn_sage').'<br/></small></span>';
}
if($FileIO->imageExists($post['tim'].$post['ext'])) {
if($fh->value('agif')) { // 動態GIF
$imgURL = $FileIO->getImageURL($post['tim'].$post['ext']);
$arrLabels['{$IMG_SRC}']=preg_replace('/<img src=".*"/U','<img src="'.$imgURL.'"',$arrLabels['{$IMG_SRC}']);
$arrLabels['{$IMG_BAR}'].='<small>['.$this->_T('siokara_anigif').']</small>';
}
if($fh->value('htmb')) { // 替換縮圖
$arrLabels['{$IMG_SRC}']=preg_replace('/<img src=".*" style="width: \d+px; height: \d+px;"/U','<img src="nothumb.gif"',$arrLabels['{$IMG_SRC}']);
$arrLabels['{$COM}'].='<br/><br/><span class="warn_txt"><small>'.$this->_T('siokara_warn_hidethumb').'<br/></small></span>';
}
}
}
public function autoHookThreadReply(&$arrLabels, $post, $isReply){
$this->autoHookThreadPost($arrLabels, $post, $isReply);
}
public function autoHookRegistBeforeCommit(&$name, &$email, &$sub, &$com, &$category, &$age, $dest, $isReply, $imgWH, &$status){
$PIO = PMCLibrary::getPIOInstance();
$fh = new FlagHelper($status);
$size = @getimagesize($dest);
if(isset($_POST['anigif']) && ($size[2] == 1)) { // 動態GIF
$fh->toggle('agif');
$status = $fh->toString();
}
if($isReply) {
$rpost = $PIO->fetchPosts($isReply); // 強制sage
$rfh = new FlagHelper($rpost[0]['status']);
if($rfh->value('asage')) $age = false;
}
}
/*
function _loadLanguage() {
global $language;
if(PIXMICAT_LANGUAGE != 'zh_TW' && PIXMICAT_LANGUAGE != 'ja_JP' && PIXMICAT_LANGUAGE != 'en_US') $lang = 'en_US';
else $lang = PIXMICAT_LANGUAGE;
// builtin language strings
if($lang == 'zh_TW') {
$language['siokara_admin_fsage'] = '強制sage';
$language['siokara_admin_ufsage'] = '解除強制sage';
$language['siokara_admin_htmb'] = '替換縮圖';
$language['siokara_admin_uhtmb'] = '解除替換縮圖';
$language['siokara_admin_agif'] = '替換縮圖為靜態縮圖';
$language['siokara_admin_uagif'] = '解除替換靜態縮圖';
$language['siokara_extra_opt'] = '附加選項';
$language['siokara_anigif'] = '動態GIF';
$language['siokara_warn_sage'] = '此討論串已被強制sage。';
$language['siokara_warn_hidethumb'] = '縮圖已被替換。';
} else if($lang == 'ja_JP'){
$language['siokara_admin_fsage'] = '強制sage';
$language['siokara_admin_ufsage'] = '強制sage解除';
$language['siokara_admin_htmb'] = 'サムネイル差替';
$language['siokara_admin_uhtmb'] = 'サムネイル差替解除';
$language['siokara_admin_agif'] = 'GIFをサムネイル化する';
$language['siokara_admin_uagif'] = 'GIFサムネイル化解除';
$language['siokara_extra_opt'] = '余分なオプション';
$language['siokara_anigif'] = 'GIFアニメ';
$language['siokara_warn_sage'] = 'このスレは管理者によりsage指定されています。理由はお察しください。';
$language['siokara_warn_hidethumb'] = 'この記事の画像は管理者によりサムネイルが差し替えられています。理由はお察しください。<br/>サムネイルをクリックすると元の画像を表示します。';
} else if($lang == 'en_US'){
$language['siokara_admin_fsage'] = 'Force sage';
$language['siokara_admin_ufsage'] = 'unForce sage';
$language['siokara_admin_htmb'] = 'Replace thumbnail with nothumb image';
$language['siokara_admin_uhtmb'] = 'Use orginal thumbnail';
$language['siokara_admin_agif'] = 'Use still image of GIF image';
$language['siokara_admin_uagif'] = 'Use Animated GIF';
$language['siokara_extra_opt'] = 'Extra Options';
$language['siokara_anigif'] = 'Animated GIF';
$language['siokara_warn_sage'] = 'This thread was forced sage by administrator.';
$language['siokara_warn_hidethumb'] = 'The thumbnail was replaced by administrator.';
}
// external language file
if(file_exists($langfile=str_replace('.php','.lang.php',__FILE__))) include_once($langfile);
}
*/
public function ModulePage(){
$PIO = PMCLibrary::getPIOInstance();
$FileIO = PMCLibrary::getFileIOInstance();
if(!adminAuthenticate('check')) die('403 Access denied');
$act=isset($_GET['action'])?$_GET['action']:'';
switch($act) {
case 'sage'; // 強制sage
if($PIO->isThread($_GET['no'])) {
$post = $PIO->fetchPosts($_GET['no']);
if(!count($post)) die('[Error] Post does not exist.');
$flgh = $PIO->getPostStatus($post[0]['status']);
$flgh->toggle('asage');
$PIO->setPostStatus($post[0]['no'], $flgh->toString());
$PIO->dbCommit();
//die('Done. Please go back.');
die('Done. Please go <script type="text/javascript"> document.write("<"+"a href=\""+document.referrer+"\">back</a>."); </script><noscript>back.</noscript> ');
} else die('[Error] Thread does not exist.');
break;
case 'thumb'; // 替換縮圖
$post = $PIO->fetchPosts($_GET['no']);
if(!count($post)) die('[Error] Post does not exist.');
if($post[0]['ext']) {
if(!$FileIO->imageExists($post[0]['tim'].$post[0]['ext'])) die('[Error] attachment does not exist.');
$flgh = $PIO->getPostStatus($post[0]['status']);
$flgh->toggle('htmb');
$PIO->setPostStatus($post[0]['no'], $flgh->toString());
$PIO->dbCommit();
//die('Done. Please go back.');
die('Done. Please go <script type="text/javascript"> document.write("<"+"a href=\""+document.referrer+"\">back</a>."); </script><noscript>back.</noscript> ');
} else die('[Error] Post does not have attechment.');
break;
case 'agif'; // 動態GIF
$post = $PIO->fetchPosts($_GET['no']);
if(!count($post)) die('[Error] Post does not exist.');
if($post[0]['ext'] && $post[0]['ext'] == '.gif') {
if(!$FileIO->imageExists($post[0]['tim'].$post[0]['ext'])) die('[Error] attachment does not exist.');
$flgh = $PIO->getPostStatus($post[0]['status']);
$flgh->toggle('agif');
$PIO->setPostStatus($post[0]['no'], $flgh->toString());
$PIO->dbCommit();
die('Done. Please go <script type="text/javascript"> document.write("<"+"a href=\""+document.referrer+"\">back</a>."); </script><noscript>back.</noscript> ');
} else die('[Error] Post does not have attechment.');
break;
}
}
}
|
miyorineko/pixmicat-materialize
|
module/mod_siokara.php
|
PHP
|
artistic-2.0
| 10,573 |
<?php
class view_conf extends admin_common
{
public $message = false;
private function set_tinymce_vars($section=array())
{
$tmp = 'var all_tinymce=" ';
//$tmpA = array('tinymce');
$tmp .='";';
$tmp .= 'var content_css_set="'.make_path("css","admin","css",false,true).'";';
global $conf;
$tmp .= 'var main_base_path="'.$conf->main_base_path.'"';
$this->set_js_code($tmp);
}
private function js_for_page($conf_data)
{
$js = "";
global $conf;
$this->set_tinymce_vars();
$js .= <<<EOF
jQuery(document).ready(function(){
EOF;
foreach($conf_data as $key=>$val)
{
if ($val['type'] == 'tinymce')
{
$js.= 'jQuery("#'. $val['key'] .'").editInPlace({
url: "conf",
show_buttons: true,
value_required: true,
field_type: "textarea",
params: "action=update",
delegate: delegateeip,
use_html: true
}); '."\n";
} else {
$js .= 'jQuery("#'.$val['key'].'").editInPlace({
url: "conf",
show_buttons: true,
value_required: true,
field_type: "'.$val['type'].'",
params: "action=update",
delegate: delegatebutton,
use_html: true
});'."\n";
}
$js.= 'jQuery("#desc_'. $val['key'] .'").editInPlace({
url: "conf",
show_buttons: true,
value_required: true,
field_type: "textarea",
params: "action=update_description",
delegate: delegateeip
}); '."\n";
}
$js.='});';
return $js;
}
public function display_result($result)
{
echo $result;
}
public function run($conf_data)
{
$this->set_title(_("Configuration"));
$title=$this->req;
$this->set_css_code('table { border-collapse: collapse;}');
$this->set_css(array('admin',"jquery.growl",$this->req,'jquery-ui.min'));
$this->set_js(array('tinymce_var',"jquery.growl",'admin','jquery','jquery-ui.min','jquery-migrate-1.2.1','tinymce/tinymce.min','jquery.editinplace','tinymce/jquery.tinymce.min','validation/jquery.validate.min','validation/additional-methods.min',$this->req,));
$this->set_js_code($this->js_for_page($conf_data));
$this->set_extra_render('conf_data', $conf_data);
global $lang,$conf;
$tmpLang = substr($lang,0,2);
if ($tmpLang != "en")
{
if (is_file(make_path('js', "validation/localization/messages_".$lang, "js")))
{
$this->set_js('validation/localization/messages_'.$lang.'.js');
} elseif (is_file(make_path('js', "validation/localization/messages_".$tmpLang, "js")))
{
$this->set_js('validation/localization/messages_'.$tmpLang.'.js');
} else {
$tmpLang = substr($conf->default_lang,0,2);
if (is_file(make_path('js', "validation/localization/messages_".$conf->default_lang, "js")))
{
$this->set_js('validation/localization/messages_'.$conf->default_lang.'.js');
} else {
$this->set_js('validation/localization/messages_'.$tmpLang.'.js');
}
}
}
$this->set_js(array (
'tinymce/themes/modern/theme.min',
'tinymce/plugins/pagebreak/plugin.min',
'tinymce/plugins/layer/plugin.min',
'tinymce/plugins/table/plugin.min',
'tinymce/plugins/save/plugin.min',
'tinymce/plugins/emoticons/plugin.min',
'tinymce/plugins/insertdatetime/plugin.min',
'tinymce/plugins/preview/plugin.min',
'tinymce/plugins/media/plugin.min',
'tinymce/plugins/searchreplace/plugin.min',
'tinymce/plugins/print/plugin.min',
'tinymce/plugins/contextmenu/plugin.min',
'tinymce/plugins/paste/plugin.min',
'tinymce/plugins/directionality/plugin.min',
'tinymce/plugins/fullscreen/plugin.min',
'tinymce/plugins/hr/plugin.min',
'tinymce/plugins/wordcount/plugin.min',
'tinymce/plugins/noneditable/plugin.min',
'tinymce/plugins/visualchars/plugin.min',
'tinymce/plugins/nonbreaking/plugin.min',
'tinymce/plugins/template/plugin.min',
'tinymce/plugins/image/plugin.min',
'tinymce/plugins/code/plugin.min'));
global $lang,$conf;
$tmpLang = substr($lang,0,2);
if (is_file(make_path('js', "tinymce/langs/".$lang, "js")))
{
$this->set_js('tinymce/langs/'.$lang.'.js');
} elseif (is_file(make_path('js', "tinymce/langs/".$tmpLang, "js")))
{
$this->set_js('tinymce/langs/'.$tmpLang.'.js');
} else {
$tmpLang = substr($conf->default_lang,0,2);
if (is_file(make_path('js', "tinymce/langs/".$conf->default_lang, "js")))
{
$this->set_js('tinymce/langs/'.$conf->default_lang.'.js');
} else {
$this->set_js('tinymce/langs/'.$tmpLang.'.js');
}
}
if ($this->message)
{
$this->set_js_code('
jQuery(document).ready(function(){
jQuery.growl({
title: "'._("Résultat").'",
message: "'.$this->message.'",
location: "tr",
duration: 3200
});
});
');
}
echo $this->gen_page();
}
}
|
eos-13/YaCMS
|
main/admin/view/conf.php
|
PHP
|
artistic-2.0
| 6,240 |
#!/usr/bin/env python
"""
Created by _UserName_
11/28/2013
"""
import Connect, DB
import uuid
def Register():
# Generate A Unique Idenfifier
ident = uuid.uuid4().hex
# Allow For Database Manipulation
database = DB.DB()
# Create Database
database.create()
# Add Self To Database
externalIP = "127.0.0.1"
database.personalInfo(ident, externalIP)
|
Us3rNam/F2F-Network
|
Register.py
|
Python
|
artistic-2.0
| 398 |