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 |
|---|---|---|---|---|---|
resource_name :code_deploy_agent
default_action %i[install enable start]
provides :code_deploy_agent_linux
provides :code_deploy_agent, platform_family: 'debian'
property :auto_update, [true, false], default: false
action_class do
include CodeDeploy::Helper
end
action :install do
include_recipe 'apt'
package 'ruby' do
package_name 'ruby2.0' if ubuntu_less_than_15?
end
download_installer_to_cache('deb')
dpkg_package installer_cache_path('deb')
service 'codedeploy-agent' do
action :nothing
retries 2
end
file '/etc/cron.d/codedeploy-agent-update' do
action :delete
not_if { new_resource.auto_update }
end
end
action :uninstall do
execute 'systemctl daemon-reload' do
only_if { systemd? }
action :nothing
end
package 'codedeploy-agent' do
action :purge
notifies :run, 'execute[systemctl daemon-reload]'
end
end
%i[
disable
enable
restart
start
stop
].each do |a|
action a do
service 'codedeploy-agent' do
action a
retries 2
end
end
end
| meringu/code_deploy | resources/agent_debian.rb | Ruby | apache-2.0 | 1,052 |
package any.ejbtest;
import com.dms.Discriminated;
import java.util.List;
/**
* MoviesImplEjb, 02.03.2015
*
* Copyright (c) 2014 Marius Dinu. All rights reserved.
*
* @author mdinu
* @version $Id$
*/
//@Named
@Discriminated(isResultAggregated = true)
public class MoviesImplWrapper implements Movies {
private Movies movies;
public void setMovies(Movies movies) {
this.movies = movies;
}
public Movies getMovies() {
return movies;
}
@Override
public void addMovie(Movie movie) throws Exception {
movies.addMovie(movie);
}
@Override
public void deleteMovie(Movie movie) throws Exception {
movies.deleteMovie(movie);
}
@Override
public List<Movie> getAllMovies() throws Exception {
return movies.getAllMovies();
}
}
| dmarius99/ImplementationDiscriminator | src/test/java/any/ejbtest/MoviesImplWrapper.java | Java | apache-2.0 | 826 |
const crypto = require('crypto')
module.exports = function (doc) {
doc._source.bar = crypto
.createHash('md5')
.update(String(doc._source.foo))
.digest('hex')
}
| taskrabbit/elasticsearch-dump | test/test-resources/transform.js | JavaScript | apache-2.0 | 176 |
/*
* Copyright © 2009 HotPads (admin@hotpads.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.datarouter.client.mysql.ddl.domain;
import java.util.List;
import java.util.Objects;
public class SqlIndex{
private final String name;
private final List<String> columnNames;
public SqlIndex(String name, List<String> columns){
this.name = name;
this.columnNames = columns;
}
public String getName(){
return name;
}
public List<String> getColumnNames(){
return columnNames;
}
@Override
public int hashCode(){
return Objects.hash(name, columnNames);
}
@Override
public boolean equals(Object obj){
if(this == obj){
return true;
}
if(!(obj instanceof SqlIndex)){
return false;
}
SqlIndex other = (SqlIndex)obj;
return Objects.equals(name, other.name)
&& Objects.equals(columnNames, other.columnNames);
}
public static SqlIndex createPrimaryKey(List<String> columns){
return new SqlIndex("PRIMARY", columns);
}
}
| hotpads/datarouter | datarouter-mysql/src/main/java/io/datarouter/client/mysql/ddl/domain/SqlIndex.java | Java | apache-2.0 | 1,493 |
/**
*/
package CIM15.IEC61970.Wires;
import CIM15.IEC61970.Core.IdentifiedObject;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.util.BasicInternalEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Per Length Phase Impedance</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getLineSegments <em>Line Segments</em>}</li>
* <li>{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getConductorCount <em>Conductor Count</em>}</li>
* <li>{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getPhaseImpedanceData <em>Phase Impedance Data</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class PerLengthPhaseImpedance extends IdentifiedObject {
/**
* The cached value of the '{@link #getLineSegments() <em>Line Segments</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLineSegments()
* @generated
* @ordered
*/
protected EList<ACLineSegment> lineSegments;
/**
* The default value of the '{@link #getConductorCount() <em>Conductor Count</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getConductorCount()
* @generated
* @ordered
*/
protected static final int CONDUCTOR_COUNT_EDEFAULT = 0;
/**
* The cached value of the '{@link #getConductorCount() <em>Conductor Count</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getConductorCount()
* @generated
* @ordered
*/
protected int conductorCount = CONDUCTOR_COUNT_EDEFAULT;
/**
* This is true if the Conductor Count attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean conductorCountESet;
/**
* The cached value of the '{@link #getPhaseImpedanceData() <em>Phase Impedance Data</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPhaseImpedanceData()
* @generated
* @ordered
*/
protected EList<PhaseImpedanceData> phaseImpedanceData;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PerLengthPhaseImpedance() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return WiresPackage.Literals.PER_LENGTH_PHASE_IMPEDANCE;
}
/**
* Returns the value of the '<em><b>Line Segments</b></em>' reference list.
* The list contents are of type {@link CIM15.IEC61970.Wires.ACLineSegment}.
* It is bidirectional and its opposite is '{@link CIM15.IEC61970.Wires.ACLineSegment#getPhaseImpedance <em>Phase Impedance</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Line Segments</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Line Segments</em>' reference list.
* @see CIM15.IEC61970.Wires.ACLineSegment#getPhaseImpedance
* @generated
*/
public EList<ACLineSegment> getLineSegments() {
if (lineSegments == null) {
lineSegments = new BasicInternalEList<ACLineSegment>(ACLineSegment.class);
}
return lineSegments;
}
/**
* Returns the value of the '<em><b>Conductor Count</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Conductor Count</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Conductor Count</em>' attribute.
* @see #isSetConductorCount()
* @see #unsetConductorCount()
* @see #setConductorCount(int)
* @generated
*/
public int getConductorCount() {
return conductorCount;
}
/**
* Sets the value of the '{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getConductorCount <em>Conductor Count</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Conductor Count</em>' attribute.
* @see #isSetConductorCount()
* @see #unsetConductorCount()
* @see #getConductorCount()
* @generated
*/
public void setConductorCount(int newConductorCount) {
conductorCount = newConductorCount;
conductorCountESet = true;
}
/**
* Unsets the value of the '{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getConductorCount <em>Conductor Count</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetConductorCount()
* @see #getConductorCount()
* @see #setConductorCount(int)
* @generated
*/
public void unsetConductorCount() {
conductorCount = CONDUCTOR_COUNT_EDEFAULT;
conductorCountESet = false;
}
/**
* Returns whether the value of the '{@link CIM15.IEC61970.Wires.PerLengthPhaseImpedance#getConductorCount <em>Conductor Count</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Conductor Count</em>' attribute is set.
* @see #unsetConductorCount()
* @see #getConductorCount()
* @see #setConductorCount(int)
* @generated
*/
public boolean isSetConductorCount() {
return conductorCountESet;
}
/**
* Returns the value of the '<em><b>Phase Impedance Data</b></em>' reference list.
* The list contents are of type {@link CIM15.IEC61970.Wires.PhaseImpedanceData}.
* It is bidirectional and its opposite is '{@link CIM15.IEC61970.Wires.PhaseImpedanceData#getPhaseImpedance <em>Phase Impedance</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Phase Impedance Data</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Phase Impedance Data</em>' reference list.
* @see CIM15.IEC61970.Wires.PhaseImpedanceData#getPhaseImpedance
* @generated
*/
public EList<PhaseImpedanceData> getPhaseImpedanceData() {
if (phaseImpedanceData == null) {
phaseImpedanceData = new BasicInternalEList<PhaseImpedanceData>(PhaseImpedanceData.class);
}
return phaseImpedanceData;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getLineSegments()).basicAdd(otherEnd, msgs);
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getPhaseImpedanceData()).basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS:
return ((InternalEList<?>)getLineSegments()).basicRemove(otherEnd, msgs);
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA:
return ((InternalEList<?>)getPhaseImpedanceData()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS:
return getLineSegments();
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__CONDUCTOR_COUNT:
return getConductorCount();
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA:
return getPhaseImpedanceData();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS:
getLineSegments().clear();
getLineSegments().addAll((Collection<? extends ACLineSegment>)newValue);
return;
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__CONDUCTOR_COUNT:
setConductorCount((Integer)newValue);
return;
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA:
getPhaseImpedanceData().clear();
getPhaseImpedanceData().addAll((Collection<? extends PhaseImpedanceData>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS:
getLineSegments().clear();
return;
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__CONDUCTOR_COUNT:
unsetConductorCount();
return;
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA:
getPhaseImpedanceData().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__LINE_SEGMENTS:
return lineSegments != null && !lineSegments.isEmpty();
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__CONDUCTOR_COUNT:
return isSetConductorCount();
case WiresPackage.PER_LENGTH_PHASE_IMPEDANCE__PHASE_IMPEDANCE_DATA:
return phaseImpedanceData != null && !phaseImpedanceData.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (conductorCount: ");
if (conductorCountESet) result.append(conductorCount); else result.append("<unset>");
result.append(')');
return result.toString();
}
} // PerLengthPhaseImpedance
| SES-fortiss/SmartGridCoSimulation | core/cim15/src/CIM15/IEC61970/Wires/PerLengthPhaseImpedance.java | Java | apache-2.0 | 10,430 |
package uk.co.ourfriendirony.medianotifier.clients.tmdb.movie.get;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonFormat;
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 java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"adult",
"backdrop_path",
"belongs_to_collection",
"budget",
"movieGetGenres",
"homepage",
"id",
"imdb_id",
"original_language",
"original_title",
"overview",
"popularity",
"poster_path",
"production_companies",
"production_countries",
"release_date",
"revenue",
"runtime",
"spoken_languages",
"status",
"tagline",
"title",
"video",
"vote_average",
"vote_count",
"external_ids"
})
public class MovieGet {
@JsonProperty("adult")
private Boolean adult;
@JsonProperty("backdrop_path")
private String backdropPath;
@JsonProperty("belongs_to_collection")
private MovieGetBelongsToCollection belongsToCollection;
@JsonProperty("budget")
private Integer budget;
@JsonProperty("movieGetGenres")
private List<MovieGetGenre> movieGetGenres = null;
@JsonProperty("homepage")
private String homepage;
@JsonProperty("id")
private Integer id;
@JsonProperty("imdb_id")
private String imdbId;
@JsonProperty("original_language")
private String originalLanguage;
@JsonProperty("original_title")
private String originalTitle;
@JsonProperty("overview")
private String overview;
@JsonProperty("popularity")
private Double popularity;
@JsonProperty("poster_path")
private String posterPath;
@JsonProperty("production_companies")
private List<MovieGetProductionCompany> productionCompanies = null;
@JsonProperty("production_countries")
private List<MovieGetProductionCountry> productionCountries = null;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
@JsonProperty("release_date")
private Date releaseDate;
@JsonProperty("revenue")
private Integer revenue;
@JsonProperty("runtime")
private Integer runtime;
@JsonProperty("spoken_languages")
private List<MovieGetSpokenLanguage> movieGetSpokenLanguages = null;
@JsonProperty("status")
private String status;
@JsonProperty("tagline")
private String tagline;
@JsonProperty("title")
private String title;
@JsonProperty("video")
private Boolean video;
@JsonProperty("vote_average")
private Double voteAverage;
@JsonProperty("vote_count")
private Integer voteCount;
@JsonProperty("external_ids")
private MovieGetExternalIds movieGetExternalIds;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("adult")
public Boolean getAdult() {
return adult;
}
@JsonProperty("adult")
public void setAdult(Boolean adult) {
this.adult = adult;
}
@JsonProperty("backdrop_path")
public String getBackdropPath() {
return backdropPath;
}
@JsonProperty("backdrop_path")
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
@JsonProperty("belongs_to_collection")
public MovieGetBelongsToCollection getBelongsToCollection() {
return belongsToCollection;
}
@JsonProperty("belongs_to_collection")
public void setBelongsToCollection(MovieGetBelongsToCollection belongsToCollection) {
this.belongsToCollection = belongsToCollection;
}
@JsonProperty("budget")
public Integer getBudget() {
return budget;
}
@JsonProperty("budget")
public void setBudget(Integer budget) {
this.budget = budget;
}
@JsonProperty("movieGetGenres")
public List<MovieGetGenre> getMovieGetGenres() {
return movieGetGenres;
}
@JsonProperty("movieGetGenres")
public void setMovieGetGenres(List<MovieGetGenre> movieGetGenres) {
this.movieGetGenres = movieGetGenres;
}
@JsonProperty("homepage")
public String getHomepage() {
return homepage;
}
@JsonProperty("homepage")
public void setHomepage(String homepage) {
this.homepage = homepage;
}
@JsonProperty("id")
public Integer getId() {
return id;
}
@JsonProperty("id")
public void setId(Integer id) {
this.id = id;
}
@JsonProperty("imdb_id")
public String getImdbId() {
return imdbId;
}
@JsonProperty("imdb_id")
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
@JsonProperty("original_language")
public String getOriginalLanguage() {
return originalLanguage;
}
@JsonProperty("original_language")
public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}
@JsonProperty("original_title")
public String getOriginalTitle() {
return originalTitle;
}
@JsonProperty("original_title")
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
@JsonProperty("overview")
public String getOverview() {
return overview;
}
@JsonProperty("overview")
public void setOverview(String overview) {
this.overview = overview;
}
@JsonProperty("popularity")
public Double getPopularity() {
return popularity;
}
@JsonProperty("popularity")
public void setPopularity(Double popularity) {
this.popularity = popularity;
}
@JsonProperty("poster_path")
public String getPosterPath() {
return posterPath;
}
@JsonProperty("poster_path")
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
@JsonProperty("production_companies")
public List<MovieGetProductionCompany> getProductionCompanies() {
return productionCompanies;
}
@JsonProperty("production_companies")
public void setProductionCompanies(List<MovieGetProductionCompany> productionCompanies) {
this.productionCompanies = productionCompanies;
}
@JsonProperty("production_countries")
public List<MovieGetProductionCountry> getProductionCountries() {
return productionCountries;
}
@JsonProperty("production_countries")
public void setProductionCountries(List<MovieGetProductionCountry> productionCountries) {
this.productionCountries = productionCountries;
}
@JsonProperty("release_date")
public Date getReleaseDate() {
return releaseDate;
}
@JsonProperty("release_date")
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
@JsonProperty("revenue")
public Integer getRevenue() {
return revenue;
}
@JsonProperty("revenue")
public void setRevenue(Integer revenue) {
this.revenue = revenue;
}
@JsonProperty("runtime")
public Integer getRuntime() {
return runtime;
}
@JsonProperty("runtime")
public void setRuntime(Integer runtime) {
this.runtime = runtime;
}
@JsonProperty("spoken_languages")
public List<MovieGetSpokenLanguage> getMovieGetSpokenLanguages() {
return movieGetSpokenLanguages;
}
@JsonProperty("spoken_languages")
public void setMovieGetSpokenLanguages(List<MovieGetSpokenLanguage> movieGetSpokenLanguages) {
this.movieGetSpokenLanguages = movieGetSpokenLanguages;
}
@JsonProperty("status")
public String getStatus() {
return status;
}
@JsonProperty("status")
public void setStatus(String status) {
this.status = status;
}
@JsonProperty("tagline")
public String getTagline() {
return tagline;
}
@JsonProperty("tagline")
public void setTagline(String tagline) {
this.tagline = tagline;
}
@JsonProperty("title")
public String getTitle() {
return title;
}
@JsonProperty("title")
public void setTitle(String title) {
this.title = title;
}
@JsonProperty("video")
public Boolean getVideo() {
return video;
}
@JsonProperty("video")
public void setVideo(Boolean video) {
this.video = video;
}
@JsonProperty("vote_average")
public Double getVoteAverage() {
return voteAverage;
}
@JsonProperty("vote_average")
public void setVoteAverage(Double voteAverage) {
this.voteAverage = voteAverage;
}
@JsonProperty("vote_count")
public Integer getVoteCount() {
return voteCount;
}
@JsonProperty("vote_count")
public void setVoteCount(Integer voteCount) {
this.voteCount = voteCount;
}
@JsonProperty("external_ids")
public MovieGetExternalIds getMovieGetExternalIds() {
return movieGetExternalIds;
}
@JsonProperty("external_ids")
public void setMovieGetExternalIds(MovieGetExternalIds movieGetExternalIds) {
this.movieGetExternalIds = movieGetExternalIds;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
//@JsonInclude(JsonInclude.Include.NON_NULL)
//@JsonPropertyOrder({
// "id",
// "name",
// "poster_path",
// "backdrop_path"
//})
//class MovieGetBelongsToCollection {
//
// @JsonProperty("id")
// private Integer id;
// @JsonProperty("name")
// private String name;
// @JsonProperty("poster_path")
// private String posterPath;
// @JsonProperty("backdrop_path")
// private String backdropPath;
// @JsonIgnore
// private Map<String, Object> additionalProperties = new HashMap<String, Object>();
//
// @JsonProperty("id")
// public Integer getId() {
// return id;
// }
//
// @JsonProperty("id")
// public void setId(Integer id) {
// this.id = id;
// }
//
// @JsonProperty("name")
// public String getName() {
// return name;
// }
//
// @JsonProperty("name")
// public void setName(String name) {
// this.name = name;
// }
//
// @JsonProperty("poster_path")
// public String getPosterPath() {
// return posterPath;
// }
//
// @JsonProperty("poster_path")
// public void setPosterPath(String posterPath) {
// this.posterPath = posterPath;
// }
//
// @JsonProperty("backdrop_path")
// public String getBackdropPath() {
// return backdropPath;
// }
//
// @JsonProperty("backdrop_path")
// public void setBackdropPath(String backdropPath) {
// this.backdropPath = backdropPath;
// }
//
// @JsonAnyGetter
// public Map<String, Object> getAdditionalProperties() {
// return this.additionalProperties;
// }
//
// @JsonAnySetter
// public void setAdditionalProperty(String name, Object value) {
// this.additionalProperties.put(name, value);
// }
//
//} | OurFriendIrony/MediaNotifier | app/src/main/java/uk/co/ourfriendirony/medianotifier/clients/tmdb/movie/get/MovieGet.java | Java | apache-2.0 | 11,616 |
# [START maps_http_geocode_place_id]
import requests
url = "https://maps.googleapis.com/maps/api/geocode/json?place_id=ChIJd8BlQ2BZwokRAFUEcm_qrcA&key=YOUR_API_KEY"
payload={}
headers = {}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
# [END maps_http_geocode_place_id] | googlemaps/openapi-specification | dist/snippets/maps_http_geocode_place_id/maps_http_geocode_place_id.py | Python | apache-2.0 | 320 |
// file ExampleInventoryRead
// $Id: ExampleInventoryRead.java,v 1.10 2009/01/09 22:10:13 mark Exp $
package je.gettingStarted;
import java.io.File;
import java.io.IOException;
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.je.Cursor;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.SecondaryCursor;
public class ExampleInventoryRead {
private static File myDbEnvPath =
new File("/tmp/JEDB");
// Encapsulates the database environment and databases.
private static MyDbEnv myDbEnv = new MyDbEnv();
private static TupleBinding inventoryBinding;
private static EntryBinding vendorBinding;
// The item to locate if the -s switch is used
private static String locateItem;
private static void usage() {
System.out.println("ExampleInventoryRead [-h <env directory>]" +
"[-s <item to locate>]");
System.exit(-1);
}
public static void main(String args[]) {
ExampleInventoryRead eir = new ExampleInventoryRead();
try {
eir.run(args);
} catch (DatabaseException dbe) {
System.err.println("ExampleInventoryRead: " + dbe.toString());
dbe.printStackTrace();
} finally {
myDbEnv.close();
}
System.out.println("All done.");
}
private void run(String args[])
throws DatabaseException {
// Parse the arguments list
parseArgs(args);
myDbEnv.setup(myDbEnvPath, // path to the environment home
true); // is this environment read-only?
// Setup our bindings.
inventoryBinding = new InventoryBinding();
vendorBinding =
new SerialBinding(myDbEnv.getClassCatalog(),
Vendor.class);
if (locateItem != null) {
showItem();
} else {
showAllInventory();
}
}
private void showItem() throws DatabaseException {
SecondaryCursor secCursor = null;
try {
// searchKey is the key that we want to find in the
// secondary db.
DatabaseEntry searchKey =
new DatabaseEntry(locateItem.getBytes("UTF-8"));
// foundKey and foundData are populated from the primary
// entry that is associated with the secondary db key.
DatabaseEntry foundKey = new DatabaseEntry();
DatabaseEntry foundData = new DatabaseEntry();
// open a secondary cursor
secCursor =
myDbEnv.getNameIndexDB().openSecondaryCursor(null, null);
// Search for the secondary database entry.
OperationStatus retVal =
secCursor.getSearchKey(searchKey, foundKey,
foundData, LockMode.DEFAULT);
// Display the entry, if one is found. Repeat until no more
// secondary duplicate entries are found
while(retVal == OperationStatus.SUCCESS) {
Inventory theInventory =
(Inventory)inventoryBinding.entryToObject(foundData);
displayInventoryRecord(foundKey, theInventory);
retVal = secCursor.getNextDup(searchKey, foundKey,
foundData, LockMode.DEFAULT);
}
} catch (Exception e) {
System.err.println("Error on inventory secondary cursor:");
System.err.println(e.toString());
e.printStackTrace();
} finally {
if (secCursor != null) {
secCursor.close();
}
}
}
private void showAllInventory()
throws DatabaseException {
// Get a cursor
Cursor cursor = myDbEnv.getInventoryDB().openCursor(null, null);
// DatabaseEntry objects used for reading records
DatabaseEntry foundKey = new DatabaseEntry();
DatabaseEntry foundData = new DatabaseEntry();
try { // always want to make sure the cursor gets closed
while (cursor.getNext(foundKey, foundData,
LockMode.DEFAULT) == OperationStatus.SUCCESS) {
Inventory theInventory =
(Inventory)inventoryBinding.entryToObject(foundData);
displayInventoryRecord(foundKey, theInventory);
}
} catch (Exception e) {
System.err.println("Error on inventory cursor:");
System.err.println(e.toString());
e.printStackTrace();
} finally {
cursor.close();
}
}
private void displayInventoryRecord(DatabaseEntry theKey,
Inventory theInventory)
throws DatabaseException {
DatabaseEntry searchKey = null;
try {
String theSKU = new String(theKey.getData(), "UTF-8");
System.out.println(theSKU + ":");
System.out.println("\t " + theInventory.getItemName());
System.out.println("\t " + theInventory.getCategory());
System.out.println("\t " + theInventory.getVendor());
System.out.println("\t\tNumber in stock: " +
theInventory.getVendorInventory());
System.out.println("\t\tPrice per unit: " +
theInventory.getVendorPrice());
System.out.println("\t\tContact: ");
searchKey =
new DatabaseEntry(theInventory.getVendor().getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
DatabaseEntry foundVendor = new DatabaseEntry();
if (myDbEnv.getVendorDB().get(null, searchKey, foundVendor,
LockMode.DEFAULT) != OperationStatus.SUCCESS) {
System.out.println("Could not find vendor: " +
theInventory.getVendor() + ".");
System.exit(-1);
} else {
Vendor theVendor =
(Vendor)vendorBinding.entryToObject(foundVendor);
System.out.println("\t\t " + theVendor.getAddress());
System.out.println("\t\t " + theVendor.getCity() + ", " +
theVendor.getState() + " " + theVendor.getZipcode());
System.out.println("\t\t Business Phone: " +
theVendor.getBusinessPhoneNumber());
System.out.println("\t\t Sales Rep: " +
theVendor.getRepName());
System.out.println("\t\t " +
theVendor.getRepPhoneNumber());
}
}
protected ExampleInventoryRead() {}
private static void parseArgs(String args[]) {
for(int i = 0; i < args.length; ++i) {
if (args[i].startsWith("-")) {
switch(args[i].charAt(1)) {
case 'h':
myDbEnvPath = new File(args[++i]);
break;
case 's':
locateItem = new String(args[++i]);
break;
default:
usage();
}
}
}
}
}
| bjorndm/prebake | code/third_party/bdb/examples/je/gettingStarted/ExampleInventoryRead.java | Java | apache-2.0 | 7,325 |
<?php
/**
* @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
*/
/**
* Catalog product weight backend attribute model
*
* @author Magento Core Team <core@magentocommerce.com>
*/
namespace Magento\Catalog\Model\Product\Attribute\Backend;
class Weight extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
{
/**
* Validate
*
* @param \Magento\Catalog\Model\Product $object
* @throws \Magento\Framework\Model\Exception
* @return bool
*/
public function validate($object)
{
$attrCode = $this->getAttribute()->getAttributeCode();
$value = $object->getData($attrCode);
if (!empty($value) && !\Zend_Validate::is($value, 'Between', ['min' => 0, 'max' => 99999999.9999])) {
throw new \Magento\Framework\Model\Exception(__('Please enter a number 0 or greater in this field.'));
}
return true;
}
}
| webadvancedservicescom/magento | app/code/Magento/Catalog/Model/Product/Attribute/Backend/Weight.php | PHP | apache-2.0 | 941 |
/*
* Copyright 2018 TWO SIGMA OPEN SOURCE, 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 PlotStyleUtils from "beakerx_shared/lib/utils/PlotStyleUtils";
import PlotUtils from "./utils/PlotUtils";
export default class PlotCursor {
scope: any;
constructor(scope) {
this.scope = scope;
this.render = this.render.bind(this);
}
render(event) {
const x = event.offsetX;
const y = event.offsetY;
const width = PlotStyleUtils.safeWidth(this.scope.jqsvg);
const height = PlotStyleUtils.safeHeight(this.scope.jqsvg);
const leftMargin = this.scope.layout.leftLayoutMargin;
const bottomMargin = this.scope.layout.bottomLayoutMargin;
const rightMargin = this.scope.layout.rightLayoutMargin;
const topMargin = this.scope.layout.topLayoutMargin;
const model = this.scope.stdmodel;
if (
x < leftMargin
|| model.yAxisR != null && x > width - rightMargin
|| y > height - bottomMargin
|| y < topMargin
) {
this.scope.svg.selectAll(".plot-cursor").remove();
this.scope.jqcontainer.find(".plot-cursorlabel").remove();
return;
}
this.renderCursorX(x, height, topMargin, bottomMargin);
this.renderCursorY(y, width, leftMargin, rightMargin);
}
renderCursorX(x, height, topMargin, bottomMargin) {
if (this.scope.stdmodel.xCursor == null) {
return;
}
const model = this.scope.stdmodel;
const opt = model.xCursor;
const mapX = this.scope.plotRange.scr2dataX;
this.scope.svg.selectAll("#cursor_x")
.data([{}])
.enter()
.append("line")
.attr("id", "cursor_x")
.attr("class", "plot-cursor")
.style("stroke", opt.color)
.style("stroke-opacity", opt.color_opacity)
.style("stroke-width", opt.width)
.style("stroke-dasharray", opt.stroke_dasharray);
this.scope.svg.select("#cursor_x")
.attr("x1", x)
.attr("y1", topMargin)
.attr("x2", x)
.attr("y2", height - bottomMargin);
this.scope.jqcontainer.find("#cursor_xlabel").remove();
const label = $(`<div id="cursor_xlabel" class="plot-cursorlabel"></div>`)
.appendTo(this.scope.jqcontainer)
.text(PlotUtils.getTipStringPercent(mapX(x), model.xAxis));
const width = label.outerWidth();
const labelHeight = label.outerHeight();
const point = {
x: x - width / 2,
y: height - bottomMargin - this.scope.labelPadding.y - labelHeight
};
label.css({
"left" : point.x ,
"top" : point.y ,
"background-color" : opt.color != null ? opt.color : "black"
});
}
renderCursorY(y, width, leftMargin, rightMargin) {
if (this.scope.stdmodel.yCursor == null) {
return;
}
const model = this.scope.stdmodel;
const opt = model.yCursor;
this.scope.svg.selectAll("#cursor_y").data([{}]).enter().append("line")
.attr("id", "cursor_y")
.attr("class", "plot-cursor")
.style("stroke", opt.color)
.style("stroke-opacity", opt.color_opacity)
.style("stroke-width", opt.width)
.style("stroke-dasharray", opt.stroke_dasharray);
this.scope.svg.select("#cursor_y")
.attr("x1", leftMargin)
.attr("y1", y)
.attr("x2", width - rightMargin)
.attr("y2", y);
this.renderCursorLabel(model.yAxis, "cursor_ylabel", y, false);
if (model.yAxisR) {
this.renderCursorLabel(model.yAxisR, "cursor_yrlabel", y, true);
}
}
renderCursorLabel(axis, id, y, alignRight) {
if (axis == null) {
return;
}
const model = this.scope.stdmodel;
const opt = model.yCursor;
const lMargin = this.scope.layout.leftLayoutMargin;
const rMargin = this.scope.layout.rightLayoutMargin;
const mapY = this.scope.plotRange.scr2dataY;
this.scope.jqcontainer.find("#" + id).remove();
const label = $(`<div id="${id}" class='plot-cursorlabel'></div>`)
.appendTo(this.scope.jqcontainer)
.text(PlotUtils.getTipStringPercent(mapY(y), axis));
const height = label.outerHeight();
const point = { x: (alignRight ? rMargin : lMargin) + this.scope.labelPadding.x, y: y - height / 2 };
label.css({
"top" : point.y ,
"background-color" : opt.color != null ? opt.color : "black",
[alignRight ? "right" : "left"]: point.x
});
}
clear() {
this.scope.svg.selectAll(".plot-cursor").remove();
this.scope.jqcontainer.find(".plot-cursorlabel").remove();
}
}
| twosigma/beaker-notebook | js/notebook/src/plot/PlotCursor.ts | TypeScript | apache-2.0 | 4,974 |
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.server.integrationtests.optaplanner;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.server.api.exception.KieServicesException;
import org.kie.server.api.model.ReleaseId;
import org.kie.server.api.model.instance.ScoreWrapper;
import org.kie.server.api.model.instance.SolverInstance;
import org.kie.server.integrationtests.shared.KieServerAssert;
import org.kie.server.integrationtests.shared.KieServerDeployer;
import org.kie.server.integrationtests.shared.KieServerReflections;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.optaplanner.core.impl.solver.ProblemFactChange;
import static org.junit.Assert.*;
public class OptaplannerIntegrationTest
extends OptaplannerKieServerBaseIntegrationTest {
private static final ReleaseId kjar1 = new ReleaseId(
"org.kie.server.testing",
"cloudbalance",
"1.0.0.Final");
private static final String NOT_EXISTING_CONTAINER_ID = "no_container";
private static final String CONTAINER_1_ID = "cloudbalance";
private static final String SOLVER_1_ID = "cloudsolver";
private static final String SOLVER_1_CONFIG = "cloudbalance-solver.xml";
private static final String SOLVER_1_REALTIME_CONFIG = "cloudbalance-realtime-planning-solver.xml";
private static final String SOLVER_1_REALTIME_DAEMON_CONFIG = "cloudbalance-realtime-planning-daemon-solver.xml";
private static final String CLASS_CLOUD_BALANCE = "org.kie.server.testing.CloudBalance";
private static final String CLASS_CLOUD_COMPUTER = "org.kie.server.testing.CloudComputer";
private static final String CLASS_CLOUD_PROCESS = "org.kie.server.testing.CloudProcess";
private static final String CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE = "org.kie.server.testing.AddComputerProblemFactChange";
private static final String CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE = "org.kie.server.testing.DeleteComputerProblemFactChange";
private static final String CLASS_CLOUD_GENERATOR = "org.kie.server.testing.CloudBalancingGenerator";
@BeforeClass
public static void deployArtifacts() {
KieServerDeployer.buildAndDeployCommonMavenParent();
KieServerDeployer.buildAndDeployMavenProject(ClassLoader.class.getResource("/kjars-sources/cloudbalance").getFile());
kieContainer = KieServices.Factory.get().newKieContainer(kjar1);
createContainer(CONTAINER_1_ID,
kjar1);
}
@Override
protected void addExtraCustomClasses(Map<String, Class<?>> extraClasses)
throws ClassNotFoundException {
extraClasses.put(CLASS_CLOUD_BALANCE,
Class.forName(CLASS_CLOUD_BALANCE,
true,
kieContainer.getClassLoader()));
extraClasses.put(CLASS_CLOUD_COMPUTER,
Class.forName(CLASS_CLOUD_COMPUTER,
true,
kieContainer.getClassLoader()));
extraClasses.put(CLASS_CLOUD_PROCESS,
Class.forName(CLASS_CLOUD_PROCESS,
true,
kieContainer.getClassLoader()));
extraClasses.put(CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE,
Class.forName(CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE,
true,
kieContainer.getClassLoader()));
extraClasses.put(CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE,
Class.forName(CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE,
true,
kieContainer.getClassLoader()));
}
@Test
public void testCreateDisposeSolver() {
solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
SOLVER_1_CONFIG);
solverClient.disposeSolver(CONTAINER_1_ID,
SOLVER_1_ID);
}
@Test
public void testCreateSolverFromNotExistingContainer() {
try {
solverClient.createSolver(NOT_EXISTING_CONTAINER_ID,
SOLVER_1_ID,
SOLVER_1_CONFIG);
fail("A KieServicesException should have been thrown by now.");
} catch (KieServicesException e) {
KieServerAssert.assertResultContainsStringRegex(e.getMessage(),
".*Container '" + NOT_EXISTING_CONTAINER_ID + "' is not instantiated or cannot find container for alias '" + NOT_EXISTING_CONTAINER_ID + "'.*");
}
}
@Test(expected = IllegalArgumentException.class)
public void testCreateSolverWithoutConfigPath() {
solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
null);
}
@Test
public void testCreateSolverWrongConfigPath() {
try {
solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
"NonExistingPath");
fail("A KieServicesException should have been thrown by now.");
} catch (KieServicesException e) {
KieServerAssert.assertResultContainsStringRegex(e.getMessage(),
".*The solverConfigResource \\(.*\\) does not exist as a classpath resource in the classLoader \\(.*\\)*");
}
}
@Test(expected = IllegalArgumentException.class)
public void testCreateSolverNullContainer() {
solverClient.createSolver(null,
SOLVER_1_ID,
SOLVER_1_CONFIG);
}
@Test
public void testCreateDuplicitSolver() {
SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
SOLVER_1_CONFIG);
assertNotNull(solverInstance);
try {
solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
SOLVER_1_CONFIG);
fail("A KieServicesException should have been thrown by now.");
} catch (KieServicesException e) {
KieServerAssert.assertResultContainsStringRegex(e.getMessage(),
".*Failed to create solver. Solver .* already exists for container .*");
}
}
@Test
public void testDisposeNotExistingSolver() {
try {
solverClient.disposeSolver(CONTAINER_1_ID,
SOLVER_1_ID);
fail("A KieServicesException should have been thrown by now.");
} catch (KieServicesException e) {
KieServerAssert.assertResultContainsStringRegex(e.getMessage(),
".*Solver.*from container.*not found.*");
}
}
@Test
public void testGetSolverState() {
SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
SOLVER_1_CONFIG);
assertNotNull(solverInstance);
solverInstance = solverClient.getSolver(CONTAINER_1_ID,
SOLVER_1_ID);
assertNotNull(solverInstance);
assertEquals(CONTAINER_1_ID,
solverInstance.getContainerId());
assertEquals(SOLVER_1_CONFIG,
solverInstance.getSolverConfigFile());
assertEquals(SOLVER_1_ID,
solverInstance.getSolverId());
assertEquals(SolverInstance.getSolverInstanceKey(CONTAINER_1_ID,
SOLVER_1_ID),
solverInstance.getSolverInstanceKey());
assertEquals(SolverInstance.SolverStatus.NOT_SOLVING,
solverInstance.getStatus());
assertNotNull(solverInstance.getScoreWrapper());
assertNull(solverInstance.getScoreWrapper().toScore());
}
@Test
public void testGetNotExistingSolverState() {
try {
solverClient.getSolver(CONTAINER_1_ID,
SOLVER_1_ID);
fail("A KieServicesException should have been thrown by now.");
} catch (KieServicesException e) {
KieServerAssert.assertResultContainsStringRegex(e.getMessage(),
".*Solver.*not found in container.*");
}
}
@Test
public void testGetSolvers() {
List<SolverInstance> solverInstanceList = solverClient.getSolvers(CONTAINER_1_ID);
assertNotNull(solverInstanceList);
assertEquals(0,
solverInstanceList.size());
solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
SOLVER_1_CONFIG);
solverInstanceList = solverClient.getSolvers(CONTAINER_1_ID);
assertNotNull(solverInstanceList);
assertEquals(1,
solverInstanceList.size());
SolverInstance returnedInstance = solverInstanceList.get(0);
assertEquals(CONTAINER_1_ID,
returnedInstance.getContainerId());
assertEquals(SOLVER_1_CONFIG,
returnedInstance.getSolverConfigFile());
assertEquals(SOLVER_1_ID,
returnedInstance.getSolverId());
assertEquals(SolverInstance.getSolverInstanceKey(CONTAINER_1_ID,
SOLVER_1_ID),
returnedInstance.getSolverInstanceKey());
assertEquals(SolverInstance.SolverStatus.NOT_SOLVING,
returnedInstance.getStatus());
assertNotNull(returnedInstance.getScoreWrapper());
assertNull(returnedInstance.getScoreWrapper().toScore());
}
@Test
public void testExecuteSolver() throws Exception {
SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
SOLVER_1_CONFIG);
assertNotNull(solverInstance);
assertEquals(SolverInstance.SolverStatus.NOT_SOLVING,
solverInstance.getStatus());
// the following status starts the solver
Object planningProblem = loadPlanningProblem(5,
15);
solverClient.solvePlanningProblem(CONTAINER_1_ID,
SOLVER_1_ID,
planningProblem);
solverInstance = solverClient.getSolver(CONTAINER_1_ID,
SOLVER_1_ID);
// solver should finish in 5 seconds, but we wait up to 15s before timing out
for (int i = 0; i < 5 && solverInstance.getStatus() == SolverInstance.SolverStatus.SOLVING; i++) {
Thread.sleep(3000);
solverInstance = solverClient.getSolver(CONTAINER_1_ID,
SOLVER_1_ID);
assertNotNull(solverInstance);
}
assertEquals(SolverInstance.SolverStatus.NOT_SOLVING,
solverInstance.getStatus());
solverClient.disposeSolver(CONTAINER_1_ID,
SOLVER_1_ID);
}
@Test(timeout = 60_000)
public void testExecuteRealtimePlanningSolverSingleItemSubmit() throws Exception {
testExecuteRealtimePlanningSolverSingleItemSubmit(false);
}
@Test(timeout = 60_000)
public void testExecuteRealtimePlanningSolverSingleItemSubmitDaemonEnabled() throws Exception {
testExecuteRealtimePlanningSolverSingleItemSubmit(true);
}
private void testExecuteRealtimePlanningSolverSingleItemSubmit(boolean daemon) throws Exception {
SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
daemon ? SOLVER_1_REALTIME_DAEMON_CONFIG : SOLVER_1_REALTIME_CONFIG);
assertNotNull(solverInstance);
assertEquals(SolverInstance.SolverStatus.NOT_SOLVING,
solverInstance.getStatus());
final int computerCount = 5;
final int numberOfComputersToAdd = 5;
final Object planningProblem = loadPlanningProblem(computerCount,
15);
solverClient.solvePlanningProblem(CONTAINER_1_ID,
SOLVER_1_ID,
planningProblem);
SolverInstance solver = solverClient.getSolver(CONTAINER_1_ID,
SOLVER_1_ID);
assertEquals(SolverInstance.SolverStatus.SOLVING,
solver.getStatus());
Thread.sleep(3000);
List computerList = null;
for (int i = 0; i < numberOfComputersToAdd; i++) {
ProblemFactChange<?> problemFactChange = loadAddProblemFactChange(computerCount + i);
solverClient.addProblemFactChange(CONTAINER_1_ID,
SOLVER_1_ID,
problemFactChange);
do {
final Object bestSolution = verifySolverAndGetBestSolution();
computerList = getCloudBalanceComputerList(bestSolution);
} while (computerCount + i + 1 != computerList.size());
}
assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID,
SOLVER_1_ID));
Thread.sleep(3000);
assertNotNull(computerList);
for (int i = 0; i < numberOfComputersToAdd; i++) {
ProblemFactChange<?> problemFactChange = loadDeleteProblemFactChange(computerList.get(i));
solverClient.addProblemFactChange(CONTAINER_1_ID,
SOLVER_1_ID,
problemFactChange);
do {
final Object bestSolution = verifySolverAndGetBestSolution();
computerList = getCloudBalanceComputerList(bestSolution);
} while (computerCount + numberOfComputersToAdd - i - 1 != computerList.size());
}
assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID,
SOLVER_1_ID));
solverClient.disposeSolver(CONTAINER_1_ID,
SOLVER_1_ID);
}
@Test(timeout = 60_000)
public void testExecuteRealtimePlanningSolverBulkItemSubmit() throws Exception {
testExecuteRealtimePlanningSolverBulkItemSubmit(false);
}
@Test(timeout = 60_000)
public void testExecuteRealtimePlanningSolverBulkItemSubmitDaemonEnabled() throws Exception {
testExecuteRealtimePlanningSolverBulkItemSubmit(true);
}
private void testExecuteRealtimePlanningSolverBulkItemSubmit(boolean daemon) throws Exception {
SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
daemon ? SOLVER_1_REALTIME_DAEMON_CONFIG : SOLVER_1_REALTIME_CONFIG);
assertNotNull(solverInstance);
assertEquals(SolverInstance.SolverStatus.NOT_SOLVING,
solverInstance.getStatus());
final int initialComputerCount = 5;
final int numberOfComputersToAdd = 5;
final Object planningProblem = loadPlanningProblem(initialComputerCount,
15);
solverClient.solvePlanningProblem(CONTAINER_1_ID,
SOLVER_1_ID,
planningProblem);
SolverInstance solver = solverClient.getSolver(CONTAINER_1_ID,
SOLVER_1_ID);
assertEquals(SolverInstance.SolverStatus.SOLVING,
solver.getStatus());
Thread.sleep(3000);
List<ProblemFactChange> problemFactChangeList = new ArrayList<>(numberOfComputersToAdd);
for (int i = 0; i < numberOfComputersToAdd; i++) {
problemFactChangeList.add(loadAddProblemFactChange(initialComputerCount + i));
}
solverClient.addProblemFactChanges(CONTAINER_1_ID,
SOLVER_1_ID,
problemFactChangeList);
List computerList = null;
do {
final Object bestSolution = verifySolverAndGetBestSolution();
computerList = getCloudBalanceComputerList(bestSolution);
} while (initialComputerCount + numberOfComputersToAdd != computerList.size());
assertNotNull(computerList);
assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID,
SOLVER_1_ID));
Thread.sleep(3000);
problemFactChangeList.clear();
for (int i = 0; i < numberOfComputersToAdd; i++) {
problemFactChangeList.add(loadDeleteProblemFactChange(computerList.get(i)));
}
solverClient.addProblemFactChanges(CONTAINER_1_ID,
SOLVER_1_ID,
problemFactChangeList);
do {
final Object bestSolution = verifySolverAndGetBestSolution();
computerList = getCloudBalanceComputerList(bestSolution);
} while (initialComputerCount != computerList.size());
assertTrue(solverClient.isEveryProblemFactChangeProcessed(CONTAINER_1_ID,
SOLVER_1_ID));
solverClient.disposeSolver(CONTAINER_1_ID,
SOLVER_1_ID);
}
private Object verifySolverAndGetBestSolution() {
SolverInstance solver = solverClient.getSolverWithBestSolution(CONTAINER_1_ID,
SOLVER_1_ID);
assertEquals(SolverInstance.SolverStatus.SOLVING,
solver.getStatus());
Object bestSolution = solver.getBestSolution();
assertEquals(bestSolution.getClass().getName(),
CLASS_CLOUD_BALANCE);
return bestSolution;
}
private List getCloudBalanceComputerList(final Object cloudBalance) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method computerListMethod = cloudBalance.getClass().getDeclaredMethod("getComputerList");
return (List) computerListMethod.invoke(cloudBalance);
}
@Test
public void testExecuteRunningSolver() throws Exception {
SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
SOLVER_1_CONFIG);
assertNotNull(solverInstance);
assertEquals(SolverInstance.SolverStatus.NOT_SOLVING,
solverInstance.getStatus());
// start solver
Object planningProblem = loadPlanningProblem(5,
15);
solverClient.solvePlanningProblem(CONTAINER_1_ID,
SOLVER_1_ID,
planningProblem);
// start solver again
try {
solverClient.solvePlanningProblem(CONTAINER_1_ID,
SOLVER_1_ID,
planningProblem);
fail("A KieServicesException should have been thrown by now.");
} catch (KieServicesException e) {
KieServerAssert.assertResultContainsStringRegex(e.getMessage(),
".*Solver .* on container .* is already executing.*");
}
solverClient.disposeSolver(CONTAINER_1_ID,
SOLVER_1_ID);
}
@Test(timeout = 60000)
public void testGetBestSolution() throws Exception {
SolverInstance solverInstance = solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
SOLVER_1_CONFIG);
// Start the solver
Object planningProblem = loadPlanningProblem(10,
30);
solverClient.solvePlanningProblem(CONTAINER_1_ID,
SOLVER_1_ID,
planningProblem);
Object solution = null;
HardSoftScore score = null;
// It can take a while for the Construction Heuristic to initialize the solution
// The test timeout will interrupt this thread if it takes too long
while (!Thread.currentThread().isInterrupted()) {
solverInstance = solverClient.getSolverWithBestSolution(CONTAINER_1_ID,
SOLVER_1_ID);
assertNotNull(solverInstance);
solution = solverInstance.getBestSolution();
ScoreWrapper scoreWrapper = solverInstance.getScoreWrapper();
assertNotNull(scoreWrapper);
if (scoreWrapper.toScore() != null) {
assertEquals(HardSoftScore.class,
scoreWrapper.getScoreClass());
score = (HardSoftScore) scoreWrapper.toScore();
}
// Wait until the solver finished initializing the solution
if (solution != null && score != null && score.isSolutionInitialized()) {
break;
}
Thread.sleep(1000);
}
assertNotNull(score);
assertTrue(score.isSolutionInitialized());
assertTrue(score.getHardScore() <= 0);
// A soft score of 0 is impossible because we'll always need at least 1 computer
assertTrue(score.getSoftScore() < 0);
List<?> computerList = (List<?>) KieServerReflections.valueOf(solution,
"computerList");
assertEquals(10,
computerList.size());
List<?> processList = (List<?>) KieServerReflections.valueOf(solution,
"processList");
assertEquals(30,
processList.size());
for (Object process : processList) {
Object computer = KieServerReflections.valueOf(process,
"computer");
assertNotNull(computer);
// TODO: Change to identity comparation after @XmlID is implemented
assertTrue(computerList.contains(computer));
}
solverClient.disposeSolver(CONTAINER_1_ID,
SOLVER_1_ID);
}
@Test
public void testGetBestSolutionNotExistingSolver() {
try {
solverClient.getSolverWithBestSolution(CONTAINER_1_ID,
SOLVER_1_ID);
fail("A KieServicesException should have been thrown by now.");
} catch (KieServicesException e) {
KieServerAssert.assertResultContainsStringRegex(e.getMessage(),
".*Solver.*not found in container.*");
}
}
@Test
public void testTerminateEarlyNotExistingSolver() {
try {
solverClient.terminateSolverEarly(CONTAINER_1_ID,
SOLVER_1_ID);
fail("A KieServicesException should have been thrown by now.");
} catch (KieServicesException e) {
KieServerAssert.assertResultContainsStringRegex(e.getMessage(),
".*Solver.*not found in container.*");
}
}
@Test
public void testTerminateEarlyStoppedSolver() {
solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
SOLVER_1_CONFIG);
try {
solverClient.terminateSolverEarly(CONTAINER_1_ID,
SOLVER_1_ID);
fail("A KieServicesException should have been thrown by now.");
} catch (KieServicesException e) {
KieServerAssert.assertResultContainsStringRegex(e.getMessage(),
".*Solver.*from container.*is not executing.*");
}
}
@Test
public void testTerminateEarly() throws Exception {
solverClient.createSolver(CONTAINER_1_ID,
SOLVER_1_ID,
SOLVER_1_CONFIG);
// start solver
solverClient.solvePlanningProblem(CONTAINER_1_ID,
SOLVER_1_ID,
loadPlanningProblem(50,
150));
SolverInstance instance = solverClient.getSolver(CONTAINER_1_ID,
SOLVER_1_ID);
assertEquals(SolverInstance.SolverStatus.SOLVING,
instance.getStatus());
// and then terminate it
solverClient.terminateSolverEarly(CONTAINER_1_ID,
SOLVER_1_ID);
instance = solverClient.getSolver(CONTAINER_1_ID,
SOLVER_1_ID);
assertTrue(instance.getStatus() == SolverInstance.SolverStatus.TERMINATING_EARLY
|| instance.getStatus() == SolverInstance.SolverStatus.NOT_SOLVING);
solverClient.disposeSolver(CONTAINER_1_ID,
SOLVER_1_ID);
}
private Object loadPlanningProblem(int computerListSize,
int processListSize) throws NoSuchMethodException, ClassNotFoundException,
IllegalAccessException, InstantiationException, InvocationTargetException {
Class<?> cbgc = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_GENERATOR);
Object cbgi = cbgc.newInstance();
Method method = cbgc.getMethod("createCloudBalance",
int.class,
int.class);
return method.invoke(cbgi,
computerListSize,
processListSize);
}
private ProblemFactChange<?> loadAddProblemFactChange(final int currentNumberOfComputers) throws ClassNotFoundException,
IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<?> cbgc = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_GENERATOR);
Object cbgi = cbgc.newInstance();
Method method = cbgc.getMethod("createCloudComputer",
int.class);
Object cloudComputer = method.invoke(cbgi,
currentNumberOfComputers);
Class<?> cloudComputerClass = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_COMPUTER);
Class<?> problemFactChangeClass = kieContainer.getClassLoader().loadClass(CLASS_ADD_COMPUTER_PROBLEM_FACT_CHANGE);
Constructor<?> constructor = problemFactChangeClass.getConstructor(cloudComputerClass);
return (ProblemFactChange) constructor.newInstance(cloudComputer);
}
private ProblemFactChange<?> loadDeleteProblemFactChange(final Object cloudComputer) throws ClassNotFoundException,
NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> cloudComputerClass = kieContainer.getClassLoader().loadClass(CLASS_CLOUD_COMPUTER);
Class<?> problemFactChangeClass = kieContainer.getClassLoader().loadClass(CLASS_DELETE_COMPUTER_PROBLEM_FACT_CHANGE);
Constructor<?> constructor = problemFactChangeClass.getConstructor(cloudComputerClass);
return (ProblemFactChange) constructor.newInstance(cloudComputer);
}
}
| etirelli/droolsjbpm-integration | kie-server-parent/kie-server-tests/kie-server-integ-tests-optaplanner/src/test/java/org/kie/server/integrationtests/optaplanner/OptaplannerIntegrationTest.java | Java | apache-2.0 | 30,201 |
<?php
/*
* Copyright (C) 2017 Luis Pinto <luis.nestesitio@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Catrineta\form;
use \Catrineta\form\Input;
/**
* Description of Form
*
* @author Luís Pinto / luis.nestesitio@gmail.com
* Created @Sep 22, 2017
*/
class Form
{
/**
*
* @var array The models to be merged
*/
protected $models = [];
function __construct()
{
}
/**
* @var array
*/
protected $forminputs = [];
/**
* @param string $field
* @param \Catrineta\form\Input $input
* @return \Catrineta\form\Input
*/
public function setFieldInput($field, Input $input)
{
$this->forminputs[$field] = $input;
return $this->forminputs[$field];
}
/**
* @param $field
* @return $this
*/
public function unsetFieldInput($field)
{
unset($this->forminputs[$field]);
return $this;
}
/**
* @param $field
* @param $value
* @return mixed
*/
public function setFieldValue($field, $value)
{
return $this->forminputs[$field]->setValue($value);
}
public function renderFormInputs()
{
$inputs = [];
foreach ($this->forminputs as $input){
$inputs[] = $input->parseInput();
}
return $inputs;
}
public function getInputs()
{
return $this->forminputs;
}
public static function renderInput($input)
{
echo $input;
}
}
| nestesitio/mvc-catrineta | catrineta/form/Form.php | PHP | apache-2.0 | 2,183 |
$(function() {
var search = $("#search");
var submissions = $("#submissions tbody tr");
search.on('keyup', function(event) {
var filter = search.val();
submissions.each(function(index, elem) {
var $elem = $(elem);
$elem.toggle($elem.data("student").indexOf(filter) !== -1);
});
})
});
| josalmi/lapio-stats | app/assets/javascripts/submissions.js | JavaScript | apache-2.0 | 318 |
/*
* Copyright 2016 Netflix, 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 io.rsocket.transport.local;
import io.rsocket.transport.ClientTransport;
import io.rsocket.transport.ServerTransport;
import io.rsocket.uri.UriHandler;
import java.net.URI;
import java.util.Optional;
public class LocalUriHandler implements UriHandler {
@Override
public Optional<ClientTransport> buildClient(URI uri) {
if ("local".equals(uri.getScheme())) {
return Optional.of(LocalClientTransport.create(uri.getSchemeSpecificPart()));
}
return UriHandler.super.buildClient(uri);
}
@Override
public Optional<ServerTransport> buildServer(URI uri) {
if ("local".equals(uri.getScheme())) {
return Optional.of(LocalServerTransport.create(uri.getSchemeSpecificPart()));
}
return UriHandler.super.buildServer(uri);
}
}
| qweek/rsocket-java | rsocket-transport-local/src/main/java/io/rsocket/transport/local/LocalUriHandler.java | Java | apache-2.0 | 1,377 |
/*
* Copyright 2010-2021 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$
*/
package com.hack23.cia.systemintegrationtest;
import java.util.Map;
import java.util.Map.Entry;
import org.dussan.vaadin.dcharts.base.elements.XYaxis;
import org.dussan.vaadin.dcharts.base.elements.XYseries;
import org.dussan.vaadin.dcharts.helpers.ClassHelper;
import org.dussan.vaadin.dcharts.helpers.ObjectHelper;
import org.dussan.vaadin.dcharts.metadata.XYaxes;
import org.junit.Assert;
import org.junit.Test;
public final class ChartTest extends Assert {
/**
* To json string.
*
* @param object
* the object
* @return the string
*/
public static String toJsonString(final Object object) {
try {
final Map<String, Object> values = ClassHelper.getFieldValues(object);
final StringBuilder builder = new StringBuilder();
for (final Entry<String, Object> entry : values.entrySet()) {
final String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
if (!fieldName.contains("jacocoData")) {
if (ObjectHelper.isArray(fieldValue)) {
if (fieldValue instanceof Object[][]) {
fieldValue = ObjectHelper
.toArrayString((Object[][]) fieldValue);
} else if (fieldValue instanceof boolean[]) {
} else
{
fieldValue = ObjectHelper
.toArrayString((Object[]) fieldValue);
}
}
if (fieldValue != null) {
fieldValue = !ObjectHelper.isString(fieldValue) ? fieldValue
: fieldValue.toString().replaceAll("\"", "'");
builder.append(builder.length() > 0 ? ", " : "");
builder.append(fieldName).append(": ");
builder.append(ObjectHelper.isString(fieldValue) ? "\""
: "");
builder.append(fieldValue);
builder.append(ObjectHelper.isString(fieldValue) ? "\""
: "");
}
}
}
return builder.insert(0, "{").append("}").toString();
} catch (final Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Adds the serie test.
*/
@Test
public void addSerieTest() {
final XYseries label = new XYseriesFix();
label.setLabel("sune");
toJsonString(label);
assertNotNull("Problem with toJsonString, no label",label);
}
static class XYaxisFix extends XYaxis {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Instantiates a new x yaxis fix.
*/
public XYaxisFix() {
super();
}
/**
* Instantiates a new x yaxis fix.
*
* @param y
* the y
*/
public XYaxisFix(final XYaxes y) {
super(y);
}
@Override
public String getValue() {
return toJsonString(this);
}
}
static class XYseriesFix extends XYseries {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
@Override
public String getValue() {
return toJsonString(this);
}
}
}
| Hack23/cia | citizen-intelligence-agency/src/test/java/com/hack23/cia/systemintegrationtest/ChartTest.java | Java | apache-2.0 | 3,413 |
package es.josealmela.BasicMathCalculator.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* The async counterpart of <code>convertNumberService</code>.
*/
public interface ConverNumberServiceAsync {
void convertNumbertServer(String input, AsyncCallback<String> callback)
throws IllegalArgumentException;
}
| jalmela/BasicMathCalculator | BasicMathCalculator/src/es/josealmela/BasicMathCalculator/client/ConverNumberServiceAsync.java | Java | apache-2.0 | 335 |
package org.dfhu.thpwa.routing;
abstract class RouteAdder<T extends Route> {
/**
* Get the url pattern for this route
*/
protected abstract String getPath();
/**
* get the HTTP request method
*/
protected abstract Route.METHOD getMethod();
public void doGet(RouteAdder<T> routeAdder) {
Halting.haltNotImplemented();
}
public void doPost(RouteAdder<T> routeAdder) {
Halting.haltNotImplemented();
}
public void addRoute() {
Route.METHOD method = getMethod();
switch (method) {
case GET:
doGet(this);
break;
case POST:
doPost(this);
break;
default:
throw new RuntimeException("Request Method not implemented");
}
}
}
| Victory/TreasureHuntPWA | backspark/src/main/java/org/dfhu/thpwa/routing/RouteAdder.java | Java | apache-2.0 | 730 |
package com.github.takezoe.xlsbeans;
import com.github.takezoe.xlsbeans.annotation.Column;
import com.github.takezoe.xlsbeans.annotation.MapColumns;
import java.util.Map;
public class LanguageIDE {
private String name;
private Map<String, String> attributes;
public Map<String, String> getAttributes() {
return attributes;
}
@MapColumns(previousColumnName = "Name")
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public String getName() {
return name;
}
@Column(columnName = "Name")
public void setName(String name) {
this.name = name;
}
}
| takezoe/xlsbeans | src/test/java/com/github/takezoe/xlsbeans/LanguageIDE.java | Java | apache-2.0 | 665 |
package com.ironz.binaryprefs;
import com.ironz.binaryprefs.cache.candidates.CacheCandidateProvider;
import com.ironz.binaryprefs.cache.provider.CacheProvider;
import com.ironz.binaryprefs.event.EventBridge;
import com.ironz.binaryprefs.exception.TransactionInvalidatedException;
import com.ironz.binaryprefs.file.transaction.FileTransaction;
import com.ironz.binaryprefs.file.transaction.TransactionElement;
import com.ironz.binaryprefs.serialization.SerializerFactory;
import com.ironz.binaryprefs.serialization.serializer.persistable.Persistable;
import com.ironz.binaryprefs.serialization.strategy.SerializationStrategy;
import com.ironz.binaryprefs.serialization.strategy.impl.*;
import com.ironz.binaryprefs.task.barrier.FutureBarrier;
import com.ironz.binaryprefs.task.TaskExecutor;
import java.util.*;
import java.util.concurrent.locks.Lock;
final class BinaryPreferencesEditor implements PreferencesEditor {
private static final String TRANSACTED_TWICE_MESSAGE = "Transaction should be applied or committed only once!";
private final Map<String, SerializationStrategy> strategyMap = new HashMap<>();
private final Set<String> removeSet = new HashSet<>();
private final FileTransaction fileTransaction;
private final EventBridge bridge;
private final TaskExecutor taskExecutor;
private final SerializerFactory serializerFactory;
private final CacheProvider cacheProvider;
private final CacheCandidateProvider candidateProvider;
private final Lock writeLock;
private boolean invalidated;
BinaryPreferencesEditor(FileTransaction fileTransaction,
EventBridge bridge,
TaskExecutor taskExecutor,
SerializerFactory serializerFactory,
CacheProvider cacheProvider,
CacheCandidateProvider candidateProvider,
Lock writeLock) {
this.fileTransaction = fileTransaction;
this.bridge = bridge;
this.taskExecutor = taskExecutor;
this.serializerFactory = serializerFactory;
this.cacheProvider = cacheProvider;
this.candidateProvider = candidateProvider;
this.writeLock = writeLock;
}
@Override
public PreferencesEditor putString(String key, String value) {
if (value == null) {
return remove(key);
}
writeLock.lock();
try {
SerializationStrategy strategy = new StringSerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor putStringSet(String key, Set<String> value) {
if (value == null) {
return remove(key);
}
writeLock.lock();
try {
SerializationStrategy strategy = new StringSetSerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor putInt(String key, int value) {
writeLock.lock();
try {
SerializationStrategy strategy = new IntegerSerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor putLong(String key, long value) {
writeLock.lock();
try {
SerializationStrategy strategy = new LongSerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor putFloat(String key, float value) {
writeLock.lock();
try {
SerializationStrategy strategy = new FloatSerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor putBoolean(String key, boolean value) {
writeLock.lock();
try {
SerializationStrategy strategy = new BooleanSerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public <T extends Persistable> PreferencesEditor putPersistable(String key, T value) {
if (value == null) {
return remove(key);
}
writeLock.lock();
try {
SerializationStrategy strategy = new PersistableSerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor putByte(String key, byte value) {
writeLock.lock();
try {
SerializationStrategy strategy = new ByteSerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor putShort(String key, short value) {
writeLock.lock();
try {
SerializationStrategy strategy = new ShortSerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor putChar(String key, char value) {
writeLock.lock();
try {
SerializationStrategy strategy = new CharSerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor putDouble(String key, double value) {
writeLock.lock();
try {
SerializationStrategy strategy = new DoubleSerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor putByteArray(String key, byte[] value) {
writeLock.lock();
try {
SerializationStrategy strategy = new ByteArraySerializationStrategy(value, serializerFactory);
strategyMap.put(key, strategy);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor remove(String key) {
writeLock.lock();
try {
removeSet.add(key);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public PreferencesEditor clear() {
writeLock.lock();
try {
Set<String> all = candidateProvider.keys();
removeSet.addAll(all);
return this;
} finally {
writeLock.unlock();
}
}
@Override
public void apply() {
writeLock.lock();
try {
performTransaction();
} finally {
writeLock.unlock();
}
}
@Override
public boolean commit() {
writeLock.lock();
try {
FutureBarrier barrier = performTransaction();
return barrier.completeBlockingWithStatus();
} finally {
writeLock.unlock();
}
}
private FutureBarrier performTransaction() {
removeCache();
storeCache();
invalidate();
return taskExecutor.submit(new Runnable() {
@Override
public void run() {
commitTransaction();
}
});
}
private void removeCache() {
for (String name : removeSet) {
candidateProvider.remove(name);
cacheProvider.remove(name);
}
}
private void storeCache() {
for (String name : strategyMap.keySet()) {
SerializationStrategy strategy = strategyMap.get(name);
Object value = strategy.getValue();
candidateProvider.put(name);
cacheProvider.put(name, value);
}
}
private void invalidate() {
if (invalidated) {
throw new TransactionInvalidatedException(TRANSACTED_TWICE_MESSAGE);
}
invalidated = true;
}
private void commitTransaction() {
List<TransactionElement> transaction = createTransaction();
fileTransaction.commit(transaction);
notifyListeners(transaction);
}
private List<TransactionElement> createTransaction() {
List<TransactionElement> elements = new LinkedList<>();
elements.addAll(removePersistence());
elements.addAll(storePersistence());
return elements;
}
private List<TransactionElement> removePersistence() {
List<TransactionElement> elements = new LinkedList<>();
for (String name : removeSet) {
TransactionElement e = TransactionElement.createRemovalElement(name);
elements.add(e);
}
return elements;
}
private List<TransactionElement> storePersistence() {
Set<String> strings = strategyMap.keySet();
List<TransactionElement> elements = new LinkedList<>();
for (String name : strings) {
SerializationStrategy strategy = strategyMap.get(name);
byte[] bytes = strategy.serialize();
TransactionElement e = TransactionElement.createUpdateElement(name, bytes);
elements.add(e);
}
return elements;
}
private void notifyListeners(List<TransactionElement> transaction) {
for (TransactionElement element : transaction) {
String name = element.getName();
byte[] bytes = element.getContent();
if (element.getAction() == TransactionElement.ACTION_REMOVE) {
bridge.notifyListenersRemove(name);
}
if (element.getAction() == TransactionElement.ACTION_UPDATE) {
bridge.notifyListenersUpdate(name, bytes);
}
}
}
} | iamironz/binaryprefs | library/src/main/java/com/ironz/binaryprefs/BinaryPreferencesEditor.java | Java | apache-2.0 | 10,537 |
package org.jrenner.fps.utils;
import com.badlogic.gdx.utils.Array;
import org.jrenner.fps.Log;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class Compression {
public static byte[] writeCompressedString(String s) {
GZIPOutputStream gzout = null;
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
gzout = new GZIPOutputStream(bout);
gzout.write(s.getBytes());
gzout.flush();
gzout.close();
return bout.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzout != null) {
try {
gzout.flush();
gzout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static String decompressToString(byte[] bytes) {
GZIPInputStream gzin = null;
try {
gzin = new GZIPInputStream(new ByteArrayInputStream(bytes));
byte[] buf = new byte[8192];
byte[] storage = new byte[65536];
int n = 0;
int total = 0;
while (true) {
n = gzin.read(buf);
if (n == -1) break;
// expand to meet needs
if (total + n >= storage.length) {
byte[] expanded = new byte[storage.length * 2];
System.arraycopy(storage, 0, expanded, 0, storage.length);
storage = expanded;
}
System.out.printf("blen: %d, storlen: %d, total: %d, n: %d\n", buf.length, storage.length, total, n);
System.arraycopy(buf, 0, storage, total, n);
total += n;
}
Log.debug("read " + total + " bytes from compressed files");
byte[] result = new byte[total];
System.arraycopy(storage, 0, result, 0, total);
return new String(result);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (gzin != null) {
try {
gzin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
| jrenner/gdx-proto | core/src/org/jrenner/fps/utils/Compression.java | Java | apache-2.0 | 1,974 |
package demo.hashing;
import java.nio.ByteBuffer;
public class CassandraHash {
private static long getblock(ByteBuffer key, int offset, int index) {
int i_8 = index << 3;
return ((long) key.get(offset + i_8 + 0) & 0xff) + (((long) key.get(offset + i_8 + 1) & 0xff) << 8) +
(((long) key.get(offset + i_8 + 2) & 0xff) << 16) + (((long) key.get(offset + i_8 + 3) & 0xff) << 24) +
(((long) key.get(offset + i_8 + 4) & 0xff) << 32) + (((long) key.get(offset + i_8 + 5) & 0xff) << 40) +
(((long) key.get(offset + i_8 + 6) & 0xff) << 48) + (((long) key.get(offset + i_8 + 7) & 0xff) << 56);
}
private static long rotl64(long v, int n) {
return ((v << n) | (v >>> (64 - n)));
}
private static long fmix(long k) {
k ^= k >>> 33;
k *= 0xff51afd7ed558ccdL;
k ^= k >>> 33;
k *= 0xc4ceb9fe1a85ec53L;
k ^= k >>> 33;
return k;
}
//taken from com.twitter.algebird.CassandraMurmurHash
public static long[] hash3_x64_128(ByteBuffer key, int offset, int length, long seed) {
final int nblocks = length >> 4; // Process as 128-bit blocks.
long h1 = seed;
long h2 = seed;
long c1 = 0x87c37b91114253d5L;
long c2 = 0x4cf5ad432745937fL;
//----------
// body
for (int i = 0; i < nblocks; i++) {
long k1 = getblock(key, offset, i * 2 + 0);
long k2 = getblock(key, offset, i * 2 + 1);
k1 *= c1;
k1 = rotl64(k1, 31);
k1 *= c2;
h1 ^= k1;
h1 = rotl64(h1, 27);
h1 += h2;
h1 = h1 * 5 + 0x52dce729;
k2 *= c2;
k2 = rotl64(k2, 33);
k2 *= c1;
h2 ^= k2;
h2 = rotl64(h2, 31);
h2 += h1;
h2 = h2 * 5 + 0x38495ab5;
}
//----------
// tail
// Advance offset to the unprocessed tail of the data.
offset += nblocks * 16;
long k1 = 0;
long k2 = 0;
switch (length & 15) {
case 15:
k2 ^= ((long) key.get(offset + 14)) << 48;
case 14:
k2 ^= ((long) key.get(offset + 13)) << 40;
case 13:
k2 ^= ((long) key.get(offset + 12)) << 32;
case 12:
k2 ^= ((long) key.get(offset + 11)) << 24;
case 11:
k2 ^= ((long) key.get(offset + 10)) << 16;
case 10:
k2 ^= ((long) key.get(offset + 9)) << 8;
case 9:
k2 ^= ((long) key.get(offset + 8)) << 0;
k2 *= c2;
k2 = rotl64(k2, 33);
k2 *= c1;
h2 ^= k2;
case 8:
k1 ^= ((long) key.get(offset + 7)) << 56;
case 7:
k1 ^= ((long) key.get(offset + 6)) << 48;
case 6:
k1 ^= ((long) key.get(offset + 5)) << 40;
case 5:
k1 ^= ((long) key.get(offset + 4)) << 32;
case 4:
k1 ^= ((long) key.get(offset + 3)) << 24;
case 3:
k1 ^= ((long) key.get(offset + 2)) << 16;
case 2:
k1 ^= ((long) key.get(offset + 1)) << 8;
case 1:
k1 ^= ((long) key.get(offset));
k1 *= c1;
k1 = rotl64(k1, 31);
k1 *= c2;
h1 ^= k1;
}
;
//----------
// finalization
h1 ^= length;
h2 ^= length;
h1 += h2;
h2 += h1;
h1 = fmix(h1);
h2 = fmix(h2);
h1 += h2;
h2 += h1;
return (new long[]{h1, h2});
}
//kafka utils
public static int murmur2(final byte[] data) {
int length = data.length;
int seed = 0x9747b28c;
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
final int m = 0x5bd1e995;
final int r = 24;
// Initialize the hash to a random value
int h = seed ^ length;
int length4 = length / 4;
for (int i = 0; i < length4; i++) {
final int i4 = i * 4;
int k = (data[i4 + 0] & 0xff) + ((data[i4 + 1] & 0xff) << 8) + ((data[i4 + 2] & 0xff) << 16) + ((data[i4 + 3] & 0xff) << 24);
k *= m;
k ^= k >>> r;
k *= m;
h *= m;
h ^= k;
}
// Handle the last few bytes of the input array
switch (length % 4) {
case 3:
h ^= (data[(length & ~3) + 2] & 0xff) << 16;
case 2:
h ^= (data[(length & ~3) + 1] & 0xff) << 8;
case 1:
h ^= (data[length & ~3] & 0xff);
h *= m;
}
h ^= h >>> 13;
h *= m;
h ^= h >>> 15;
return h;
}
}
| haghard/docker-compose-akka-cluster | src/main/scala/demo/hashing/CassandraHash.java | Java | apache-2.0 | 4,268 |
/*
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.pricer.swaption;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.OptionalInt;
import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaBean;
import org.joda.beans.MetaProperty;
import org.joda.beans.gen.BeanDefinition;
import org.joda.beans.gen.ImmutableConstructor;
import org.joda.beans.gen.PropertyDefinition;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import org.joda.beans.impl.direct.DirectPrivateBeanBuilder;
import com.opengamma.strata.basics.date.DayCount;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.data.MarketDataName;
import com.opengamma.strata.market.ValueType;
import com.opengamma.strata.market.param.CurrencyParameterSensitivities;
import com.opengamma.strata.market.param.CurrencyParameterSensitivity;
import com.opengamma.strata.market.param.ParameterMetadata;
import com.opengamma.strata.market.param.ParameterPerturbation;
import com.opengamma.strata.market.param.UnitParameterSensitivity;
import com.opengamma.strata.market.sensitivity.PointSensitivities;
import com.opengamma.strata.market.sensitivity.PointSensitivity;
import com.opengamma.strata.market.surface.InterpolatedNodalSurface;
import com.opengamma.strata.market.surface.Surface;
import com.opengamma.strata.market.surface.SurfaceInfoType;
import com.opengamma.strata.market.surface.Surfaces;
import com.opengamma.strata.pricer.impl.option.NormalFormulaRepository;
import com.opengamma.strata.product.common.PutCall;
import com.opengamma.strata.product.swap.type.FixedFloatSwapConvention;
import com.opengamma.strata.product.swap.type.FixedIborSwapConvention;
/**
* Volatility for swaptions in the normal or Bachelier model based on a surface.
* <p>
* The volatility is represented by a surface on the expiry and strike dimensions.
*/
@BeanDefinition(builderScope = "private")
public final class NormalSwaptionExpiryStrikeVolatilities
implements NormalSwaptionVolatilities, ImmutableBean, Serializable {
/**
* The swap convention that the volatilities are to be used for.
*/
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final FixedFloatSwapConvention convention;
/**
* The valuation date-time.
* <p>
* The volatilities are calibrated for this date-time.
*/
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final ZonedDateTime valuationDateTime;
/**
* The normal volatility surface.
* <p>
* The x-value of the surface is the expiry, as a year fraction.
* The y-value of the surface is the strike, as a rate.
*/
@PropertyDefinition(validate = "notNull")
private final Surface surface;
/**
* The day count convention of the surface.
*/
private final transient DayCount dayCount; // cached, not a property
//-------------------------------------------------------------------------
/**
* Obtains an instance from the implied volatility surface and the date-time for which it is valid.
* <p>
* The surface is specified by an instance of {@link Surface}, such as {@link InterpolatedNodalSurface}.
* The surface must contain the correct metadata:
* <ul>
* <li>The x-value type must be {@link ValueType#YEAR_FRACTION}
* <li>The y-value type must be {@link ValueType#STRIKE}
* <li>The z-value type must be {@link ValueType#NORMAL_VOLATILITY}
* <li>The day count must be set in the additional information using {@link SurfaceInfoType#DAY_COUNT}
* </ul>
* Suitable surface metadata can be created using
* {@link Surfaces#normalVolatilityByExpiryStrike(String, DayCount)}.
*
* @param convention the swap convention that the volatilities are to be used for
* @param valuationDateTime the valuation date-time
* @param surface the implied volatility surface
* @return the volatilities
*/
public static NormalSwaptionExpiryStrikeVolatilities of(
FixedFloatSwapConvention convention,
ZonedDateTime valuationDateTime,
Surface surface) {
return new NormalSwaptionExpiryStrikeVolatilities(convention, valuationDateTime, surface);
}
@ImmutableConstructor
private NormalSwaptionExpiryStrikeVolatilities(
FixedFloatSwapConvention convention,
ZonedDateTime valuationDateTime,
Surface surface) {
ArgChecker.notNull(convention, "convention");
ArgChecker.notNull(valuationDateTime, "valuationDateTime");
ArgChecker.notNull(surface, "surface");
surface.getMetadata().getXValueType().checkEquals(
ValueType.YEAR_FRACTION, "Incorrect x-value type for Normal volatilities");
surface.getMetadata().getYValueType().checkEquals(
ValueType.STRIKE, "Incorrect y-value type for Normal volatilities");
surface.getMetadata().getZValueType().checkEquals(
ValueType.NORMAL_VOLATILITY, "Incorrect z-value type for Normal volatilities");
DayCount dayCount = surface.getMetadata().findInfo(SurfaceInfoType.DAY_COUNT)
.orElseThrow(() -> new IllegalArgumentException("Incorrect surface metadata, missing DayCount"));
this.valuationDateTime = valuationDateTime;
this.surface = surface;
this.convention = convention;
this.dayCount = dayCount;
}
// ensure standard constructor is invoked
private Object readResolve() {
return new NormalSwaptionExpiryStrikeVolatilities(convention, valuationDateTime, surface);
}
//-------------------------------------------------------------------------
@Override
public SwaptionVolatilitiesName getName() {
return SwaptionVolatilitiesName.of(surface.getName().getName());
}
@Override
public <T> Optional<T> findData(MarketDataName<T> name) {
if (surface.getName().equals(name)) {
return Optional.of(name.getMarketDataType().cast(surface));
}
return Optional.empty();
}
@Override
public int getParameterCount() {
return surface.getParameterCount();
}
@Override
public double getParameter(int parameterIndex) {
return surface.getParameter(parameterIndex);
}
@Override
public ParameterMetadata getParameterMetadata(int parameterIndex) {
return surface.getParameterMetadata(parameterIndex);
}
@Override
public OptionalInt findParameterIndex(ParameterMetadata metadata) {
return surface.findParameterIndex(metadata);
}
@Override
public NormalSwaptionExpiryStrikeVolatilities withParameter(int parameterIndex, double newValue) {
return new NormalSwaptionExpiryStrikeVolatilities(
convention, valuationDateTime, surface.withParameter(parameterIndex, newValue));
}
@Override
public NormalSwaptionExpiryStrikeVolatilities withPerturbation(ParameterPerturbation perturbation) {
return new NormalSwaptionExpiryStrikeVolatilities(
convention, valuationDateTime, surface.withPerturbation(perturbation));
}
//-------------------------------------------------------------------------
@Override
public double volatility(double expiry, double tenor, double strike, double forwardRate) {
return surface.zValue(expiry, strike);
}
@Override
public CurrencyParameterSensitivities parameterSensitivity(PointSensitivities pointSensitivities) {
CurrencyParameterSensitivities sens = CurrencyParameterSensitivities.empty();
for (PointSensitivity point : pointSensitivities.getSensitivities()) {
if (point instanceof SwaptionSensitivity) {
SwaptionSensitivity pt = (SwaptionSensitivity) point;
if (pt.getVolatilitiesName().equals(getName())) {
sens = sens.combinedWith(parameterSensitivity(pt));
}
}
}
return sens;
}
private CurrencyParameterSensitivity parameterSensitivity(SwaptionSensitivity point) {
double expiry = point.getExpiry();
double strike = point.getStrike();
UnitParameterSensitivity unitSens = surface.zValueParameterSensitivity(expiry, strike);
return unitSens.multipliedBy(point.getCurrency(), point.getSensitivity());
}
//-------------------------------------------------------------------------
@Override
public double price(double expiry, double tenor, PutCall putCall, double strike, double forward, double volatility) {
return NormalFormulaRepository.price(forward, strike, expiry, volatility, putCall);
}
@Override
public double priceDelta(double expiry, double tenor, PutCall putCall, double strike, double forward, double volatility) {
return NormalFormulaRepository.delta(forward, strike, expiry, volatility, putCall);
}
@Override
public double priceGamma(double expiry, double tenor, PutCall putCall, double strike, double forward, double volatility) {
return NormalFormulaRepository.gamma(forward, strike, expiry, volatility, putCall);
}
@Override
public double priceTheta(double expiry, double tenor, PutCall putCall, double strike, double forward, double volatility) {
return NormalFormulaRepository.theta(forward, strike, expiry, volatility, putCall);
}
@Override
public double priceVega(double expiry, double tenor, PutCall putCall, double strike, double forward, double volatility) {
return NormalFormulaRepository.vega(forward, strike, expiry, volatility, putCall);
}
//-------------------------------------------------------------------------
@Override
public double relativeTime(ZonedDateTime dateTime) {
ArgChecker.notNull(dateTime, "dateTime");
LocalDate valuationDate = valuationDateTime.toLocalDate();
LocalDate date = dateTime.toLocalDate();
return dayCount.relativeYearFraction(valuationDate, date);
}
@Override
public double tenor(LocalDate startDate, LocalDate endDate) {
// rounded number of months. the rounding is to ensure that an integer number of year even with holidays/leap year
return Math.round((endDate.toEpochDay() - startDate.toEpochDay()) / 365.25 * 12) / 12;
}
//------------------------- AUTOGENERATED START -------------------------
/**
* The meta-bean for {@code NormalSwaptionExpiryStrikeVolatilities}.
* @return the meta-bean, not null
*/
public static NormalSwaptionExpiryStrikeVolatilities.Meta meta() {
return NormalSwaptionExpiryStrikeVolatilities.Meta.INSTANCE;
}
static {
MetaBean.register(NormalSwaptionExpiryStrikeVolatilities.Meta.INSTANCE);
}
/**
* The serialization version id.
*/
private static final long serialVersionUID = 1L;
@Override
public NormalSwaptionExpiryStrikeVolatilities.Meta metaBean() {
return NormalSwaptionExpiryStrikeVolatilities.Meta.INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Gets the swap convention that the volatilities are to be used for.
* @return the value of the property, not null
*/
@Override
public FixedFloatSwapConvention getConvention() {
return convention;
}
//-----------------------------------------------------------------------
/**
* Gets the valuation date-time.
* <p>
* The volatilities are calibrated for this date-time.
* @return the value of the property, not null
*/
@Override
public ZonedDateTime getValuationDateTime() {
return valuationDateTime;
}
//-----------------------------------------------------------------------
/**
* Gets the normal volatility surface.
* <p>
* The x-value of the surface is the expiry, as a year fraction.
* The y-value of the surface is the strike, as a rate.
* @return the value of the property, not null
*/
public Surface getSurface() {
return surface;
}
//-----------------------------------------------------------------------
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
NormalSwaptionExpiryStrikeVolatilities other = (NormalSwaptionExpiryStrikeVolatilities) obj;
return JodaBeanUtils.equal(convention, other.convention) &&
JodaBeanUtils.equal(valuationDateTime, other.valuationDateTime) &&
JodaBeanUtils.equal(surface, other.surface);
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = hash * 31 + JodaBeanUtils.hashCode(convention);
hash = hash * 31 + JodaBeanUtils.hashCode(valuationDateTime);
hash = hash * 31 + JodaBeanUtils.hashCode(surface);
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(128);
buf.append("NormalSwaptionExpiryStrikeVolatilities{");
buf.append("convention").append('=').append(JodaBeanUtils.toString(convention)).append(',').append(' ');
buf.append("valuationDateTime").append('=').append(JodaBeanUtils.toString(valuationDateTime)).append(',').append(' ');
buf.append("surface").append('=').append(JodaBeanUtils.toString(surface));
buf.append('}');
return buf.toString();
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code NormalSwaptionExpiryStrikeVolatilities}.
*/
public static final class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code convention} property.
*/
private final MetaProperty<FixedFloatSwapConvention> convention = DirectMetaProperty.ofImmutable(
this, "convention", NormalSwaptionExpiryStrikeVolatilities.class, FixedFloatSwapConvention.class);
/**
* The meta-property for the {@code valuationDateTime} property.
*/
private final MetaProperty<ZonedDateTime> valuationDateTime = DirectMetaProperty.ofImmutable(
this, "valuationDateTime", NormalSwaptionExpiryStrikeVolatilities.class, ZonedDateTime.class);
/**
* The meta-property for the {@code surface} property.
*/
private final MetaProperty<Surface> surface = DirectMetaProperty.ofImmutable(
this, "surface", NormalSwaptionExpiryStrikeVolatilities.class, Surface.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"convention",
"valuationDateTime",
"surface");
/**
* Restricted constructor.
*/
private Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case 2039569265: // convention
return convention;
case -949589828: // valuationDateTime
return valuationDateTime;
case -1853231955: // surface
return surface;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends NormalSwaptionExpiryStrikeVolatilities> builder() {
return new NormalSwaptionExpiryStrikeVolatilities.Builder();
}
@Override
public Class<? extends NormalSwaptionExpiryStrikeVolatilities> beanType() {
return NormalSwaptionExpiryStrikeVolatilities.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code convention} property.
* @return the meta-property, not null
*/
public MetaProperty<FixedFloatSwapConvention> convention() {
return convention;
}
/**
* The meta-property for the {@code valuationDateTime} property.
* @return the meta-property, not null
*/
public MetaProperty<ZonedDateTime> valuationDateTime() {
return valuationDateTime;
}
/**
* The meta-property for the {@code surface} property.
* @return the meta-property, not null
*/
public MetaProperty<Surface> surface() {
return surface;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case 2039569265: // convention
return ((NormalSwaptionExpiryStrikeVolatilities) bean).getConvention();
case -949589828: // valuationDateTime
return ((NormalSwaptionExpiryStrikeVolatilities) bean).getValuationDateTime();
case -1853231955: // surface
return ((NormalSwaptionExpiryStrikeVolatilities) bean).getSurface();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
metaProperty(propertyName);
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
}
}
//-----------------------------------------------------------------------
/**
* The bean-builder for {@code NormalSwaptionExpiryStrikeVolatilities}.
*/
private static final class Builder extends DirectPrivateBeanBuilder<NormalSwaptionExpiryStrikeVolatilities> {
private FixedFloatSwapConvention convention;
private ZonedDateTime valuationDateTime;
private Surface surface;
/**
* Restricted constructor.
*/
private Builder() {
}
//-----------------------------------------------------------------------
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case 2039569265: // convention
return convention;
case -949589828: // valuationDateTime
return valuationDateTime;
case -1853231955: // surface
return surface;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
}
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
case 2039569265: // convention
this.convention = (FixedFloatSwapConvention) newValue;
break;
case -949589828: // valuationDateTime
this.valuationDateTime = (ZonedDateTime) newValue;
break;
case -1853231955: // surface
this.surface = (Surface) newValue;
break;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
return this;
}
@Override
public NormalSwaptionExpiryStrikeVolatilities build() {
return new NormalSwaptionExpiryStrikeVolatilities(
convention,
valuationDateTime,
surface);
}
//-----------------------------------------------------------------------
@Override
public String toString() {
StringBuilder buf = new StringBuilder(128);
buf.append("NormalSwaptionExpiryStrikeVolatilities.Builder{");
buf.append("convention").append('=').append(JodaBeanUtils.toString(convention)).append(',').append(' ');
buf.append("valuationDateTime").append('=').append(JodaBeanUtils.toString(valuationDateTime)).append(',').append(' ');
buf.append("surface").append('=').append(JodaBeanUtils.toString(surface));
buf.append('}');
return buf.toString();
}
}
//-------------------------- AUTOGENERATED END --------------------------
}
| OpenGamma/Strata | modules/pricer/src/main/java/com/opengamma/strata/pricer/swaption/NormalSwaptionExpiryStrikeVolatilities.java | Java | apache-2.0 | 19,774 |
// Start of user code Copyright
/*******************************************************************************
* Copyright (c) 2012 IBM Corporation and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
*
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
*
* Russell Boykin - initial API and implementation
* Alberto Giammaria - initial API and implementation
* Chris Peters - initial API and implementation
* Gianluca Bernardini - initial API and implementation
* Sam Padgett - initial API and implementation
* Michael Fiedler - adapted for OSLC4J
* Jad El-khoury - initial implementation of code generator (https://bugs.eclipse.org/bugs/show_bug.cgi?id=422448)
*
* This file is generated by org.eclipse.lyo.oslc4j.codegenerator
*******************************************************************************/
// End of user code
package eu.scott.warehouse.domains.pddl;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;
import org.eclipse.lyo.oslc4j.core.annotation.OslcAllowedValue;
import org.eclipse.lyo.oslc4j.core.annotation.OslcDescription;
import org.eclipse.lyo.oslc4j.core.annotation.OslcMemberProperty;
import org.eclipse.lyo.oslc4j.core.annotation.OslcName;
import org.eclipse.lyo.oslc4j.core.annotation.OslcNamespace;
import org.eclipse.lyo.oslc4j.core.annotation.OslcOccurs;
import org.eclipse.lyo.oslc4j.core.annotation.OslcPropertyDefinition;
import org.eclipse.lyo.oslc4j.core.annotation.OslcRange;
import org.eclipse.lyo.oslc4j.core.annotation.OslcReadOnly;
import org.eclipse.lyo.oslc4j.core.annotation.OslcRepresentation;
import org.eclipse.lyo.oslc4j.core.annotation.OslcResourceShape;
import org.eclipse.lyo.oslc4j.core.annotation.OslcTitle;
import org.eclipse.lyo.oslc4j.core.annotation.OslcValueType;
import org.eclipse.lyo.oslc4j.core.model.AbstractResource;
import org.eclipse.lyo.oslc4j.core.model.Link;
import org.eclipse.lyo.oslc4j.core.model.Occurs;
import org.eclipse.lyo.oslc4j.core.model.OslcConstants;
import org.eclipse.lyo.oslc4j.core.model.Representation;
import org.eclipse.lyo.oslc4j.core.model.ValueType;
import eu.scott.warehouse.domains.pddl.PddlDomainConstants;
import eu.scott.warehouse.domains.pddl.PddlDomainConstants;
import eu.scott.warehouse.domains.pddl.IAction;
// Start of user code imports
// End of user code
@OslcNamespace(PddlDomainConstants.STEP_NAMESPACE)
@OslcName(PddlDomainConstants.STEP_LOCALNAME)
@OslcResourceShape(title = "Step Resource Shape", describes = PddlDomainConstants.STEP_TYPE)
public interface IStep
{
public void addAdding(final Link adding );
public void addDeleting(final Link deleting );
public void addUpdating(final Link updating );
@OslcName("action")
@OslcPropertyDefinition(PddlDomainConstants.SCOTT_PDDL_2_1_SUBSET_SPEC_NAMSPACE + "action")
@OslcDescription("Action of the plan step.")
@OslcOccurs(Occurs.ExactlyOne)
@OslcValueType(ValueType.Resource)
@OslcRange({PddlDomainConstants.ACTION_TYPE})
@OslcReadOnly(false)
public Link getAction();
@OslcName("adding")
@OslcPropertyDefinition(PddlDomainConstants.SCOTT_PDDL_2_1_SUBSET_SPEC_NAMSPACE + "adding")
@OslcDescription("Step additions.")
@OslcOccurs(Occurs.ZeroOrMany)
@OslcValueType(ValueType.Resource)
@OslcReadOnly(false)
public Set<Link> getAdding();
@OslcName("deleting")
@OslcPropertyDefinition(PddlDomainConstants.SCOTT_PDDL_2_1_SUBSET_SPEC_NAMSPACE + "deleting")
@OslcDescription("Step deletions.")
@OslcOccurs(Occurs.ZeroOrMany)
@OslcValueType(ValueType.Resource)
@OslcReadOnly(false)
public Set<Link> getDeleting();
@OslcName("updating")
@OslcPropertyDefinition(PddlDomainConstants.SCOTT_PDDL_2_1_SUBSET_SPEC_NAMSPACE + "updating")
@OslcDescription("Step updates.")
@OslcOccurs(Occurs.ZeroOrMany)
@OslcValueType(ValueType.Resource)
@OslcReadOnly(false)
public Set<Link> getUpdating();
@OslcName("order")
@OslcPropertyDefinition(PddlDomainConstants.SCOTT_PDDL_2_1_SUBSET_SPEC_NAMSPACE + "order")
@OslcDescription("Parameter order.")
@OslcOccurs(Occurs.ExactlyOne)
@OslcValueType(ValueType.Integer)
@OslcReadOnly(false)
public Integer getOrder();
public void setAction(final Link action );
public void setAdding(final Set<Link> adding );
public void setDeleting(final Set<Link> deleting );
public void setUpdating(final Set<Link> updating );
public void setOrder(final Integer order );
}
| EricssonResearch/scott-eu | lyo-services/domain-pddl/src/main/java/eu/scott/warehouse/domains/pddl/IStep.java | Java | apache-2.0 | 5,144 |
package com.nes.processor;
import com.nes.NesAbstractTst;
import org.junit.Test;
/**
*
* @author Dmitry
*/
public class SbcTest extends NesAbstractTst {
@Test
public void testSbc() {
String[] lines;
lines = new String[]{
"clc",
"lda #$50",
"sbc #$5"
};
testAlu(lines, 0x4a, 0x00, 0, 0xfd, 0x606, true, false, false, false);
lines = new String[]{
"sec",
"lda #$50",
"sbc #$5"
};
testAlu(lines, 0x4b, 0x00, 0, 0xfd, 0x606, true, false, false, false);
lines = new String[]{
"sec",
"lda #$5",
"sbc #$55"
};
testAlu(lines, 0xb0, 0x00, 0, 0xfd, 0x606, false, false, true, false);
lines = new String[]{
"clc",
"lda #$80",
"sbc #$20"
};
testAlu(lines, 0x5f, 0x00, 0, 0xfd, 0x606, true, false, false, true);
lines = new String[]{
"clc",
"lda #$20",
"sbc #$80"
};
testAlu(lines, 0x9f, 0x00, 0, 0xfd, 0x606, false, false, true, true);
lines = new String[]{
"sec",
"lda #$20",
"sbc #$80"
};
testAlu(lines, 0xa0, 0x00, 0, 0xfd, 0x606, false, false, true, true);
}
}
| Otaka/mydifferentprojects | nes-java/test/com/nes/processor/SbcTest.java | Java | apache-2.0 | 1,413 |
/*
* Copyright © 2015 Lable (info@lable.nl)
*
* 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.lable.oss.bitsandbytes;
/**
* Create bit or byte masks, where respectively each bit or the bytes 0x0 and 0x1 represent the mask, from a pattern
* specification.
*/
public class BitMask {
BitMask() {
// Static utility class.
}
/**
* Convert a pattern description into a byte array where each byte (not bit) is either a 0 or a 1. This format is
* used by the {@code FuzzyRowFilter} in HBase.
* <p>
* Through the pattern passed as argument to this method you specify the alternating groups of ones and zeroes,
* so {@code byteMask(2, 4, 1)} returns a byte array containing {@code 0x00 0x00 0x01 0x01 0x01 0x01 0x00}.
* <p>
* To start the mask with ones, pass 0 as the first number in the pattern.
*
* @param pattern The mask pattern, alternately specifying the length of the groups of zeroes and ones.
* @return A byte array.
*/
public static byte[] byteMask(int... pattern) {
if (pattern == null) {
return new byte[0];
}
int length = 0;
for (int blockLength : pattern) {
length += blockLength;
}
byte[] mask = new byte[length];
int blockOffset = 0;
boolean writeZero = true;
for (int blockLength : pattern) {
for (int i = 0; i < blockLength; i++) {
mask[blockOffset + i] = (byte) (writeZero ? 0x00 : 0x01);
}
blockOffset += blockLength;
writeZero = !writeZero;
}
return mask;
}
/**
* Convert a pattern description into a byte array where the pattern is represented by its bits.
* <p>
* Through the pattern passed as argument to this method you specify the alternating groups of ones and zeroes,
* so {@code byteMask(8, 8)} returns a byte arrays containing {@code 0x00 0xFF}. If the pattern is not cleanly
* divisible by eight, the bitmask returned will be padded with zeroes. So {@code byteMask(0, 4)} returns
* {@code 0x0F}.
* <p>
* To start the mask with ones, pass 0 as the first number in the pattern.
*
* @param pattern The mask pattern, alternately specifying the length of the groups of zeroes and ones.
* @return A byte array.
*/
public static byte[] bitMask(int... pattern) {
if (pattern == null) {
return new byte[0];
}
int length = 0;
for (int blockLength : pattern) {
length += blockLength;
}
boolean cleanlyDivisible = length % 8 == 0;
// Start at an offset when the pattern is not exactly divisible by 8.
int blockOffset = cleanlyDivisible ? 0 : 8 - (length % 8);
byte[] mask = new byte[(length / 8) + (cleanlyDivisible ? 0 : 1)];
boolean writeZero = true;
for (int blockLength : pattern) {
if (!writeZero) {
for (int i = 0; i < blockLength; i++) {
int bytePosition = (blockOffset + i) / 8;
int bitPosition = (blockOffset + i) % 8;
mask[bytePosition] = (byte) (mask[bytePosition] ^ 1 << (7 - bitPosition));
}
}
blockOffset += blockLength;
writeZero = !writeZero;
}
return mask;
}
}
| LableOrg/java-bitsandbytes | src/main/java/org/lable/oss/bitsandbytes/BitMask.java | Java | apache-2.0 | 3,928 |
/*******************************************************************************
* Copyright [2017] [Quirino Brizi (quirino.brizi@gmail.com)]
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
'use strict'
module.exports = {
handleError: function(eventEmitter, err, req, res) {
console.error("received error %j", err);
var statusCode = (!err.statusCode || err.statusCode == 0) ? 500 : err.statusCode,
message = !err.error ? !err.body ? { message: "Internal Server Error" } : err.body : err.error;
eventEmitter.emit('event', {message: message, payload: err});
res.status(statusCode).send(message);
},
handleSuccess: function(eventEmitter, res, message, payload) {
eventEmitter.emit('event', {message: message, payload: payload});
res.status(200).json(payload);
},
handleApiError: function(err, req, res) {
console.error("received error: ", err.stack);
var statusCode = (!err.statusCode || err.statusCode == 0) ? 500 : err.statusCode,
message = !err.error ? !err.body ? { message: "Internal Server Error" } : err.body : err.error;
res.status(statusCode).send(message);
},
};
| quirinobrizi/buckle | src/interfaces/api/api-helper.js | JavaScript | apache-2.0 | 1,728 |
/*
* Copyright 2017 Courtanet
*
* 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.doov.core.dsl;
import io.doov.core.FieldId;
import io.doov.core.dsl.impl.DefaultCondition;
import io.doov.core.dsl.lang.Readable;
/**
* Interface for all field types.
*
* Generic type parameter {@link T} defines the type of the field.
*/
public interface DslField<T> extends Readable {
FieldId id();
/**
* Returns a new default condition that will use this as a field.
*
* @return the default condition
*/
DefaultCondition<T> getDefaultCondition();
}
| lesfurets/dOOv | core/src/main/java/io/doov/core/dsl/DslField.java | Java | apache-2.0 | 1,096 |
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.scana.okgradle.internal.dsl.parser.elements;
import me.scana.okgradle.internal.dsl.api.ext.ReferenceTo;
import me.scana.okgradle.internal.dsl.parser.GradleReferenceInjection;
import me.scana.okgradle.internal.dsl.parser.elements.GradleDslElement;
import me.scana.okgradle.internal.dsl.parser.elements.GradleDslSettableExpression;
import me.scana.okgradle.internal.dsl.parser.elements.GradleNameElement;
import com.google.common.collect.ImmutableList;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import static me.scana.okgradle.internal.dsl.api.ext.GradlePropertyModel.iStr;
/**
* Represents a literal element.
*/
public final class GradleDslLiteral extends GradleDslSettableExpression {
public GradleDslLiteral(@NotNull me.scana.okgradle.internal.dsl.parser.elements.GradleDslElement parent, @NotNull GradleNameElement name) {
super(parent, null, name, null);
// Will be set in the call to #setValue
myIsReference = false;
}
public GradleDslLiteral(@NotNull me.scana.okgradle.internal.dsl.parser.elements.GradleDslElement parent,
@NotNull PsiElement psiElement,
@NotNull GradleNameElement name,
@NotNull PsiElement literal,
boolean isReference) {
super(parent, psiElement, name, literal);
myIsReference = isReference;
}
@Override
@Nullable
public Object produceValue() {
PsiElement element = getCurrentElement();
if (element == null) {
return null;
}
return ApplicationManager.getApplication()
.runReadAction((Computable<Object>)() -> getDslFile().getParser().extractValue(this, element, true));
}
@Override
@Nullable
public Object produceUnresolvedValue() {
PsiElement element = getCurrentElement();
if (element == null) {
return null;
}
return ApplicationManager.getApplication()
.runReadAction((Computable<Object>)() -> getDslFile().getParser().extractValue(this, element, false));
}
@Override
public void setValue(@NotNull Object value) {
checkForValidValue(value);
PsiElement element =
ApplicationManager.getApplication().runReadAction((Computable<PsiElement>)() -> {
PsiElement psiElement = getDslFile().getParser().convertToPsiElement(value);
getDslFile().getParser().setUpForNewValue(this, psiElement);
return psiElement;
});
setUnsavedValue(element);
valueChanged();
}
@Nullable
@Override
public Object produceRawValue() {
PsiElement currentElement = getCurrentElement();
if (currentElement == null) {
return null;
}
return ApplicationManager.getApplication()
.runReadAction((Computable<Object>)() -> {
boolean shouldInterpolate = getDslFile().getParser().shouldInterpolate(this);
Object val = getDslFile().getParser().extractValue(this, currentElement, false);
if (val instanceof String && shouldInterpolate) {
return iStr((String)val);
}
return val;
});
}
@NotNull
@Override
public GradleDslLiteral copy() {
assert myParent != null;
GradleDslLiteral literal = new GradleDslLiteral(myParent, GradleNameElement.copy(myName));
Object v = getRawValue();
if (v != null) {
literal.setValue(isReference() ? new ReferenceTo((String)v) : v);
}
return literal;
}
@Override
public String toString() {
Object value = getValue();
return value != null ? value.toString() : super.toString();
}
@Override
@NotNull
public Collection<GradleDslElement> getChildren() {
return ImmutableList.of();
}
@Override
@Nullable
public PsiElement create() {
return getDslFile().getWriter().createDslLiteral(this);
}
@Override
public void delete() {
getDslFile().getWriter().deleteDslLiteral(this);
}
@Override
protected void apply() {
getDslFile().getWriter().applyDslLiteral(this);
}
@Nullable
public GradleReferenceInjection getReferenceInjection() {
return myDependencies.isEmpty() ? null : myDependencies.get(0);
}
@Override
@Nullable
public String getReferenceText() {
if (!myIsReference) {
return null;
}
PsiElement element = getCurrentElement();
return element != null ? getPsiText(element) : null;
}
@Override
public void reset() {
super.reset();
ApplicationManager.getApplication().runReadAction(() -> getDslFile().getParser().setUpForNewValue(this, getCurrentElement()));
}
}
| scana/ok-gradle | plugin/src/main/java/me/scana/okgradle/internal/dsl/parser/elements/GradleDslLiteral.java | Java | apache-2.0 | 5,565 |
package org.apache.sftp.protocol.packetdata;
import org.apache.sftp.protocol.Response;
public interface ExtendedImplementation<T extends Extended<T, S>, S extends Response<S>>
extends Implementation<T> {
public String getExtendedRequest();
public Implementation<S> getExtendedReplyImplementation();
}
| lucastheisen/mina-sshd | sshd-fs/src/main/java/org/apache/sftp/protocol/packetdata/ExtendedImplementation.java | Java | apache-2.0 | 338 |
package com.myntra.coachmarks.builder;
import android.graphics.Rect;
import android.os.Parcelable;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class CoachMarkPixelInfo implements Parcelable {
public static CoachMarkPixelInfo.Builder create() {
return new AutoValue_CoachMarkPixelInfo.Builder()
.setImageWidthInPixels(0)
.setImageHeightInPixels(0)
.setMarginRectInPixels(new Rect(0, 0, 0, 0))
.setPopUpWidthInPixelsWithOffset(0)
.setPopUpHeightInPixelsWithOffset(0)
.setPopUpWidthInPixels(0)
.setPopUpHeightInPixels(0)
.setScreenWidthInPixels(0)
.setScreenHeightInPixels(0)
.setNotchDimenInPixels(0)
.setActionBarHeightPixels(0)
.setFooterHeightPixels(0)
.setMarginOffsetForNotchInPixels(0)
.setWidthHeightOffsetForCoachMarkPopUp(0);
}
public abstract int getImageWidthInPixels();
public abstract int getImageHeightInPixels();
public abstract Rect getMarginRectInPixels();
public abstract int getPopUpWidthInPixelsWithOffset();
public abstract int getPopUpHeightInPixelsWithOffset();
public abstract int getPopUpWidthInPixels();
public abstract int getPopUpHeightInPixels();
public abstract int getScreenWidthInPixels();
public abstract int getScreenHeightInPixels();
public abstract int getNotchDimenInPixels();
public abstract int getActionBarHeightPixels();
public abstract int getFooterHeightPixels();
public abstract int getMarginOffsetForNotchInPixels();
public abstract int getWidthHeightOffsetForCoachMarkPopUp();
@AutoValue.Builder
public static abstract class Builder {
public abstract Builder setImageWidthInPixels(int imageWidthInPixels);
public abstract Builder setImageHeightInPixels(int imageHeightInPixels);
public abstract Builder setMarginRectInPixels(Rect coachMarkMarginRectInPixels);
public abstract Builder setPopUpWidthInPixelsWithOffset(int coachMarkPopUpWidthInPixelsWithOffset);
public abstract Builder setPopUpHeightInPixelsWithOffset(int coachMarkPopUpHeightInPixelsWithOffset);
public abstract Builder setPopUpWidthInPixels(int coachMarkPopUpWidthInPixels);
public abstract Builder setPopUpHeightInPixels(int coachMarkPopUpHeightInPixels);
public abstract Builder setScreenWidthInPixels(int screenWidthInPixels);
public abstract Builder setScreenHeightInPixels(int screenHeightInPixels);
public abstract Builder setNotchDimenInPixels(int notchDimenInPixels);
public abstract Builder setActionBarHeightPixels(int actionBarHeightPixels);
public abstract Builder setFooterHeightPixels(int footerHeightPixels);
public abstract Builder setMarginOffsetForNotchInPixels(int marginOffsetForNotchInPixels);
public abstract Builder setWidthHeightOffsetForCoachMarkPopUp(int widthHeightOffsetForCoachMarkPopUp);
public abstract CoachMarkPixelInfo build();
}
}
| myntra/CoachMarks | coachmarks/src/main/java/com/myntra/coachmarks/builder/CoachMarkPixelInfo.java | Java | apache-2.0 | 3,163 |
/* eslint-disable */
var webpack = require('webpack');
var path = require('path');
var nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './index.js',
output: {
path: path.join(__dirname, '..', '..', 'build'),
filename: 'app.js'
},
resolve: {
modulesDirectories: ['shared', 'node_modules'],
extensions: ['', '.js', '.jsx', '.json']
},
externals: [nodeExternals()],
plugins: [
new webpack.BannerPlugin('require("source-map-support").install();', {
raw: true,
entryOnly: false
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
})
],
target: 'node',
node: { // webpack strangely doesn't do this when you set `target: 'node'`
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false,
setImmediate: false
},
devtool: 'sourcemap',
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['react', 'es2015', 'stage-0'],
plugins: ['transform-decorators-legacy', ['react-transform', {
transforms: [
{
transform: 'react-transform-catch-errors',
imports: ['react', 'redbox-react']
}
]
}]]
}
},
{
test: /\.(css|less)$/,
loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!less'
},
{
test: /\.(woff|woff2|ttf|eot|svg|png|jpg|jpeg|gif)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url'
}
]
}
};
| SmallShrimp/node-tpl | webpack/dev/webpack.node.config.js | JavaScript | apache-2.0 | 1,756 |
# # Use this setup block to configure all options available in SimpleForm.
# SimpleForm.setup do |config|
# # Wrappers are used by the form builder to generate a
# # complete input. You can remove any component from the
# # wrapper, change the order or even add your own to the
# # stack. The options given below are used to wrap the
# # whole input.
# config.wrappers :default, class: :input,
# hint_class: :field_with_hint, error_class: :field_with_errors do |b|
# ## Extensions enabled by default
# # Any of these extensions can be disabled for a
# # given input by passing: `f.input EXTENSION_NAME => false`.
# # You can make any of these extensions optional by
# # renaming `b.use` to `b.optional`.
#
# # Determines whether to use HTML5 (:email, :url, ...)
# # and required attributes
# b.use :html5
#
# # Calculates placeholders automatically from I18n
# # You can also pass a string as f.input placeholder: "Placeholder"
# b.use :placeholder
#
# ## Optional extensions
# # They are disabled unless you pass `f.input EXTENSION_NAME => true`
# # to the input. If so, they will retrieve the values from the model
# # if any exists. If you want to enable any of those
# # extensions by default, you can change `b.optional` to `b.use`.
#
# # Calculates maxlength from length validations for string inputs
# b.optional :maxlength
#
# # Calculates pattern from format validations for string inputs
# b.optional :pattern
#
# # Calculates min and max from length validations for numeric inputs
# b.optional :min_max
#
# # Calculates readonly automatically from readonly attributes
# b.optional :readonly
#
# ## Inputs
# b.use :label_input
# b.use :hint, wrap_with: { tag: :span, class: :hint }
# b.use :error, wrap_with: { tag: :span, class: :error }
#
# ## full_messages_for
# # If you want to display the full error message for the attribute, you can
# # use the component :full_error, like:
# #
# # b.use :full_error, wrap_with: { tag: :span, class: :error }
# end
#
# # The default wrapper to be used by the FormBuilder.
# config.default_wrapper = :default
#
# # Define the way to render check boxes / radio buttons with labels.
# # Defaults to :nested for bootstrap config.
# # inline: input + label
# # nested: label > input
# config.boolean_style = :nested
#
# # Default class for buttons
# config.button_class = 'btn'
#
# # Method used to tidy up errors. Specify any Rails Array method.
# # :first lists the first message for each field.
# # Use :to_sentence to list all errors for each field.
# # config.error_method = :first
#
# # Default tag used for error notification helper.
# config.error_notification_tag = :div
#
# # CSS class to add for error notification helper.
# config.error_notification_class = 'error_notification'
#
# # ID to add for error notification helper.
# # config.error_notification_id = nil
#
# # Series of attempts to detect a default label method for collection.
# # config.collection_label_methods = [ :to_label, :name, :title, :to_s ]
#
# # Series of attempts to detect a default value method for collection.
# # config.collection_value_methods = [ :id, :to_s ]
#
# # You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
# # config.collection_wrapper_tag = nil
#
# # You can define the class to use on all collection wrappers. Defaulting to none.
# # config.collection_wrapper_class = nil
#
# # You can wrap each item in a collection of radio/check boxes with a tag,
# # defaulting to :span. Please note that when using :boolean_style = :nested,
# # SimpleForm will force this option to be a label.
# # config.item_wrapper_tag = :span
#
# # You can define a class to use in all item wrappers. Defaulting to none.
# # config.item_wrapper_class = nil
#
# # How the label text should be generated altogether with the required text.
# # config.label_text = lambda { |label, required, explicit_label| "#{required} #{label}" }
#
# # You can define the class to use on all labels. Default is nil.
# # config.label_class = nil
#
# # You can define the default class to be used on forms. Can be overriden
# # with `html: { :class }`. Defaulting to none.
# # config.default_form_class = nil
#
# # You can define which elements should obtain additional classes
# # config.generate_additional_classes_for = [:wrapper, :label, :input]
#
# # Whether attributes are required by default (or not). Default is true.
# # config.required_by_default = true
#
# # Tell browsers whether to use the native HTML5 validations (novalidate form option).
# # These validations are enabled in SimpleForm's internal config but disabled by default
# # in this configuration, which is recommended due to some quirks from different browsers.
# # To stop SimpleForm from generating the novalidate option, enabling the HTML5 validations,
# # change this configuration to true.
# config.browser_validations = false
#
# # Collection of methods to detect if a file type was given.
# # config.file_methods = [ :mounted_as, :file?, :public_filename ]
#
# # Custom mappings for input types. This should be a hash containing a regexp
# # to match as key, and the input type that will be used when the field name
# # matches the regexp as value.
# # config.input_mappings = { /count/ => :integer }
#
# # Custom wrappers for input types. This should be a hash containing an input
# # type as key and the wrapper that will be used for all inputs with specified type.
# # config.wrapper_mappings = { string: :prepend }
#
# # Namespaces where SimpleForm should look for custom input classes that
# # override default inputs.
# # config.custom_inputs_namespaces << "CustomInputs"
#
# # Default priority for time_zone inputs.
# # config.time_zone_priority = nil
#
# # Default priority for country inputs.
# # config.country_priority = nil
#
# # When false, do not use translations for labels.
# # config.translate_labels = true
#
# # Automatically discover new inputs in Rails' autoload path.
# # config.inputs_discovery = true
#
# # Cache SimpleForm inputs discovery
# # config.cache_discovery = !Rails.env.development?
#
# # Default class for inputs
# # config.input_class = nil
#
# # Define the default class of the input wrapper of the boolean input.
# config.boolean_label_class = 'checkbox'
#
# # Defines if the default input wrapper class should be included in radio
# # collection wrappers.
# # config.include_default_input_wrapper_class = true
#
# # Defines which i18n scope will be used in Simple Form.
# # config.i18n_scope = 'simple_form'
# end
| QutBioacoustics/baw-server | config/initializers/simple_form.rb | Ruby | apache-2.0 | 6,796 |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.reader.gtfs;
import com.graphhopper.reader.ReaderRelation;
import com.graphhopper.reader.ReaderWay;
import com.graphhopper.routing.profiles.EncodedValue;
import com.graphhopper.routing.profiles.IntEncodedValue;
import com.graphhopper.routing.profiles.SimpleIntEncodedValue;
import com.graphhopper.routing.util.AbstractFlagEncoder;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.storage.IntsRef;
import com.graphhopper.util.EdgeIteratorState;
import java.util.List;
public class PtFlagEncoder extends AbstractFlagEncoder {
private IntEncodedValue timeEnc;
private IntEncodedValue transfersEnc;
private IntEncodedValue validityIdEnc;
private IntEncodedValue typeEnc;
public PtFlagEncoder() {
super(0, 1, 0);
}
@Override
public void createEncodedValues(List<EncodedValue> list, String prefix, int index) {
// do we really need 2 bits for pt.access?
super.createEncodedValues(list, prefix, index);
list.add(validityIdEnc = new SimpleIntEncodedValue(prefix + "validity_id", 20, false));
list.add(transfersEnc = new SimpleIntEncodedValue(prefix + "transfers", 1, false));
list.add(typeEnc = new SimpleIntEncodedValue(prefix + "type", 4, false));
list.add(timeEnc = new SimpleIntEncodedValue(prefix + "time", 17, false));
}
@Override
public long handleRelationTags(long oldRelationFlags, ReaderRelation relation) {
return oldRelationFlags;
}
@Override
public EncodingManager.Access getAccess(ReaderWay way) {
return EncodingManager.Access.CAN_SKIP;
}
@Override
public IntsRef handleWayTags(IntsRef edgeFlags, ReaderWay way, EncodingManager.Access access, long relationFlags) {
return edgeFlags;
}
public IntEncodedValue getTimeEnc() {
return timeEnc;
}
public IntEncodedValue getTransfersEnc() {
return transfersEnc;
}
public IntEncodedValue getValidityIdEnc() {
return validityIdEnc;
}
GtfsStorage.EdgeType getEdgeType(EdgeIteratorState edge) {
return GtfsStorage.EdgeType.values()[edge.get(typeEnc)];
}
void setEdgeType(EdgeIteratorState edge, GtfsStorage.EdgeType edgeType) {
edge.set(typeEnc, edgeType.ordinal());
}
public String toString() {
return "pt";
}
@Override
public int getVersion() {
return 1;
}
}
| komoot/graphhopper | reader-gtfs/src/main/java/com/graphhopper/reader/gtfs/PtFlagEncoder.java | Java | apache-2.0 | 3,249 |
// <copyright file="BingMainPageElementMap.cs" company="Automate The Planet Ltd.">
// Copyright 2021 Automate The Planet 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.
// </copyright>
// <author>Anton Angelov</author>
// <site>http://automatetheplanet.com/</site>
using OpenQA.Selenium;
namespace AdvancedPageObjectPattern.Pages.BingMainPage
{
public class BingMainPageElementMap : BasePageElementMap
{
public IWebElement SearchBox
{
get
{
return Browser.FindElement(By.Id("sb_form_q"));
}
}
public IWebElement GoButton
{
get
{
return Browser.FindElement(By.XPath("//label[@for='sb_form_go']"));
}
}
public IWebElement ResultsCountDiv
{
get
{
return Browser.FindElement(By.Id("b_tween"));
}
}
}
} | angelovstanton/AutomateThePlanet | dotnet/Design-Architecture-Series/AdvancedPageObjectPattern/Pages/BingMainPage/BingMainPageElementMap.cs | C# | apache-2.0 | 1,443 |
package org.siggd.actor;
import org.siggd.ContactHandler;
import org.siggd.Convert;
import org.siggd.Game;
import org.siggd.Level;
import org.siggd.StableContact;
import org.siggd.Timer;
import org.siggd.view.BodySprite;
import org.siggd.view.CompositeDrawable;
import org.siggd.view.Drawable;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.RayCastCallback;
public class Cannon extends Actor implements RayCastCallback {
private class HitScanDrawable implements Drawable {
@Override
public void drawSprite(SpriteBatch batch) {
// no sprite to draw
}
@Override
public void drawElse(ShapeRenderer shapeRender) {
// draw laser!
if(targetAcquired) {
shapeRender.begin(ShapeType.Line);
shapeRender.setColor(1, 0, 0, 1);
shapeRender.line(startOfLaser.x, startOfLaser.y, mLaserEnd.x, mLaserEnd.y);
shapeRender.end();
}
}
@Override
public void drawDebug(Camera camera) {
// use?
}
}
private String mTex;
private Timer mSpawnTimer;
private Fixture mSensorBall;
float detectRadius = 6f;
Blob rememberBlob;
int initialAngle;
int shotsFired = 0;
boolean immediateRefire = false;
long previousID;
boolean targetAcquired = false;
//private ShapeRenderer mShapeRenderer;
private Vector2 mLaserEnd = new Vector2();
private final float mLaserLength = 1000;
Vector2 startOfLaser = new Vector2();
boolean checkingLOS = false;
public Cannon(Level level, long id) {
super(level, id);
mName = "lightbulb";
mTex = "data/" + Game.get().getBodyEditorLoader().getImagePath(mName);
Vector2 origin = new Vector2();
mBody = makeBody(mName, 128, BodyType.KinematicBody, origin, true);
((CompositeDrawable) mDrawable).mDrawables.add(new BodySprite(mBody, origin, mTex));
CircleShape circle = new CircleShape();
circle.setPosition(new Vector2(0, 0));
circle.setRadius(detectRadius);
FixtureDef fd = new FixtureDef();
fd.shape = circle;
fd.isSensor = true;
mSensorBall = mBody.createFixture(fd);
mSpawnTimer = new Timer();
mSpawnTimer.setTimer(Convert.getInt(this.getProp("Rate")));
mSpawnTimer.unpause();
this.setProp("Rate", 120);
this.setProp("Exit Velocity", 25);
this.setProp("Layer", 4);
// 0 - Explode Ball 1 - Implode Ball
this.setProp("Ammo", 0);
this.setProp("explodeTime", 180);
this.setProp("Alternate", 0);
((CompositeDrawable) mDrawable).mDrawables.add(new BodySprite(mBody, origin, mTex));
((CompositeDrawable) mDrawable).mDrawables.add(new HitScanDrawable());
}
@Override
public void loadResources() {
AssetManager man = Game.get().getAssetManager();
man.load(mTex, Texture.class);
}
public void update() {
// Hitscan Stuff
float daAngle = (Convert.getDegrees(mBody.getAngle()) - 90);
if (daAngle < 0)
daAngle += 360;
if (daAngle > 360)
daAngle -= 360;
Vector2 finalStart = new Vector2(mBody.getPosition().cpy().x + 0.585f, mBody.getPosition()
.cpy().y);
finalStart.sub(mBody.getPosition().cpy());
finalStart.rotate(Convert.getDegrees(mBody.getAngle()));
Vector2 start = new Vector2(mBody.getPosition().cpy().x, mBody.getPosition().cpy().y);
start.add(finalStart);
startOfLaser = start;
Vector2 end = new Vector2(0, mLaserLength).rotate(daAngle);
mLaserEnd = end.add(start);
setProp("Actor Hit", -1);
mLevel.getWorld().rayCast(this, start, mLaserEnd.cpy());
Iterable<StableContact> contacts = Game.get().getLevel().getContactHandler()
.getContacts(this);
Iterable<Actor> actors = ContactHandler.getActors(contacts);
boolean enemySeen = false;
super.update();
for (Actor a : actors) {
if (a instanceof Blob) {
checkingLOS = true;
Blob seeCheck = (Blob) a;
Vector2 seeCheckPos = new Vector2(seeCheck.getX(), seeCheck.getY());
mLevel.getWorld().rayCast(this, mBody.getPosition(), seeCheckPos);
checkingLOS = false;
if(!targetAcquired) {
continue;
}
if (rememberBlob != null) {
Vector2 rememberDist = new Vector2( rememberBlob.getX(), rememberBlob.getY() );
rememberDist.sub(mBody.getPosition());
float remDist = Math.abs(rememberDist.len());
if (remDist > detectRadius) {
rememberBlob = null;
}
}
if (rememberBlob == null) {
rememberBlob = (Blob) a;
}
enemySeen = true;
Blob blob = rememberBlob;
Vector2 blobPos = new Vector2(blob.getX(), blob.getY());
Vector2 blobCpy = blobPos.cpy();
blobCpy.sub(mBody.getPosition());
float blobDistance = blobCpy.len();
blobCpy.nor();
int desiredAngle;
int currentAngle = Convert.getInt(getProp("Angle"));
if (Convert.getFloat(blob.getProp("Velocity X")) > 0) {
desiredAngle = 2;
} else {
desiredAngle = -2;
}
if (blobPos.y > mBody.getPosition().y) {
desiredAngle += (int) (Math.acos(Convert.getDouble(blobCpy.x)) * (180 / Math.PI));
} else {
if (blobPos.x > mBody.getPosition().x) {
desiredAngle += (int) ((Math.asin(Convert.getDouble(blobCpy.y)) + 2 * Math.PI) * (180 / Math.PI));
} else {
desiredAngle += (int) ((Math.PI + (Math.abs(Math.asin(Convert
.getDouble(blobCpy.y))))) * (180 / Math.PI));
}
}
int totalRotation = desiredAngle - currentAngle;
int swapper = 1;
if (totalRotation > 180 || totalRotation < -180) {
swapper = -1;
}
float rotSpeed = 1.5f;
// System.out.println("Current: " + currentAngle);
// System.out.println(" Desired: " + desiredAngle);
float spawnCheckTotal = desiredAngle - currentAngle;
if (spawnCheckTotal > 360)
spawnCheckTotal -= 360;
if (spawnCheckTotal < -360)
spawnCheckTotal += 360;
// 3 is because of the aiming offset
if ((Math.abs(spawnCheckTotal) < 3 || Math.abs(spawnCheckTotal) > 357)
&& targetAcquired) {
if (immediateRefire && shotsFired >= 1) {
if (Game.get().getLevel().getActorById(previousID) != null) {
if (!Game.get().getLevel().getActorById(previousID).isActive()) {
spawnActor();
shotsFired++;
mSpawnTimer.reset();
}
}
} else {
mSpawnTimer.update();
if (mSpawnTimer.isTriggered() || shotsFired == 0) {
spawnActor();
shotsFired++;
mSpawnTimer.reset();
}
}
}
if (currentAngle == desiredAngle) {
mBody.setAngularVelocity(0f);
} else if (desiredAngle > currentAngle) {
mBody.setAngularVelocity(swapper * (rotSpeed));
} else if (desiredAngle < currentAngle) {
mBody.setAngularVelocity(swapper * (-rotSpeed));
}
}
}
if (!enemySeen) {
shotsFired = 0;
int currentAngle = Convert.getInt(getProp("Angle"));
int desiredAngle = initialAngle;
float totalRotation = desiredAngle - currentAngle;
int swapper = 1;
if (totalRotation > 180f || totalRotation < -180f) {
swapper = -1;
}
float rotSpeed = 1.5f;
if (totalRotation > 360) {
totalRotation -= 360;
}
if (totalRotation < -360) {
totalRotation += 360;
}
if (Math.abs(totalRotation) < 30 || Math.abs(totalRotation) > 330) {
rotSpeed = 0.5f;
}
if (currentAngle == desiredAngle) {
mBody.setAngularVelocity(0f);
} else if (desiredAngle > currentAngle) {
mBody.setAngularVelocity(swapper * (rotSpeed));
} else if (desiredAngle < currentAngle) {
mBody.setAngularVelocity(swapper * (-rotSpeed));
}
}
}
private void spawnActor() {
Level thisHereLevel = Game.get().getLevel();
long nextID = thisHereLevel.getId();
previousID = nextID;
Actor toSpawn;
if (Convert.getInt(getProp("Alternate")) == 1) {
if ((((shotsFired + 1) % 2) == 0 && Convert.getInt(getProp("Ammo")) == 0)
|| (((shotsFired + 1) % 2) == 1 && Convert.getInt(getProp("Ammo")) == 1)) {
toSpawn = new ImplodeBall(thisHereLevel, nextID,
Convert.getInt(getProp("explodeTime")));
} else {
toSpawn = new ExplodeBall(thisHereLevel, nextID,
Convert.getInt(getProp("explodeTime")));
}
} else {
if (Convert.getInt(getProp("Ammo")) == 1) {
toSpawn = new ImplodeBall(thisHereLevel, nextID,
Convert.getInt(getProp("explodeTime")));
} else {
toSpawn = new ExplodeBall(thisHereLevel, nextID,
Convert.getInt(getProp("explodeTime")));
}
}
Vector2 pos = mBody.getPosition();
toSpawn.setX(pos.x);
toSpawn.setY(pos.y);
toSpawn.setProp("Angle", mBody.getAngle());
Game.get().getLevel().addActor(toSpawn);
Vector2 vel = new Vector2(Convert.getInt(getProp("Exit Velocity")), 0);
vel.rotate(Convert.getDegrees(mBody.getAngle()));
toSpawn.setProp("Velocity X", vel.x);
toSpawn.setProp("Velocity Y", vel.y);
}
public void setProp(String name, Object val) {
if (name.equals("Rate")) {
if (Convert.getInt(val) == -1) {
// it wont even use this timer, kindof, I THINK ESNARF!
mSpawnTimer.setTimer(5000);
immediateRefire = true;
} else {
immediateRefire = false;
mSpawnTimer.setTimer(Convert.getInt(val));
}
}
if (name.equals("Angle")) {
initialAngle = Convert.getInt(val);
}
super.setProp(name, val);
}
@Override
public void loadBodies() {
}
@Override
public void postLoad() {
}
@Override
public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
Actor intersect = (Actor) fixture.getBody().getUserData();
if (intersect != null) {
// ignore things like wind/redirectors
if (intersect.mBody.getFixtureList().get(0).isSensor()
|| intersect instanceof VacuumBot || intersect instanceof ExplodeBall
|| intersect instanceof ImplodeBall) {
return -1;
}
if (intersect instanceof Blob) {
targetAcquired = true;
} else {
targetAcquired = false;
}
setProp("Actor Hit", intersect.getId());
if(!checkingLOS) {
mLaserEnd = point.cpy();
}
// clip at the first actor
return fraction;
} else {
// there was no actor tied to this fixture, ignore it
return -1;
}
}
} | underclocker/Blob-Game | BlobGame/src/org/siggd/actor/Cannon.java | Java | apache-2.0 | 10,975 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.logging;
import static org.apache.geode.internal.logging.LogServiceIntegrationTestSupport.*;
import static org.assertj.core.api.Assertions.*;
import java.io.File;
import java.net.URL;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.status.StatusLogger;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.SystemErrRule;
import org.junit.contrib.java.lang.system.SystemOutRule;
import org.junit.experimental.categories.Category;
import org.junit.rules.ExternalResource;
import org.junit.rules.TemporaryFolder;
import org.apache.geode.internal.logging.log4j.Configurator;
import org.apache.geode.test.junit.categories.IntegrationTest;
/**
* Integration tests for LogService and how it configures and uses log4j2
*
*/
@Category(IntegrationTest.class)
public class LogServiceIntegrationJUnitTest {
private static final String DEFAULT_CONFIG_FILE_NAME = "log4j2.xml";
private static final String CLI_CONFIG_FILE_NAME = "log4j2-cli.xml";
@Rule
public final SystemErrRule systemErrRule = new SystemErrRule().enableLog();
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
@Rule
public final TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule
public final ExternalResource externalResource = new ExternalResource() {
@Override
protected void before() {
beforeConfigFileProp = System.getProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
beforeLevel = StatusLogger.getLogger().getLevel();
System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
StatusLogger.getLogger().setLevel(Level.OFF);
Configurator.shutdown();
}
@Override
protected void after() {
Configurator.shutdown();
System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
if (beforeConfigFileProp != null) {
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, beforeConfigFileProp);
}
StatusLogger.getLogger().setLevel(beforeLevel);
LogService.reconfigure();
assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation())
.isTrue();
}
};
private String beforeConfigFileProp;
private Level beforeLevel;
private URL defaultConfigUrl;
private URL cliConfigUrl;
@Before
public void setUp() {
this.defaultConfigUrl = LogService.class.getResource(LogService.DEFAULT_CONFIG);
this.cliConfigUrl = LogService.class.getResource(LogService.CLI_CONFIG);
}
@After
public void after() {
// if either of these fail then log4j2 probably logged a failure to stdout
assertThat(this.systemErrRule.getLog()).isEmpty();
assertThat(this.systemOutRule.getLog()).isEmpty();
}
@Test
public void shouldPreferConfigurationFilePropertyIfSet() throws Exception {
final File configFile = this.temporaryFolder.newFile(DEFAULT_CONFIG_FILE_NAME);
final String configFileName = configFile.toURI().toString();
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, configFileName);
writeConfigFile(configFile, Level.DEBUG);
LogService.reconfigure();
assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation())
.isFalse();
assertThat(System.getProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY))
.isEqualTo(configFileName);
assertThat(LogService.getLogger().getName()).isEqualTo(getClass().getName());
}
@Test
public void shouldUseDefaultConfigIfNotConfigured() throws Exception {
LogService.reconfigure();
assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation())
.isTrue();
assertThat(System.getProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY))
.isNullOrEmpty();
}
@Test
public void defaultConfigShouldIncludeStdout() {
LogService.reconfigure();
final Logger rootLogger = (Logger) LogService.getRootLogger();
assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation())
.isTrue();
assertThat(rootLogger.getAppenders().get(LogService.STDOUT)).isNotNull();
}
@Test
public void removeConsoleAppenderShouldRemoveStdout() {
LogService.reconfigure();
final Logger rootLogger = (Logger) LogService.getRootLogger();
LogService.removeConsoleAppender();
assertThat(rootLogger.getAppenders().get(LogService.STDOUT)).isNull();
}
@Test
public void restoreConsoleAppenderShouldRestoreStdout() {
LogService.reconfigure();
final Logger rootLogger = (Logger) LogService.getRootLogger();
LogService.removeConsoleAppender();
assertThat(rootLogger.getAppenders().get(LogService.STDOUT)).isNull();
LogService.restoreConsoleAppender();
assertThat(rootLogger.getAppenders().get(LogService.STDOUT)).isNotNull();
}
@Test
public void removeAndRestoreConsoleAppenderShouldAffectRootLogger() {
LogService.reconfigure();
assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation())
.isTrue();
final Logger rootLogger = (Logger) LogService.getRootLogger();
// assert "Console" is present for ROOT
Appender appender = rootLogger.getAppenders().get(LogService.STDOUT);
assertThat(appender).isNotNull();
LogService.removeConsoleAppender();
// assert "Console" is not present for ROOT
appender = rootLogger.getAppenders().get(LogService.STDOUT);
assertThat(appender).isNull();
LogService.restoreConsoleAppender();
// assert "Console" is present for ROOT
appender = rootLogger.getAppenders().get(LogService.STDOUT);
assertThat(appender).isNotNull();
}
@Test
public void shouldNotUseDefaultConfigIfCliConfigSpecified() throws Exception {
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
this.cliConfigUrl.toString());
LogService.reconfigure();
assertThat(LogService.isUsingGemFireDefaultConfig()).as(LogService.getConfigInformation())
.isFalse();
assertThat(System.getProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY))
.isEqualTo(this.cliConfigUrl.toString());
assertThat(LogService.getLogger().getName()).isEqualTo(getClass().getName());
}
@Test
public void isUsingGemFireDefaultConfigShouldBeTrueIfDefaultConfig() throws Exception {
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
this.defaultConfigUrl.toString());
assertThat(LogService.getConfiguration().getConfigurationSource().toString())
.contains(DEFAULT_CONFIG_FILE_NAME);
assertThat(LogService.isUsingGemFireDefaultConfig()).isTrue();
}
@Test
public void isUsingGemFireDefaultConfigShouldBeFalseIfCliConfig() throws Exception {
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
this.cliConfigUrl.toString());
assertThat(LogService.getConfiguration().getConfigurationSource().toString())
.doesNotContain(DEFAULT_CONFIG_FILE_NAME);
assertThat(LogService.isUsingGemFireDefaultConfig()).isFalse();
}
@Test
public void shouldUseCliConfigIfCliConfigIsSpecifiedViaClasspath() throws Exception {
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY,
"classpath:" + CLI_CONFIG_FILE_NAME);
assertThat(LogService.getConfiguration().getConfigurationSource().toString())
.contains(CLI_CONFIG_FILE_NAME);
assertThat(LogService.isUsingGemFireDefaultConfig()).isFalse();
}
}
| smanvi-pivotal/geode | geode-core/src/test/java/org/apache/geode/internal/logging/LogServiceIntegrationJUnitTest.java | Java | apache-2.0 | 8,584 |
package ncku.hpds.hadoop.fedhdfs.shell;
import java.io.BufferedOutputStream;
import java.io.ObjectInputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import ncku.hpds.hadoop.fedhdfs.GlobalNamespaceObject;
public class DeleteDir {
private String SNaddress = "127.0.0.1";
private int SNport = 8765;
private int port = 8764;
public void rmGlobalFileFromGN(String command, String globalFileName) {
Socket client = new Socket();
ObjectInputStream ObjectIn;
InetSocketAddress isa = new InetSocketAddress(this.SNaddress, this.port);
try {
client.connect(isa, 10000);
ObjectIn = new ObjectInputStream(client.getInputStream());
// received object
GlobalNamespaceObject GN = new GlobalNamespaceObject();
try {
GN = (GlobalNamespaceObject) ObjectIn.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//doing...
if (GN.getGlobalNamespace().getLogicalDrive().getLogicalMappingTable().containsKey(globalFileName)) {
Socket SNclient = new Socket();
InetSocketAddress SNisa = new InetSocketAddress(this.SNaddress, this.SNport);
try {
SNclient.connect(SNisa, 10000);
BufferedOutputStream out = new BufferedOutputStream(SNclient
.getOutputStream());
// send message
String message = command + " " + globalFileName;
out.write(message.getBytes());
out.flush();
out.close();
out = null;
SNclient.close();
SNclient = null;
} catch (java.io.IOException e) {
System.out.println("Socket connect error");
System.out.println("IOException :" + e.toString());
}
}
else {
System.out.println("Error: " + globalFileName + " not found ");
}
ObjectIn.close();
ObjectIn = null;
client.close();
} catch (java.io.IOException e) {
System.out.println("Socket connection error");
System.out.println("IOException :" + e.toString());
}
System.out.println("globalFileName : " + globalFileName);
}
}
| tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-hdfs-project/hadoop-hdfs/src/main/java/ncku/hpds/hadoop/fedhdfs/shell/DeleteDir.java | Java | apache-2.0 | 2,262 |
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from game import app
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)
IOLoop.instance().start() | Drvanon/Game | run.py | Python | apache-2.0 | 232 |
package io.quarkus.arc.deployment;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Type;
import io.quarkus.arc.processor.BeanInfo;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.runtime.annotations.RegisterForReflection;
public class ReflectiveBeanClassesProcessor {
@BuildStep
void implicitReflectiveBeanClasses(BuildProducer<ReflectiveBeanClassBuildItem> reflectiveBeanClasses,
BeanDiscoveryFinishedBuildItem beanDiscoveryFinished) {
DotName registerForReflection = DotName.createSimple(RegisterForReflection.class.getName());
for (BeanInfo classBean : beanDiscoveryFinished.beanStream().classBeans()) {
ClassInfo beanClass = classBean.getTarget().get().asClass();
AnnotationInstance annotation = beanClass.classAnnotation(registerForReflection);
if (annotation != null) {
Type[] targets = annotation.value("targets") != null ? annotation.value("targets").asClassArray()
: new Type[] {};
String[] classNames = annotation.value("classNames") != null ? annotation.value("classNames").asStringArray()
: new String[] {};
if (targets.length == 0 && classNames.length == 0) {
reflectiveBeanClasses.produce(new ReflectiveBeanClassBuildItem(beanClass));
}
}
}
}
}
| quarkusio/quarkus | extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/ReflectiveBeanClassesProcessor.java | Java | apache-2.0 | 1,559 |
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable max-len */
import {BitsUtil} from '../util/BitsUtil';
import {ClientMessage, Frame, PARTITION_ID_OFFSET} from '../protocol/ClientMessage';
import {StringCodec} from './builtin/StringCodec';
// hex: 0x011F00
const REQUEST_MESSAGE_TYPE = 73472;
// hex: 0x011F01
// RESPONSE_MESSAGE_TYPE = 73473
const REQUEST_INITIAL_FRAME_SIZE = PARTITION_ID_OFFSET + BitsUtil.INT_SIZE_IN_BYTES;
/** @internal */
export class MapEvictAllCodec {
static encodeRequest(name: string): ClientMessage {
const clientMessage = ClientMessage.createForEncode();
clientMessage.setRetryable(false);
const initialFrame = Frame.createInitialFrame(REQUEST_INITIAL_FRAME_SIZE);
clientMessage.addFrame(initialFrame);
clientMessage.setMessageType(REQUEST_MESSAGE_TYPE);
clientMessage.setPartitionId(-1);
StringCodec.encode(clientMessage, name);
return clientMessage;
}
}
| hazelcast-incubator/hazelcast-nodejs-client | src/codec/MapEvictAllCodec.ts | TypeScript | apache-2.0 | 1,557 |
//
// TDContentOptions.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using System;
namespace Couchbase.Lite {
/// <summary>
/// Options for what metadata to include in document bodies
/// </summary>
[Flags]
[Serializable]
public enum DocumentContentOptions
{
/// <summary>
/// Include only the default information
/// </summary>
None,
/// <summary>
/// Include attachment data
/// </summary>
IncludeAttachments = 2,
/// <summary>
/// Include currently conflicting revisions
/// </summary>
IncludeConflicts = 4,
/// <summary>
/// Include a list of revisions
/// </summary>
IncludeRevs = 8,
/// <summary>
/// Include the status of each revision (i.e. whether available, missing, or deleted)
/// </summary>
IncludeRevsInfo = 16,
/// <summary>
/// Include the latest sequence number in the database
/// </summary>
IncludeLocalSeq = 32,
/// <summary>
/// Don't include the JSON properties
/// </summary>
[Obsolete("No longer used, will be removed")]
NoBody = 64,
/// <summary>
/// Attachments over a certain size are sent via a multipart response
/// </summary>
[Obsolete("No longer used, will be removed")]
BigAttachmentsFollow = 128,
/// <summary>
/// Don't include attachments
/// </summary>
[Obsolete("No longer used, will be removed")]
NoAttachments = 256,
/// <summary>
/// Includes the document's expiration time, if it has any
/// </summary>
IncludeExpiration = 512
}
}
| brettharrisonzya/couchbase-lite-net | src/Couchbase.Lite.Shared/Documents/DocumentContentOptions.cs | C# | apache-2.0 | 3,544 |
// +build matcha
package bridge
// Go support functions for Objective-C. Note that this
// file is copied into and compiled with the generated
// bindings.
/*
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include "go-foreign.h"
*/
import "C"
import (
"bytes"
"encoding/binary"
"fmt"
"math"
"reflect"
"runtime"
"runtime/debug"
"time"
)
//export matchaTestFunc
func matchaTestFunc() {
count := C.MatchaForeignTrackerCount()
for i := 0; i < 1000; i++ {
z := Nil()
a := Bool(true)
b := Int64(1234)
c := Float64(1.234)
d := String("abc")
e := Bytes([]byte("def123"))
f := Interface(123 + 234i)
if !z.IsNil() ||
a.ToBool() != true ||
b.ToInt64() != 1234 ||
c.ToFloat64() != 1.234 ||
d.ToString() != "abc" ||
!bytes.Equal(e.ToBytes(), []byte("def123")) ||
f.ToInterface() != 123+234i {
panic("Primitive mismatch")
}
arr := Array(z, a, b, c, d, e, f)
arr2 := arr.ToArray()
z = arr2[0]
a = arr2[1]
b = arr2[2]
c = arr2[3]
d = arr2[4]
e = arr2[5]
f = arr2[6]
if !z.IsNil() ||
a.ToBool() != true ||
b.ToInt64() != 1234 ||
c.ToFloat64() != 1.234 ||
d.ToString() != "abc" ||
!bytes.Equal(e.ToBytes(), []byte("def123")) ||
f.ToInterface() != 123+234i {
panic("Array mismatch")
}
runtime.GC()
}
// bridge := Bridge("a")
// fmt.Println("matchaTestFunc() - Bridge:", bridge)
debug.FreeOSMemory()
time.Sleep(time.Second)
newCount := C.MatchaForeignTrackerCount()
fmt.Println("count", count, newCount)
if math.Abs(float64(count-newCount)) > 1 { // Allow some leeway cause finalizer acts weirdly...
panic("Count mismatch")
}
}
var bridgeCache = map[string]*Value{}
var untrackChan = make(chan int64, 20)
func init() {
go func() {
runtime.LockOSThread()
for i := range untrackChan {
C.MatchaForeignUntrack(C.FgnRef(i))
}
runtime.UnlockOSThread()
}()
}
type Value struct {
ref int64
}
func newValue(ref C.FgnRef) *Value {
v := &Value{ref: int64(ref)}
runtime.SetFinalizer(v, func(a *Value) {
untrackChan <- a.ref
})
return v
}
func (v *Value) _ref() C.FgnRef {
return C.FgnRef(v.ref)
}
func Bridge(a string) *Value {
if b, ok := bridgeCache[a]; ok {
return b
}
cstr := cString(a)
b := newValue(C.MatchaForeignBridge(cstr))
bridgeCache[a] = b
return b
}
func Nil() *Value {
return newValue(C.MatchaForeignNil())
}
func (v *Value) IsNil() bool {
defer runtime.KeepAlive(v)
return bool(C.MatchaForeignIsNil(v._ref()))
}
func Bool(v bool) *Value {
return newValue(C.MatchaForeignBool(C.bool(v)))
}
func (v *Value) ToBool() bool {
defer runtime.KeepAlive(v)
return bool(C.MatchaForeignToBool(v._ref()))
}
func Int64(v int64) *Value {
return newValue(C.MatchaForeignInt64(C.int64_t(v)))
}
func (v *Value) ToInt64() int64 {
defer runtime.KeepAlive(v)
return int64(C.MatchaForeignToInt64(v._ref()))
}
func Float64(v float64) *Value {
return newValue(C.MatchaForeignFloat64(C.double(v)))
}
func (v *Value) ToFloat64() float64 {
defer runtime.KeepAlive(v)
return float64(C.MatchaForeignToFloat64(v._ref()))
}
func String(v string) *Value {
cstr := cString(v)
return newValue(C.MatchaForeignString(cstr))
}
func (v *Value) ToString() string {
defer runtime.KeepAlive(v)
buf := C.MatchaForeignToString(v._ref())
return goString(buf)
}
func Bytes(v []byte) *Value {
cbytes := cBytes(v)
return newValue(C.MatchaForeignBytes(cbytes))
}
func (v *Value) ToBytes() []byte {
defer runtime.KeepAlive(v)
buf := C.MatchaForeignToBytes(v._ref())
return goBytes(buf)
}
func Interface(v interface{}) *Value {
// Start with a go value.
// Reflect on it.
rv := reflect.ValueOf(v)
// Track it, turning it into a goref.
ref := matchaGoTrack(rv)
// Wrap the goref in an foreign object, returning a foreign ref.
return newValue(C.MatchaForeignGoRef(ref))
}
func (v *Value) ToInterface() interface{} {
defer runtime.KeepAlive(v)
// Start with a foreign ref, referring to a foreign value wrapping a go ref.
// Get the goref.
ref := C.MatchaForeignToGoRef(v._ref())
// Get the go object, and unreflect.
return matchaGoGet(ref).Interface()
}
func Array(a ...*Value) *Value {
defer runtime.KeepAlive(a)
ref := C.MatchaForeignArray(cArray2(a))
return newValue(ref)
}
func (v *Value) ToArray() []*Value { // TODO(KD): Untested....
defer runtime.KeepAlive(v)
buf := C.MatchaForeignToArray(v._ref())
return goArray2(buf)
}
// Call accepts `nil` in its variadic arguments
func (v *Value) Call(s string, args ...*Value) *Value {
defer runtime.KeepAlive(v)
defer runtime.KeepAlive(args)
return newValue(C.MatchaForeignCall(v._ref(), cString(s), cArray2(args)))
}
func cArray(v []reflect.Value) C.CGoBuffer {
var cstr C.CGoBuffer
if len(v) == 0 {
cstr = C.CGoBuffer{}
} else {
buf := new(bytes.Buffer)
for _, i := range v {
goref := matchaGoTrack(i)
err := binary.Write(buf, binary.LittleEndian, goref)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
}
cstr = C.CGoBuffer{
ptr: C.CBytes(buf.Bytes()),
len: C.int64_t(len(buf.Bytes())),
}
}
return cstr
}
func cArray2(v []*Value) C.CGoBuffer {
var cstr C.CGoBuffer
if len(v) == 0 {
cstr = C.CGoBuffer{}
} else {
buf := new(bytes.Buffer)
for _, i := range v {
foreignRef := i._ref()
err := binary.Write(buf, binary.LittleEndian, foreignRef)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
}
cstr = C.CGoBuffer{
ptr: C.CBytes(buf.Bytes()),
len: C.int64_t(len(buf.Bytes())),
}
}
return cstr
}
func cBytes(v []byte) C.CGoBuffer {
var cstr C.CGoBuffer
if len(v) == 0 {
cstr = C.CGoBuffer{}
} else {
cstr = C.CGoBuffer{
ptr: C.CBytes(v),
len: C.int64_t(len(v)),
}
}
return cstr
}
func cString(v string) C.CGoBuffer {
var cstr C.CGoBuffer
if len(v) == 0 {
cstr = C.CGoBuffer{}
} else {
cstr = C.CGoBuffer{
ptr: C.CBytes([]byte(v)),
len: C.int64_t(len(v)),
}
}
return cstr
}
func goArray(buf C.CGoBuffer) []reflect.Value {
defer C.free(buf.ptr)
gorefs := make([]int64, buf.len/8)
err := binary.Read(bytes.NewBuffer(C.GoBytes(buf.ptr, C.int(buf.len))), binary.LittleEndian, gorefs)
if err != nil {
panic(err)
}
rvs := []reflect.Value{}
for _, i := range gorefs {
rv := matchaGoGet(C.GoRef(i))
rvs = append(rvs, rv)
}
return rvs
}
func goArray2(buf C.CGoBuffer) []*Value {
defer C.free(buf.ptr)
fgnRef := make([]int64, buf.len/8)
err := binary.Read(bytes.NewBuffer(C.GoBytes(buf.ptr, C.int(buf.len))), binary.LittleEndian, fgnRef)
if err != nil {
panic(err)
}
rvs := []*Value{}
for _, i := range fgnRef {
rv := newValue(C.FgnRef(i))
rvs = append(rvs, rv)
}
return rvs
}
func goString(buf C.CGoBuffer) string {
defer C.free(buf.ptr)
str := C.GoBytes(buf.ptr, C.int(buf.len))
return string(str)
}
func goBytes(buf C.CGoBuffer) []byte {
defer C.free(buf.ptr)
return C.GoBytes(buf.ptr, C.int(buf.len))
}
| gomatcha/matcha | bridge/go-foreign.go | GO | apache-2.0 | 6,886 |
var searchData=
[
['checksyscall_2eh',['CheckSysCall.h',['../db/d19/_check_sys_call_8h.html',1,'']]],
['classid_2eh',['ClassID.h',['../dc/d14/_class_i_d_8h.html',1,'']]],
['comparator_2eh',['Comparator.h',['../d7/d0c/_comparator_8h.html',1,'']]]
];
| AubinMahe/AubinMahe.github.io | doxygen/html/search/files_2.js | JavaScript | apache-2.0 | 255 |
package com.android.potlach.cloud.client;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* This is an example of an HTTP client that does not properly
* validate SSL certificates that are used for HTTPS. You should
* NEVER use a client like this in a production application. Self-signed
* certificates are ususally only OK for testing purposes, such as
* this use case.
*
* @author jules
*
*/
public class UnsafeHttpsClient {
private static class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
public MySSLSocketFactory(SSLContext context) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
super(null);
sslContext = context;
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
public static HttpClient createUnsafeClient() {
try {
HttpClient client = new DefaultHttpClient();
client = sslClient(client);
// Execute HTTP Post Request
// HttpGet post = new HttpGet(new URI("https://google.com"));
// HttpResponse result = client.execute(post);
// Log.v("test", EntityUtils.toString(result.getEntity()));
// KeyStore trusted = KeyStore.getInstance("BKS");
// SSLContextBuilder builder = new SSLContextBuilder();
// builder.loadTrustMaterial(null, new AllowAllHostnameVerifier());
//
// SSLConnectionSocketFactory sslsf = new SSLSocketFactory(
// builder.build());
// CloseableHttpClient httpclient = HttpClients.custom()
// .setSSLSocketFactory(sslsf).build();
return client;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static HttpClient sslClient(HttpClient client) {
try {
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new MySSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = client.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 8443));
return new DefaultHttpClient(ccm, client.getParams());
} catch (Exception ex) {
return null;
}
}
}
| diyanfilipov/potlach-client | src/com/android/potlach/cloud/client/UnsafeHttpsClient.java | Java | apache-2.0 | 4,431 |
/**
* hujiawei - 15/3/21.
* <p/>
* 贪心
* <p/>
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
*/
public class BestTimetoBuyandSellStock_121 {
public static void main(String[] args) {
System.out.println(new BestTimetoBuyandSellStock_121().maxProfit(new int[]{2, 5, 3, 8, 1, 10}));
}
public int maxProfit(int[] prices) {
if (prices.length <= 1) return 0;
int max = 0, low = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] < low) low = prices[i];
else if (prices[i] - low > max) max = prices[i] - low;
}
return max;
}
}
| hujiaweibujidao/XSolutions | java/leetcode/BestTimetoBuyandSellStock_121.java | Java | apache-2.0 | 654 |
# Copyright 2011 OpenStack Foundation
# Copyright 2011 Nebula, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from keystoneclient import base
from keystoneclient import exceptions
from keystoneclient.i18n import _, _LW
from keystoneclient import utils
LOG = logging.getLogger(__name__)
class User(base.Resource):
"""Represents an Identity user.
Attributes:
* id: a uuid that identifies the user
"""
pass
class UserManager(base.CrudManager):
"""Manager class for manipulating Identity users."""
resource_class = User
collection_key = 'users'
key = 'user'
def _require_user_and_group(self, user, group):
if not (user and group):
msg = _('Specify both a user and a group')
raise exceptions.ValidationError(msg)
@utils.positional(1, enforcement=utils.positional.WARN)
def create(self, name, domain=None, project=None, password=None,
email=None, description=None, enabled=True,
default_project=None, **kwargs):
"""Create a user.
.. warning::
The project argument is deprecated, use default_project instead.
If both default_project and project is provided, the default_project
will be used.
"""
if project:
LOG.warning(_LW("The project argument is deprecated, "
"use default_project instead."))
default_project_id = base.getid(default_project) or base.getid(project)
user_data = base.filter_none(name=name,
domain_id=base.getid(domain),
default_project_id=default_project_id,
password=password,
email=email,
description=description,
enabled=enabled,
**kwargs)
return self._create('/users', {'user': user_data}, 'user',
log=not bool(password))
@utils.positional(enforcement=utils.positional.WARN)
def list(self, project=None, domain=None, group=None, default_project=None,
**kwargs):
"""List users.
If project, domain or group are provided, then filter
users with those attributes.
If ``**kwargs`` are provided, then filter users with
attributes matching ``**kwargs``.
.. warning::
The project argument is deprecated, use default_project instead.
If both default_project and project is provided, the default_project
will be used.
"""
if project:
LOG.warning(_LW("The project argument is deprecated, "
"use default_project instead."))
default_project_id = base.getid(default_project) or base.getid(project)
if group:
base_url = '/groups/%s' % base.getid(group)
else:
base_url = None
return super(UserManager, self).list(
base_url=base_url,
domain_id=base.getid(domain),
default_project_id=default_project_id,
**kwargs)
def get(self, user):
return super(UserManager, self).get(
user_id=base.getid(user))
@utils.positional(enforcement=utils.positional.WARN)
def update(self, user, name=None, domain=None, project=None, password=None,
email=None, description=None, enabled=None,
default_project=None, **kwargs):
"""Update a user.
.. warning::
The project argument is deprecated, use default_project instead.
If both default_project and project is provided, the default_project
will be used.
"""
if project:
LOG.warning(_LW("The project argument is deprecated, "
"use default_project instead."))
default_project_id = base.getid(default_project) or base.getid(project)
user_data = base.filter_none(name=name,
domain_id=base.getid(domain),
default_project_id=default_project_id,
password=password,
email=email,
description=description,
enabled=enabled,
**kwargs)
return self._update('/users/%s' % base.getid(user),
{'user': user_data},
'user',
method='PATCH',
log=False)
def update_password(self, old_password, new_password):
"""Update the password for the user the token belongs to."""
if not (old_password and new_password):
msg = _('Specify both the current password and a new password')
raise exceptions.ValidationError(msg)
if old_password == new_password:
msg = _('Old password and new password must be different.')
raise exceptions.ValidationError(msg)
params = {'user': {'password': new_password,
'original_password': old_password}}
base_url = '/users/%s/password' % self.api.user_id
return self._update(base_url, params, method='POST', log=False,
endpoint_filter={'interface': 'public'})
def add_to_group(self, user, group):
self._require_user_and_group(user, group)
base_url = '/groups/%s' % base.getid(group)
return super(UserManager, self).put(
base_url=base_url,
user_id=base.getid(user))
def check_in_group(self, user, group):
self._require_user_and_group(user, group)
base_url = '/groups/%s' % base.getid(group)
return super(UserManager, self).head(
base_url=base_url,
user_id=base.getid(user))
def remove_from_group(self, user, group):
self._require_user_and_group(user, group)
base_url = '/groups/%s' % base.getid(group)
return super(UserManager, self).delete(
base_url=base_url,
user_id=base.getid(user))
def delete(self, user):
return super(UserManager, self).delete(
user_id=base.getid(user))
| ging/python-keystoneclient | keystoneclient/v3/users.py | Python | apache-2.0 | 6,977 |
package toolbox_test
import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
"github.com/viant/toolbox"
)
func TestEncoderFactory(t *testing.T) {
buffer := new(bytes.Buffer)
assert.NotNil(t, toolbox.NewJSONEncoderFactory().Create(buffer))
}
func TestMarshalEncoderFactory(t *testing.T) {
buffer := new(bytes.Buffer)
encoder := toolbox.NewMarshalerEncoderFactory().Create(buffer)
foo := &Foo200{"abc"}
err := encoder.Encode(foo)
assert.Nil(t, err)
assert.Equal(t, "abc", string(buffer.Bytes()))
err = encoder.Encode(&Foo201{})
assert.NotNil(t, err)
}
type Foo200 struct {
Attr string
}
func (m *Foo200) Marshal() ([]byte, error) {
return []byte(m.Attr), nil
}
type Foo201 struct {
Attr string
}
| viant/toolbox | encoder_test.go | GO | apache-2.0 | 726 |
package cn.six.tutor.table2;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by songzhw on 2016/3/5.
*/
public class Table2Util {
private static ImageRegistry imgReg;
public static URL newUrl(String urlName){
try {
return new URL(urlName);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
public static ImageRegistry getImageRegister() {
if(imgReg == null){
imgReg = new ImageRegistry();
imgReg.put("folder", ImageDescriptor.createFromURL(newUrl("file:images/ic_box_16.png")));
imgReg.put("file", ImageDescriptor.createFromURL(newUrl("file:images/ic_file_16.png")));
}
return imgReg;
}
public static ImageDescriptor getImageDesp(String url){
return ImageDescriptor.createFromURL(Table2Util.newUrl(url));
}
}
| songzhw/AndroidTestDemo | IntoJFace/src/cn/six/tutor/table2/Table2Util.java | Java | apache-2.0 | 1,025 |
package com.cqs.socket.example;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by cqs on 10/29/16.
*/
public class SocketServerEncrypt {
private final static Logger logger = Logger.getLogger(SocketServerEncrypt.class.getName());
public static void main(String[] args) {
try {
ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
ServerSocket server = factory.createServerSocket(10000);
while (true) {
Socket socket = server.accept();
invoke(socket);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static void invoke(final Socket socket) throws IOException {
new Thread(new Runnable() {
public void run() {
ObjectInputStream is = null;
ObjectOutputStream os = null;
try {
is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));
os = new ObjectOutputStream(socket.getOutputStream());
Object obj = is.readObject();
User user = (User) obj;
System.out.println("user: " + user.getName() + "/" + user.getPassword());
user.setName(user.getName() + "_new");
user.setPassword(user.getPassword() + "_new");
os.writeObject(user);
os.flush();
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
logger.log(Level.SEVERE, null, ex);
} finally {
try {
is.close();
} catch (Exception ex) {
}
try {
os.close();
} catch (Exception ex) {
}
try {
socket.close();
} catch (Exception ex) {
}
}
}
}).start();
}
} | lixwcqs/funny | src/main/java/com.cqs/socket/example/SocketServerEncrypt.java | Java | apache-2.0 | 2,461 |
package net.community.chest.test.gui;
import java.io.BufferedReader;
import java.io.PrintStream;
import net.community.chest.Triplet;
import net.community.chest.awt.dom.converter.InsetsValueInstantiator;
import net.community.chest.awt.layout.gridbag.ExtendedGridBagConstraints;
import net.community.chest.awt.layout.gridbag.GridBagGridSizingType;
import net.community.chest.awt.layout.gridbag.GridBagXYValueStringInstantiator;
import net.community.chest.dom.DOMUtils;
import net.community.chest.test.TestBase;
import org.w3c.dom.Element;
/**
* <P>Copyright 2007 as per GPLv2</P>
*
* @author Lyor G.
* @since Aug 7, 2007 2:09:18 PM
*/
public class ResourcesTester extends TestBase {
private static final int testElementDataParsing (final PrintStream out, final BufferedReader in, final String elemData, final Element elem)
{
for ( ; ; )
{
out.println(elemData);
try
{
final ExtendedGridBagConstraints gbc=new ExtendedGridBagConstraints(elem);
out.println("\tgridx=" + (gbc.isAbsoluteGridX() ? String.valueOf(gbc.gridx) : GridBagXYValueStringInstantiator.RELATIVE_VALUE));
out.println("\tgridy=" + (gbc.isAbsoluteGridY() ? String.valueOf(gbc.gridy) : GridBagXYValueStringInstantiator.RELATIVE_VALUE));
final GridBagGridSizingType wt=gbc.getGridWithType(), ht=gbc.getGridHeightType();
out.println("\tgridwidth=" + ((null == wt) ? String.valueOf(gbc.gridwidth) : wt.name()));
out.println("\tgridheight=" + ((null == ht) ? String.valueOf(gbc.gridheight) : ht.name()));
out.println("\tfill=" + gbc.getFillType());
out.println("\tipadx=" + gbc.ipadx);
out.println("\tipady=" + gbc.ipady);
out.println("\tinsets=" + InsetsValueInstantiator.toString(gbc.insets));
out.println("\tanchor=" + gbc.getAnchorType());
out.println("\tweightx=" + gbc.weightx);
out.println("\tweighty=" + gbc.weighty);
}
catch(Exception e)
{
System.err.println("testElementDataParsing(" + elemData + ") " + e.getClass().getName() + ": " + e.getMessage());
}
final String ans=getval(out, in, "again (y)/[n]");
if ((null == ans) || (ans.length() <= 0) || (Character.toLowerCase(ans.charAt(0)) != 'y'))
break;
}
return 0;
}
// each argument is an XML element string to be parsed
private static final int testGridBagConstraintsParsing (final PrintStream out, final BufferedReader in, final String ... args)
{
final int numArgs=(null == args) ? 0 : args.length;
for (int aIndex=0; ; aIndex++)
{
final String elemData=(aIndex < numArgs) ? args[aIndex] : getval(out, in, "XML element data (or Quit)");
if ((null == elemData) || (elemData.length() <= 0))
continue;
if (isQuit(elemData)) break;
try
{
final Triplet<? extends Element,?,?> pe=
DOMUtils.parseElementString(elemData);
testElementDataParsing(out, in, elemData, (null == pe) ? null : pe.getV1());
}
catch(Exception e)
{
System.err.println("testGridBagConstraintsParsing(" + elemData + ") " + e.getClass().getName() + ": " + e.getMessage());
}
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
public static void main (String[] args)
{
final BufferedReader in=getStdin();
final int nErr=testGridBagConstraintsParsing(System.out, in, args);
if (nErr != 0)
System.err.println("test failed (err=" + nErr + ")");
else
System.out.println("OK");
}
}
| lgoldstein/communitychest | chest/gui/swing/src/test/java/net/community/chest/test/gui/ResourcesTester.java | Java | apache-2.0 | 3,969 |
/*
* Copyright 2015 ANTONIO CARLON
*
* 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.jummyshapefile.dbf.model;
/**
* Represents the properties of a DBF Field.
* <p>
* http://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm
*/
public class DBFFieldDescriptor {
private String name;
private String type;
private int length = -1;
private int decimalCount = -1;
/**
* Returns the name of the DBF field.
*
* @return the name of the DBF field
*/
public String getName() {
return name;
}
/**
* Sets the name of the DBF field.
*
* @param the
* name of the DBF field
*/
public void setName(final String name) {
this.name = name;
}
/**
* Returns the type of the field, as defined in the documentation.
* <p>
* Field type in ASCII (B, C, D, N, L, M, @, I, +, F, 0 or G).
*
* @return the type of the field, as defined in the documentation
*/
public String getType() {
return type;
}
/**
* Sets the type of the field, as defined in the documentation.
* <p>
* Field type in ASCII (B, C, D, N, L, M, @, I, +, F, 0 or G).
*
* @param type
* the type of the field, as defined in the documentation
*/
public void setType(final String type) {
this.type = type;
}
/**
* Returns the length of the field in bytes.
*
* @return the length of the field in bytes
*/
public int getLength() {
return length;
}
/**
* Sets the length of the field in bytes.
*
* @param length
* the length of the field in bytes
*/
public void setLength(final int length) {
this.length = length;
}
/**
* Returns the field decimal count.
*
* @return the field decimal count
*/
public int getDecimalCount() {
return decimalCount;
}
/**
* Sets the field decimal count.
*
* @param decimalCount
* the decimal count
*/
public void setDecimalCount(final int decimalCount) {
this.decimalCount = decimalCount;
}
@Override
public String toString() {
return "--- FIELD DESCRIPTOR: " + name + " / " + type + " / " + length
+ " / " + decimalCount;
}
}
| antoniocarlon/jummyshapefile | src/main/java/com/jummyshapefile/dbf/model/DBFFieldDescriptor.java | Java | apache-2.0 | 2,717 |
/*
* 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.pinpoint.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.pinpoint.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* WriteSegmentRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class WriteSegmentRequestMarshaller {
private static final MarshallingInfo<StructuredPojo> DIMENSIONS_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Dimensions").build();
private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Name").build();
private static final WriteSegmentRequestMarshaller instance = new WriteSegmentRequestMarshaller();
public static WriteSegmentRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(WriteSegmentRequest writeSegmentRequest, ProtocolMarshaller protocolMarshaller) {
if (writeSegmentRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(writeSegmentRequest.getDimensions(), DIMENSIONS_BINDING);
protocolMarshaller.marshall(writeSegmentRequest.getName(), NAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| dagnir/aws-sdk-java | aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/transform/WriteSegmentRequestMarshaller.java | Java | apache-2.0 | 2,302 |
sap.ui.define(['exports', './asset-registries/i18n', './asset-registries/LocaleData', './asset-registries/Themes', './asset-registries/Icons'], function (exports, i18n, LocaleData, Themes, Icons) { 'use strict';
exports.registerI18nLoader = i18n.registerI18nLoader;
exports.registerLocaleDataLoader = LocaleData.registerLocaleDataLoader;
exports.registerThemePropertiesLoader = Themes.registerThemePropertiesLoader;
exports.registerIconLoader = Icons.registerIconLoader;
Object.defineProperty(exports, '__esModule', { value: true });
});
| SAP/openui5 | src/sap.ui.webc.common/src/sap/ui/webc/common/thirdparty/base/AssetRegistry.js | JavaScript | apache-2.0 | 548 |
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2_app',
'username' => 'root',
'password' => 'lixiaoyu',
'charset' => 'utf8mb4',
'tablePrefix' => '',
];
| diandianxiyu/Yii2-CMS-Template | config/db_app.php | PHP | apache-2.0 | 217 |
using System;
namespace Chutzpah.Utility
{
public interface ICompilerCache
{
string Get(string source);
void Set(string source, string compiled);
void Save();
}
} | pimterry/chutzpah | Chutzpah/Utility/ICompilerCache.cs | C# | apache-2.0 | 212 |
package com.fruit.service.management;
import com.fruit.base.BaseService;
import com.fruit.entity.management.Quality;
import java.util.Map;
/**
* 产品质量检测 Service
* @author CSH
*
*/
public interface QualityService extends BaseService<Quality> {
/**返回当前质检人员的质检记录
* @param page
* @param pageSize
* @param ownid 当id小于0时,表示不采用该条件
* @param params
* @return
*/
public String showRecords(Integer page,Integer pageSize,int ownid,Map<String, String> params);
/**返回整个公司的质检记录
* @param page
* @param pageSize
* @param ownid 当id小于0时,表示不采用该条件
* @param params
* @return
*/
public String showRecordsByAdmin(Integer page,Integer pageSize,int companyId,Map<String, String> params);
/**更新质检记录
* @return
*/
public Integer updateRecords(Integer inspectorId,String name,String way,String checkResult,String picture,String date,String endNumber, String barcodes);
/**更新质检记录
* @return
*/
public Integer updateRecordToAll(Integer inspectorId,String name,String way,String checkResult,String picture,String date,String endNumber, String likeBarcode);
/**获取详细信息
* @param id
* @return
*/
public String getDetail(int id);
/**获取详细信息
* @param id
* @return
*/
public String getQualityDetail(Integer id);
/**
* 删除产品质量检测记录
* @param id
*/
// public void deleteQuality(int id) {
// Quality quality = qualityDao.getById(id);
// List<ImageBean> pictures = ImageBean.getImageList(quality.getPictures());
// for (ImageBean picture : pictures){
// FileManager.deleteImageFile(picture.getName());
// }
// qualityDao.delete(id);
// }
/**
* 获取质检记录柱状图数据
* @param page
* @param pageSize
* @param id
* @param params
* @return
*/
public String getChartData(Integer page,Integer pageSize,Integer id,Map<String, String> params);
/**
* 获取饼图数据
* @param page
* @param pageSize
* @param id
* @param params
* @return
*/
public String getPieChartData(Integer page,Integer pageSize,Integer id,Map<String, String> params);
}
| tanliu/fruit | fruit-core/src/main/java/com/fruit/service/management/QualityService.java | Java | apache-2.0 | 2,193 |
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from .client import SearchServiceClient
from .async_client import SearchServiceAsyncClient
__all__ = (
"SearchServiceClient",
"SearchServiceAsyncClient",
)
| googleapis/python-retail | google/cloud/retail_v2/services/search_service/__init__.py | Python | apache-2.0 | 765 |
<?php
/**
* Retrieves information about session cache memory usage
*
* @phpstub
*
* @return array Array of meta data about session cache memory usage
*/
function wincache_scache_meminfo()
{
} | schmittjoh/php-stubs | res/php/wincache/functions/wincache-scache-meminfo.php | PHP | apache-2.0 | 198 |
package com.focusit.jitloganalyzer.tty.model;
/**
* Created by doki on 08.11.16.
* <writer thread='139821162608384'/>
*/
public class WriterEvent extends AbstractTTYEvent implements TTYEvent, HasThreadId
{
private final static String START_TOKEN = "<writer";
private long threadId;
@Override
public boolean suitable(String line)
{
return line.startsWith(START_TOKEN);
}
@Override
public void processLine(String line)
{
}
public long getThreadId()
{
return threadId;
}
public void setThreadId(long threadId)
{
this.threadId = threadId;
}
}
| d0k1/jitloganalyzer | analyzer/src/main/java/com/focusit/jitloganalyzer/tty/model/WriterEvent.java | Java | apache-2.0 | 637 |
@extends('portalz::layout')
@section('content')
@section('breadcrumbs', Breadcrumbs::render('file-management-form',$data))
<div class="row">
<div class="col-md-12">
{!! Form::open(['url' => 'management/file/store','files' => true,'id'=>'storeForm','class'=>'form-horizontal']) !!}
{!! Form::hidden('id', isset($data)?$data->id:null, ['id' => 'id']) !!}
{!! Form::file('image',['class'=>'form-control','style' => 'visibility:hidden','id'=>'filename']) !!}
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2 no-padding-right" for="name">{!! Lang::get('label.file name') !!} *</label>
<div class="col-xs-12 col-sm-9">
<div class="input-group input-group-sm">
{!!Form::text('name',isset($data)?$data->name:null, ['readonly'=>true,'maxlength' => 100, 'class' => 'form-control','id'=>'name','placeholder'=>lang::get('label.file name')]) !!}
<span class="input-group-btn btn-group-custom">
<button type="button" id="ButtonSearch" class="btn btn-default btn-sm" onclick="$('#filename').click();" title="Suchen"><span class="glyphicon glyphicon-search"></span></button>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2 no-padding-right" for="name">{!! Lang::get('label.description') !!} *</label>
<div class="col-xs-12 col-sm-9">
<div class="clearfix">
{!!Form::textarea('description',isset($data)?$data->description:null, ['rows'=>3,'maxlength' => 100, 'class' => 'form-control col-xs-12 col-sm-6','id'=>'description','placeholder'=>lang::get('label.description')]) !!}
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2 no-padding-right" for="company_id">{!! Lang::get('label.company') !!}</label>
<div class="col-xs-11 col-sm-9">
<div class="clearfix">
{!! Form::select('company_id', \App\Models\Company::where('active',1)->lists('name', 'id'), isset($data)?$data->company_id:null, ['placeholder' => Lang::get('label.select company'),'class' => 'chosen form-control col-sm-12' ,'id' => 'company_id']) !!}
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2 no-padding-right" for="name">{!! Lang::get('label.users') !!} </label>
<div class="col-xs-12 col-sm-9">
<div class="row">
<div class="col-xs-5">
{!!Form::select('user_from[]',\App\Models\User::join('roles','roles.id','=','users.role_id')->select(['users.id','first_name'])->where('users.active',1)->where('authorize','==','0')->lists('first_name','id'),null, ['multiple'=>'multiple','size' => 8,'class' => 'form-control','id'=>'multiselect','placeholder'=>lang::get('label.select users')]) !!}
</div>
<div class="col-xs-2">
<button type="button" id="multiselect_rightAll" class="btn btn-sm btn-block btn-primary"><i class="glyphicon glyphicon-forward"></i></button>
<button type="button" id="multiselect_rightSelected" class="btn btn-sm btn-sm btn-block btn-primary"><i class="glyphicon glyphicon-chevron-right"></i></button>
<button type="button" id="multiselect_leftSelected" class="btn btn-sm btn-block btn-primary"><i class="glyphicon glyphicon-chevron-left"></i></button>
<button type="button" id="multiselect_leftAll" class="btn btn-sm btn-block btn-primary"><i class="glyphicon glyphicon-backward"></i></button>
</div>
<div class="col-xs-5">
{!!Form::select('users[]',\App\Models\FileUser::join('users','users.id','=','file_users.user_id')->select(['users.id','users.first_name'])->where('users.active',1)->where('file_users.file_id',$data?$data->id:0)->lists('first_name','id'),null, ['multiple'=>'multiple','size' => 8,'class' => 'form-control','id'=>'multiselect_to','placeholder'=>lang::get('label.selected users')]) !!}
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2 no-padding-right" for="active">{!! Lang::get('label.active') !!}:</label>
<div class="col-xs-11 col-sm-1">
<div class="clearfix">
{!!Form::checkbox('active',1,isset($data)?$data->active==1?true:false:false, ['id'=>'active']) !!}
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-7 col-md-4">
<div class="pull-right">
<button type="submit" class="btn btn-md btn-primary">
<i class="ace-icon fa fa-check bigger-110"></i>
{!! Lang::get('label.submit') !!}
</button>
<a href="{!! url('management/file') !!}" class="btn btn-md btn-primary">
<i class="ace-icon fa fa-mail-forward bigger-110"></i>
{!! Lang::get('label.back') !!}
</a>
</div>
<div class="clearfix"></div>
</div>
</div>
{!! Form::close() !!}
</div>
</div>
@endsection
@push('css')
<link rel="stylesheet" href="{{ asset('themes/portalz/assets/css/chosen.css') }}" />
@endpush
@push('scripts
<script src="{!! asset('themes/portalz/assets/js/chosen.jquery.js') !!}"></script>
<script>
$(document).ready(function(){
// This is the simple bit of jquery to duplicate the hidden field to subfile
$('#filename').change(function(){
$('#name').val($(this).val());
});
});
</script>
<script type="text/javascript" src="{!! asset('vendor/multiselect-1.0.4/js/multiselect.min.js') !!}"></script>
<script src="{!! asset('vendor/jsvalidation/js/jsvalidation.js') !!}"></script>
{!! JsValidate::formRequest('\App\Http\Requests\FileRequest', '#storeForm') !!}
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#multiselect').multiselect();
});
</script>
<script type="text/javascript">
$(".chosen").chosen();
$('#storeForm').on('submit', function(event) {
//alert("x");
event.preventDefault();
$(".loader").fadeIn("slow");
//var formData = $(this).serialize();
var formData = new FormData($(this)[0]);
var formAction = $(this).attr('action'); // form handler url
var formMethod = $(this).attr('method'); // GET, POST
$.ajax({
type : formMethod,
url : formAction,
data : formData,
async: false,
cache: false,
contentType: false,
processData: false,
beforeSend : function (xhr) {
var token = $('meta[name="_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success : function(data) {
var json = jQuery.parseJSON(data);
var loc = window.location;
if(json.error == false) {
window.location = loc.protocol+"//"+loc.hostname+"/management/file/";
}
else {
new PNotify({
title: '{!! Lang::get("label.error notification") !!}',
text: json.message,
type: 'error',
styling: "bootstrap3",
});
}
},
error : function() {
}
});
$(".loader").fadeOut("slow");
return false; // prevent send form
});
</script>
@endpush | suhe/bdoportal | resources/views/files/form Copy.blade.php | PHP | apache-2.0 | 6,981 |
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'test-page-two',
templateUrl: './page-two.component.html',
styleUrls: [
'./page-two.component.scss'
]
})
export class PageTwoComponent implements OnInit {
message: string;
constructor() {
this.message = '';
}
ngOnInit(): void {
this.message = 'PageTwoComponent message';
}
}
| vivekmore/generator-jhipster-nav-element | test/angular/nested-routes/use-sass/results/src/main/webapp/app/about-us/page-two/page-two.component.ts | TypeScript | apache-2.0 | 382 |
package postgres
import "github.com/shijuvar/gokit/examples/http-app/pkg/domain"
// ProductStore provides persistence logic for "products" table
type ProductStore struct {
Store DataStore
}
// ToDO: Write CRUD operations here
// Create creates a new Product
func (productStore ProductStore) Create(product domain.Product) (domain.Product, error) {
// ToDo: Write the code here
return domain.Product{}, nil
}
| shijuvar/gokit | examples/http-app/pkg/postgres/product_store.go | GO | apache-2.0 | 414 |
package org.tc.autonomous;
public class RetreatCommand3HullMod extends AbstractRetreatCommandHullMod {
public RetreatCommand3HullMod() {
super(3);
}
}
| herve-quiroz/autonomous-ships | src/org/tc/autonomous/RetreatCommand3HullMod.java | Java | apache-2.0 | 163 |
# Copyright 2015-2017 Capital One Services, 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.
"""
Resource Scheduling Offhours
============================
Custodian provides for time based filters, that allow for taking periodic
action on a resource, with resource schedule customization based on tag values.
A common use is offhours scheduling for asgs and instances.
Features
========
- Flexible offhours scheduling with opt-in, opt-out selection, and timezone
support.
- Resume during offhours support.
- Can be combined with other filters to get a particular set (
resources with tag, vpc, etc).
- Can be combined with arbitrary actions
Policy Configuration
====================
We provide an `onhour` and `offhour` time filter, each should be used in a
different policy, they support the same configuration options:
- **weekends**: default true, whether to leave resources off for the weekend
- **weekend-only**: default false, whether to turn the resource off only on
the weekend
- **default_tz**: which timezone to utilize when evaluating time **(REQUIRED)**
- **tag**: which resource tag name to use for per-resource configuration
(schedule and timezone overrides and opt-in/opt-out); default is
``maid_offhours``.
- **opt-out**: Determines the behavior for resources which do not have a tag
matching the one specified for **tag**. Values can be either ``false`` (the
default) where the policy operates on an opt-in basis and resources must have
the tag in order to be acted on by the policy, or ``true`` where the policy
operates on an opt-out basis, and resources without the tag are acted on by
the policy.
- **onhour**: the default time to start/run resources, specified as 0-23
- **offhour**: the default time to stop/suspend resources, specified as 0-23
This example policy overrides most of the defaults for an offhour policy:
.. code-block:: yaml
policies:
- name: offhours-stop
resource: ec2
filters:
- type: offhour
weekends: false
default_tz: pt
tag: downtime
opt-out: true
onhour: 8
offhour: 20
Tag Based Configuration
=======================
Resources can use a special tag to override the default configuration on a
per-resource basis. Note that the name of the tag is configurable via the
``tag`` option in the policy; the examples below use the default tag name,
``maid_offhours``.
The value of the tag must be one of the following:
- **(empty)** or **on** - An empty tag value or a value of "on" implies night
and weekend offhours using the default time zone configured in the policy
(tz=est if unspecified) and the default onhour and offhour values configured
in the policy.
- **off** - If offhours is configured to run in opt-out mode, this tag can be
specified to disable offhours on a given instance. If offhours is configured
to run in opt-in mode, this tag will have no effect (the resource will still
be opted out).
- a semicolon-separated string composed of one or more of the following
components, which override the defaults specified in the policy:
* ``tz=<timezone>`` to evaluate with a resource-specific timezone, where
``<timezone>`` is either one of the supported timezone aliases defined in
:py:attr:`c7n.filters.offhours.Time.TZ_ALIASES` (such as ``pt``) or the name
of a geographic timezone identifier in
[IANA's tzinfo database](https://www.iana.org/time-zones), such as
``Americas/Los_Angeles``. *(Note all timezone aliases are
referenced to a locality to ensure taking into account local daylight
savings time, if applicable.)*
* ``off=(time spec)`` and/or ``on=(time spec)`` matching time specifications
supported by :py:class:`c7n.filters.offhours.ScheduleParser` as described
in the next section.
ScheduleParser Time Specifications
----------------------------------
Each time specification follows the format ``(days,hours)``. Multiple time
specifications can be combined in square-bracketed lists, i.e.
``[(days,hours),(days,hours),(days,hours)]``.
**Examples**::
# up mon-fri from 7am-7pm; eastern time
off=(M-F,19);on=(M-F,7)
# up mon-fri from 6am-9pm; up sun from 10am-6pm; pacific time
off=[(M-F,21),(U,18)];on=[(M-F,6),(U,10)];tz=pt
**Possible values**:
+------------+----------------------+
| field | values |
+============+======================+
| days | M, T, W, H, F, S, U |
+------------+----------------------+
| hours | 0, 1, 2, ..., 22, 23 |
+------------+----------------------+
Days can be specified in a range (ex. M-F).
Policy examples
===============
Turn ec2 instances on and off
.. code-block:: yaml
policies:
- name: offhours-stop
resource: ec2
filters:
- type: offhour
actions:
- stop
- name: offhours-start
resource: ec2
filters:
- type: onhour
actions:
- start
Here's doing the same with auto scale groups
.. code-block:: yaml
policies:
- name: asg-offhours-stop
resource: asg
filters:
- offhour
actions:
- suspend
- name: asg-onhours-start
resource: asg
filters:
- onhour
actions:
- resume
Additional policy examples and resource-type-specific information can be seen in
the :ref:`EC2 Offhours <ec2offhours>` and :ref:`ASG Offhours <asgoffhours>`
use cases.
Resume During Offhours
======================
These policies are evaluated hourly; during each run (once an hour),
cloud-custodian will act on **only** the resources tagged for that **exact**
hour. In other words, if a resource has an offhours policy of
stopping/suspending at 23:00 Eastern daily and starting/resuming at 06:00
Eastern daily, and you run cloud-custodian once an hour via Lambda, that
resource will only be stopped once a day sometime between 23:00 and 23:59, and
will only be started once a day sometime between 06:00 and 06:59. If the current
hour does not *exactly* match the hour specified in the policy, nothing will be
done at all.
As a result of this, if custodian stops an instance or suspends an ASG and you
need to start/resume it, you can safely do so manually and custodian won't touch
it again until the next day.
ElasticBeanstalk, EFS and Other Services with Tag Value Restrictions
====================================================================
A number of AWS services have restrictions on the characters that can be used
in tag values, such as `ElasticBeanstalk <http://docs.aws.amazon.com/elasticbean
stalk/latest/dg/using-features.tagging.html>`_ and `EFS <http://docs.aws.amazon.
com/efs/latest/ug/API_Tag.html>`_. In particular, these services do not allow
parenthesis, square brackets, commas, or semicolons, or empty tag values. This
proves to be problematic with the tag-based schedule configuration described
above. The best current workaround is to define a separate policy with a unique
``tag`` name for each unique schedule that you want to use, and then tag
resources with that tag name and a value of ``on``. Note that this can only be
used in opt-in mode, not opt-out.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# note we have to module import for our testing mocks
import datetime
import logging
from os.path import join
from dateutil import zoneinfo
from c7n.filters import Filter, FilterValidationError
from c7n.utils import type_schema, dumps
log = logging.getLogger('custodian.offhours')
def brackets_removed(u):
return u.translate({ord('['): None, ord(']'): None})
def parens_removed(u):
return u.translate({ord('('): None, ord(')'): None})
class Time(Filter):
schema = {
'type': 'object',
'properties': {
'tag': {'type': 'string'},
'default_tz': {'type': 'string'},
'weekends': {'type': 'boolean'},
'weekends-only': {'type': 'boolean'},
'opt-out': {'type': 'boolean'},
}
}
time_type = None
# Defaults and constants
DEFAULT_TAG = "maid_offhours"
DEFAULT_TZ = 'et'
TZ_ALIASES = {
'pdt': 'America/Los_Angeles',
'pt': 'America/Los_Angeles',
'pst': 'America/Los_Angeles',
'ast': 'America/Phoenix',
'at': 'America/Phoenix',
'est': 'America/New_York',
'edt': 'America/New_York',
'et': 'America/New_York',
'cst': 'America/Chicago',
'cdt': 'America/Chicago',
'ct': 'America/Chicago',
'mst': 'America/Denver',
'mdt': 'America/Denver',
'mt': 'America/Denver',
'gmt': 'Etc/GMT',
'gt': 'Etc/GMT',
'bst': 'Europe/London',
'ist': 'Europe/Dublin',
'cet': 'Europe/Berlin',
# Technically IST (Indian Standard Time), but that's the same as Ireland
'it': 'Asia/Kolkata',
'jst': 'Asia/Tokyo',
'kst': 'Asia/Seoul',
'sgt': 'Asia/Singapore',
'aet': 'Australia/Sydney',
'brt': 'America/Sao_Paulo'
}
def __init__(self, data, manager=None):
super(Time, self).__init__(data, manager)
self.default_tz = self.data.get('default_tz', self.DEFAULT_TZ)
self.weekends = self.data.get('weekends', True)
self.weekends_only = self.data.get('weekends-only', False)
self.opt_out = self.data.get('opt-out', False)
self.tag_key = self.data.get('tag', self.DEFAULT_TAG).lower()
self.default_schedule = self.get_default_schedule()
self.parser = ScheduleParser(self.default_schedule)
self.id_key = None
self.opted_out = []
self.parse_errors = []
self.enabled_count = 0
def validate(self):
if self.get_tz(self.default_tz) is None:
raise FilterValidationError(
"Invalid timezone specified %s" % self.default_tz)
hour = self.data.get("%shour" % self.time_type, self.DEFAULT_HR)
if hour not in self.parser.VALID_HOURS:
raise FilterValidationError("Invalid hour specified %s" % hour)
return self
def process(self, resources, event=None):
resources = super(Time, self).process(resources)
if self.parse_errors and self.manager and self.manager.log_dir:
self.log.warning("parse errors %d", len(self.parse_errors))
with open(join(
self.manager.log_dir, 'parse_errors.json'), 'w') as fh:
dumps(self.parse_errors, fh=fh)
self.parse_errors = []
if self.opted_out and self.manager and self.manager.log_dir:
self.log.debug("disabled count %d", len(self.opted_out))
with open(join(
self.manager.log_dir, 'opted_out.json'), 'w') as fh:
dumps(self.opted_out, fh=fh)
self.opted_out = []
return resources
def __call__(self, i):
value = self.get_tag_value(i)
# Sigh delayed init, due to circle dep, process/init would be better
# but unit testing is calling this direct.
if self.id_key is None:
self.id_key = (
self.manager is None and 'InstanceId' or self.manager.get_model().id)
# The resource tag is not present, if we're not running in an opt-out
# mode, we're done.
if value is False:
if not self.opt_out:
return False
value = "" # take the defaults
# Resource opt out, track and record
if 'off' == value:
self.opted_out.append(i)
return False
else:
self.enabled_count += 1
try:
return self.process_resource_schedule(i, value, self.time_type)
except:
log.exception(
"%s failed to process resource:%s value:%s",
self.__class__.__name__, i[self.id_key], value)
return False
def process_resource_schedule(self, i, value, time_type):
"""Does the resource tag schedule and policy match the current time."""
rid = i[self.id_key]
# this is to normalize trailing semicolons which when done allows
# dateutil.parser.parse to process: value='off=(m-f,1);' properly.
# before this normalization, some cases would silently fail.
value = ';'.join(filter(None, value.split(';')))
if self.parser.has_resource_schedule(value, time_type):
schedule = self.parser.parse(value)
elif self.parser.keys_are_valid(value):
# respect timezone from tag
raw_data = self.parser.raw_data(value)
if 'tz' in raw_data:
schedule = dict(self.default_schedule)
schedule['tz'] = raw_data['tz']
else:
schedule = self.default_schedule
else:
schedule = None
if schedule is None:
log.warning(
"Invalid schedule on resource:%s value:%s", rid, value)
self.parse_errors.append((rid, value))
return False
tz = self.get_tz(schedule['tz'])
if not tz:
log.warning(
"Could not resolve tz on resource:%s value:%s", rid, value)
self.parse_errors.append((rid, value))
return False
now = datetime.datetime.now(tz).replace(
minute=0, second=0, microsecond=0)
return self.match(now, schedule)
def match(self, now, schedule):
time = schedule.get(self.time_type, ())
for item in time:
days, hour = item.get("days"), item.get('hour')
if now.weekday() in days and now.hour == hour:
return True
return False
def get_tag_value(self, i):
"""Get the resource's tag value specifying its schedule."""
# Look for the tag, Normalize tag key and tag value
found = False
for t in i.get('Tags', ()):
if t['Key'].lower() == self.tag_key:
found = t['Value']
break
if found is False:
return False
# enforce utf8, or do translate tables via unicode ord mapping
value = found.lower().encode('utf8').decode('utf8')
# Some folks seem to be interpreting the docs quote marks as
# literal for values.
value = value.strip("'").strip('"')
return value
@classmethod
def get_tz(cls, tz):
return zoneinfo.gettz(cls.TZ_ALIASES.get(tz, tz))
def get_default_schedule(self):
raise NotImplementedError("use subclass")
class OffHour(Time):
schema = type_schema(
'offhour', rinherit=Time.schema, required=['offhour', 'default_tz'],
offhour={'type': 'integer', 'minimum': 0, 'maximum': 23})
time_type = "off"
DEFAULT_HR = 19
def get_default_schedule(self):
default = {'tz': self.default_tz, self.time_type: [
{'hour': self.data.get(
"%shour" % self.time_type, self.DEFAULT_HR)}]}
if self.weekends_only:
default[self.time_type][0]['days'] = [4]
elif self.weekends:
default[self.time_type][0]['days'] = tuple(range(5))
else:
default[self.time_type][0]['days'] = tuple(range(7))
return default
class OnHour(Time):
schema = type_schema(
'onhour', rinherit=Time.schema, required=['onhour', 'default_tz'],
onhour={'type': 'integer', 'minimum': 0, 'maximum': 23})
time_type = "on"
DEFAULT_HR = 7
def get_default_schedule(self):
default = {'tz': self.default_tz, self.time_type: [
{'hour': self.data.get(
"%shour" % self.time_type, self.DEFAULT_HR)}]}
if self.weekends_only:
# turn on monday
default[self.time_type][0]['days'] = [0]
elif self.weekends:
default[self.time_type][0]['days'] = tuple(range(5))
else:
default[self.time_type][0]['days'] = tuple(range(7))
return default
class ScheduleParser(object):
"""Parses tag values for custom on/off hours schedules.
At the minimum the ``on`` and ``off`` values are required. Each of
these must be seperated by a ``;`` in the format described below.
**Schedule format**::
# up mon-fri from 7am-7pm; eastern time
off=(M-F,19);on=(M-F,7)
# up mon-fri from 6am-9pm; up sun from 10am-6pm; pacific time
off=[(M-F,21),(U,18)];on=[(M-F,6),(U,10)];tz=pt
**Possible values**:
+------------+----------------------+
| field | values |
+============+======================+
| days | M, T, W, H, F, S, U |
+------------+----------------------+
| hours | 0, 1, 2, ..., 22, 23 |
+------------+----------------------+
Days can be specified in a range (ex. M-F).
If the timezone is not supplied, it is assumed ET (eastern time), but this
default can be configurable.
**Parser output**:
The schedule parser will return a ``dict`` or ``None`` (if the schedule is
invalid)::
# off=[(M-F,21),(U,18)];on=[(M-F,6),(U,10)];tz=pt
{
off: [
{ days: "M-F", hour: 21 },
{ days: "U", hour: 18 }
],
on: [
{ days: "M-F", hour: 6 },
{ days: "U", hour: 10 }
],
tz: "pt"
}
"""
DAY_MAP = {'m': 0, 't': 1, 'w': 2, 'h': 3, 'f': 4, 's': 5, 'u': 6}
VALID_HOURS = tuple(range(24))
def __init__(self, default_schedule):
self.default_schedule = default_schedule
self.cache = {}
@staticmethod
def raw_data(tag_value):
"""convert the tag to a dictionary, taking values as is
This method name and purpose are opaque... and not true.
"""
data = {}
pieces = []
for p in tag_value.split(' '):
pieces.extend(p.split(';'))
# parse components
for piece in pieces:
kv = piece.split('=')
# components must by key=value
if not len(kv) == 2:
continue
key, value = kv
data[key] = value
return data
def keys_are_valid(self, tag_value):
"""test that provided tag keys are valid"""
for key in ScheduleParser.raw_data(tag_value):
if key not in ('on', 'off', 'tz'):
return False
return True
def parse(self, tag_value):
# check the cache
if tag_value in self.cache:
return self.cache[tag_value]
schedule = {}
if not self.keys_are_valid(tag_value):
return None
# parse schedule components
pieces = tag_value.split(';')
for piece in pieces:
kv = piece.split('=')
# components must by key=value
if not len(kv) == 2:
return None
key, value = kv
if key != 'tz':
value = self.parse_resource_schedule(value)
if value is None:
return None
schedule[key] = value
# add default timezone, if none supplied or blank
if not schedule.get('tz'):
schedule['tz'] = self.default_schedule['tz']
# cache
self.cache[tag_value] = schedule
return schedule
@staticmethod
def has_resource_schedule(tag_value, time_type):
raw_data = ScheduleParser.raw_data(tag_value)
# note time_type is set to 'on' or 'off' and raw_data is a dict
return time_type in raw_data
def parse_resource_schedule(self, lexeme):
parsed = []
exprs = brackets_removed(lexeme).split(',(')
for e in exprs:
tokens = parens_removed(e).split(',')
# custom hours must have two parts: (<days>, <hour>)
if not len(tokens) == 2:
return None
if not tokens[1].isdigit():
return None
hour = int(tokens[1])
if hour not in self.VALID_HOURS:
return None
days = self.expand_day_range(tokens[0])
if not days:
return None
parsed.append({'days': days, 'hour': hour})
return parsed
def expand_day_range(self, days):
# single day specified
if days in self.DAY_MAP:
return [self.DAY_MAP[days]]
day_range = [d for d in map(self.DAY_MAP.get, days.split('-'))
if d is not None]
if not len(day_range) == 2:
return None
# support wrap around days aka friday-monday = 4,5,6,0
if day_range[0] > day_range[1]:
return list(range(day_range[0], 7)) + list(range(day_range[1] + 1))
return list(range(min(day_range), max(day_range) + 1))
| sixfeetup/cloud-custodian | c7n/filters/offhours.py | Python | apache-2.0 | 21,487 |
from flask import Flask, Response, make_response
from video_stream_handler import stream_handler
import logging
import cv2
# see line 398 of connectionpool.py:
logging.basicConfig(level=logging.DEBUG)
thetav = None
app = Flask(__name__, static_url_path='/public', static_folder='../')
@app.route('/video_feed')
def video_feed():
cap = cv2.VideoCapture(0)
# cap.set(3, 3840)
# cap.set(4, 1920)
return Response(stream_handler(cap), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', threaded=True)
| rwoodley/SphericalPhotoBrowser | server/server.py | Python | apache-2.0 | 578 |
<?php return [
'pagination' => [
'ListBuckets' => [
'result_key' => 'Buckets',
],
'ListMultipartUploads' => [
'limit_key' => 'MaxUploads',
'more_results' => 'IsTruncated',
'output_token' => [
'NextKeyMarker',
'NextUploadIdMarker',
],
'input_token' => [
'KeyMarker',
'UploadIdMarker',
],
'result_key' => [
'Uploads',
'CommonPrefixes',
],
],
'ListObjectVersions' => [
'more_results' => 'IsTruncated',
'limit_key' => 'MaxKeys',
'output_token' => [
'NextKeyMarker',
'NextVersionIdMarker',
],
'input_token' => [
'KeyMarker',
'VersionIdMarker',
],
'result_key' => [
'Versions',
'DeleteMarkers',
'CommonPrefixes',
],
],
'ListObjects' => [
'more_results' => 'IsTruncated',
'limit_key' => 'MaxKeys',
'output_token' => 'NextMarker || Contents[-1].Key',
'input_token' => 'Marker',
'result_key' => [
'Contents',
'CommonPrefixes',
],
],
'ListParts' => [
'more_results' => 'IsTruncated',
'limit_key' => 'MaxParts',
'output_token' => 'NextPartNumberMarker',
'input_token' => 'PartNumberMarker',
'result_key' => 'Parts',
],
],
];
| Briareos/aws-sdk-php | src/data/s3-2006-03-01.paginators.php | PHP | apache-2.0 | 1,346 |
package com.example.fraud;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
import java.math.BigDecimal;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.fraud.model.FraudCheck;
import com.example.fraud.model.FraudCheckResult;
import com.example.fraud.model.FraudCheckStatus;
@RestController
public class FraudDetectionController {
private static final String FRAUD_SERVICE_JSON_VERSION_1 = "application/vnd.fraud.v1+json";
private static final String NO_REASON = null;
private static final String AMOUNT_TOO_HIGH = "Amount too high";
private static final BigDecimal MAX_AMOUNT = new BigDecimal("5000");
@RequestMapping(
value = "/fraudcheck",
method = PUT,
consumes = FRAUD_SERVICE_JSON_VERSION_1,
produces = FRAUD_SERVICE_JSON_VERSION_1)
public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) {
if (amountGreaterThanThreshold(fraudCheck)) {
return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH);
}
return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON);
}
private boolean amountGreaterThanThreshold(FraudCheck fraudCheck) {
return MAX_AMOUNT.compareTo(fraudCheck.getLoanAmount()) < 0;
}
}
| pfrank13/spring-cloud-contract | samples/standalone/pact/pact-http-server/src/main/java/com/example/fraud/FraudDetectionController.java | Java | apache-2.0 | 1,348 |
package annotationInteraction;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class QueryGenerator {
private long worksheet_id;
private Poem poem_content;
public QueryGenerator(long worksheet_id, Poem worksheet_content){
this.worksheet_id = worksheet_id;
poem_content = worksheet_content;
}
public List<QueryDetails> generateQueriesAtTheEndOfPenStroke(ClusterGenerator pen_stroke_cluster_generator, List<PenStroke> all_pen_strokes_in_worksheet, PenStroke pen_stroke_generating_clusters){
List<Map<PenStroke, List<String>>> annotator_pen_strokes_in_clusters = new ArrayList<Map<PenStroke, List<String>>>();
List<Map<PenStroke, List<List<PenStroke>>>> connector_pen_strokes_in_clusters = new ArrayList<Map<PenStroke, List<List<PenStroke>>>>();
List<Cluster> clusters = pen_stroke_cluster_generator.getClusterIterationAtStopIterationIndex().getClusters();
System.out.println("clusters on last pen stroke: " + clusters.size());
for(int i = 0; i < clusters.size(); i++){
Cluster cluster = clusters.get(i);
List<PenStroke> pen_strokes_in_cluster = cluster.getPenStrokes();
Map<PenStroke, List<String>> annotator_pen_strokes_in_cluster = new HashMap<PenStroke, List<String>>();
Map<PenStroke, List<List<PenStroke>>> connector_pen_strokes_in_cluster = new HashMap<PenStroke, List<List<PenStroke>>>();
System.out.println("pen strokes in cluster " + i + ": " + pen_strokes_in_cluster.size());
for(int j = 0; j < pen_strokes_in_cluster.size(); j++){
List<String> words_annotated_by_penstroke = new ArrayList<String>();
PenStroke pen_stroke = pen_strokes_in_cluster.get(j);
//TODO check for space where cluster is made if not on text space then ignore
ShapeRecognizer.penStrokeTypes pen_stroke_type = pen_stroke.getPenStrokeType();
if(pen_stroke_type == ShapeRecognizer.penStrokeTypes.Ellipse){
//System.out.println("cluster: " + i + " pen stroke " + j + " is ellipse");
words_annotated_by_penstroke = words_marked_by_ellipse(pen_stroke);
if(!words_annotated_by_penstroke.isEmpty()){
annotator_pen_strokes_in_cluster.put(pen_stroke, words_annotated_by_penstroke);
}
}
else if(pen_stroke_type == ShapeRecognizer.penStrokeTypes.Underline){
//System.out.println("cluster: " + i + " pen stroke " + j + " is underline");
words_annotated_by_penstroke = words_marked_by_underline(pen_stroke);
if(!words_annotated_by_penstroke.isEmpty()){
annotator_pen_strokes_in_cluster.put(pen_stroke, words_annotated_by_penstroke);
}
}
else if(pen_stroke_type == ShapeRecognizer.penStrokeTypes.Connector){
//System.out.println("cluster: " + i + " pen stroke " + j + " is connector");
List<List<PenStroke>> pen_strokes_connected = words_marked_by_connector(clusters, pen_stroke, all_pen_strokes_in_worksheet);
if(!pen_strokes_connected.isEmpty()){
System.out.println("found connector in cluster to add");
connector_pen_strokes_in_cluster.put(pen_stroke, pen_strokes_connected);
}
}
else{
continue;
}
}
if(!annotator_pen_strokes_in_cluster.isEmpty()){
annotator_pen_strokes_in_clusters.add(annotator_pen_strokes_in_cluster);
}
//System.out.println(connector_pen_strokes_in_cluster.isEmpty());
if(!connector_pen_strokes_in_cluster.isEmpty()){
//System.out.println("found connector in cluster to add");
connector_pen_strokes_in_clusters.add(connector_pen_strokes_in_cluster);
}
}
List<QueryDetails> all_queries = new ArrayList<QueryDetails>();
List<Long> annotator_pen_strokes_to_be_ignored_ids = new ArrayList<Long>();
// resolve all connectors first
List<Map<PenStroke, List<QueryDetails>>> connector_queries_in_clusters = new ArrayList<Map<PenStroke, List<QueryDetails>>>();
for(int i = 0; i < connector_pen_strokes_in_clusters.size(); i++){
//System.out.println("cluster " + i);
Map<PenStroke, List<QueryDetails>> connector_queries_in_cluster = new HashMap<PenStroke, List<QueryDetails>>();
Map<PenStroke, List<List<PenStroke>>> connector_pen_strokes_in_cluster = connector_pen_strokes_in_clusters.get(i);
Iterator<Entry<PenStroke, List<List<PenStroke>>>> connector_pen_strokes_iterator = connector_pen_strokes_in_cluster.entrySet().iterator();
while(connector_pen_strokes_iterator.hasNext()){
Map.Entry<PenStroke, List<List<PenStroke>>> connector_pen_stroke_entry = (Map.Entry<PenStroke, List<List<PenStroke>>>) connector_pen_strokes_iterator.next();
PenStroke connector_pen_stroke = connector_pen_stroke_entry.getKey();
//System.out.println("storke " + connector_pen_stroke.getStrokeId());
List<List<PenStroke>> connected_pen_strokes = connector_pen_stroke_entry.getValue();
List<QueryDetails> connector_pen_stroke_queries = generate_connector_queries(worksheet_id, pen_stroke_generating_clusters.getStrokeId(),connector_pen_stroke, connected_pen_strokes, annotator_pen_strokes_in_clusters);
//System.out.println(connector_pen_stroke_queries.isEmpty());
if(!connector_pen_stroke_queries.isEmpty()){
connector_queries_in_cluster.put(connector_pen_stroke, connector_pen_stroke_queries);
for(int m = 0; m < connector_pen_stroke_queries.size(); m++){
QueryDetails connector_pen_stroke_query = connector_pen_stroke_queries.get(m);
annotator_pen_strokes_to_be_ignored_ids.addAll(connector_pen_stroke_query.get_annotator_pen_strokes());
all_queries.add(connector_pen_stroke_query);
}
}
}
if(!connector_queries_in_cluster.isEmpty()){
connector_queries_in_clusters.add(connector_queries_in_cluster);
}
}
// then resolve ellipses and underlines
List<List<QueryDetails>> annotator_queries_in_clusters = new ArrayList<List<QueryDetails>>();
//System.out.println("before ellipse resolve");
for(int i = 0 ; i < annotator_pen_strokes_in_clusters.size(); i++){
List<QueryDetails> annotator_queries_in_cluster = new ArrayList<QueryDetails>();
Map<PenStroke, List<String>> ellipse_pen_strokes_in_cluster = new HashMap<PenStroke, List<String>>();
Map<PenStroke, List<String>> underline_pen_strokes_in_cluster = new HashMap<PenStroke, List<String>>();
Map<PenStroke, List<String>> annotator_pen_strokes_in_cluster = annotator_pen_strokes_in_clusters.get(i);
Iterator<Entry<PenStroke, List<String>>> annotator_pen_strokes_in_cluster_iterator = annotator_pen_strokes_in_cluster.entrySet().iterator();
while(annotator_pen_strokes_in_cluster_iterator.hasNext()){
Map.Entry<PenStroke, List<String>> annotator_stroke_entry = (Map.Entry<PenStroke, List<String>>) annotator_pen_strokes_in_cluster_iterator.next();
PenStroke annotator_pen_stroke = annotator_stroke_entry.getKey();
long annotator_pen_stroke_id = annotator_pen_stroke.getStrokeId();
boolean ignore_annotator_pen_stroke = false;
for(int j = 0; j < annotator_pen_strokes_to_be_ignored_ids.size(); j++){
if(annotator_pen_strokes_to_be_ignored_ids.get(j).longValue() == annotator_pen_stroke_id){
ignore_annotator_pen_stroke = true;
break;
}
}
if(!ignore_annotator_pen_stroke){
if(annotator_pen_stroke.getPenStrokeType() == ShapeRecognizer.penStrokeTypes.Ellipse){
ellipse_pen_strokes_in_cluster.put(annotator_pen_stroke, annotator_stroke_entry.getValue());
}
else{
underline_pen_strokes_in_cluster.put(annotator_pen_stroke, annotator_stroke_entry.getValue());
}
}
}
if(!ellipse_pen_strokes_in_cluster.isEmpty()){
QueryDetails annotator_query = new QueryDetails(worksheet_id, pen_stroke_generating_clusters.getStrokeId(), ellipse_pen_strokes_in_cluster);
annotator_queries_in_cluster.add(annotator_query);
all_queries.add(annotator_query);
}
if(!underline_pen_strokes_in_cluster.isEmpty()){
QueryDetails annotator_query = new QueryDetails(worksheet_id, pen_stroke_generating_clusters.getStrokeId(), underline_pen_strokes_in_cluster);
annotator_queries_in_cluster.add(annotator_query);
all_queries.add(annotator_query);
}
if(!annotator_queries_in_cluster.isEmpty()){
annotator_queries_in_clusters.add(annotator_queries_in_cluster);
}
}
return all_queries;
}
private List<QueryDetails> generate_connector_queries(long worksheet_id, long pen_stroke_generating_clusters_id, PenStroke connector_pen_stroke, List<List<PenStroke>> all_connected_pen_strokes, List<Map<PenStroke, List<String>>> annotator_pen_strokes_in_clusters){
//System.out.println("called generate connector");
List<QueryDetails> connector_queries = new ArrayList<QueryDetails>();
// all sets of pen strokes connected by this connector pen stroke
for(int i = 0; i < all_connected_pen_strokes.size(); i++){
// one set of pen strokes connected by this connector pen stroke
List<PenStroke> connected_pen_strokes = all_connected_pen_strokes.get(i);
long connected_1_stroke_id = connected_pen_strokes.get(0).getStrokeId(), connected_2_stroke_id = connected_pen_strokes.get(1).getStrokeId();
//System.out.println("looking for " + connected_1_stroke_id + ", " + connected_2_stroke_id + " in annotators");
Map<PenStroke, List<String>> connected_pen_strokes_all_info = new HashMap<PenStroke, List<String>>();
for(int j = 0; j < annotator_pen_strokes_in_clusters.size(); j++){
Map<PenStroke, List<String>> annotator_pen_strokes_in_cluster = annotator_pen_strokes_in_clusters.get(j);
Iterator<Entry<PenStroke, List<String>>> annotator_pen_strokes_iterator = annotator_pen_strokes_in_cluster.entrySet().iterator();
while(annotator_pen_strokes_iterator.hasNext()){
Map.Entry<PenStroke, List<String>> annotator_pen_stroke_entry = (Map.Entry<PenStroke, List<String>>) annotator_pen_strokes_iterator.next();
PenStroke annotator_pen_stroke = annotator_pen_stroke_entry.getKey();
List<String> annotated_words = annotator_pen_stroke_entry.getValue();
long annotator_pen_stroke_id = annotator_pen_stroke.getStrokeId();
//System.out.println(annotator_pen_stroke_id);
if(annotator_pen_stroke_id == connected_1_stroke_id || annotator_pen_stroke_id == connected_2_stroke_id){
//System.out.println("found match");
connected_pen_strokes_all_info.put(annotator_pen_stroke, annotated_words);
}
}
/*if(connected_pen_strokes_all_info.size() == 2){
break;
}*/
}
if(connected_pen_strokes_all_info.size() == 2){
//System.out.println("Connector query");
QueryDetails connector_query = new QueryDetails(worksheet_id, pen_stroke_generating_clusters_id, connected_pen_strokes_all_info, connector_pen_stroke);
connector_queries.add(connector_query);
}
}
return connector_queries;
}
private List<String> words_marked_by_ellipse(PenStroke pen_stroke){
//System.out.println(pen_stroke.getStrokeId());
List<String> words_annotated = new ArrayList<String>();
Rectangle2D pen_stroke_bounds = pen_stroke.getStrokeBounds();
double pen_stroke_area = pen_stroke_bounds.getWidth() * pen_stroke_bounds.getHeight();
List<Stanza> poem_stanzas = poem_content.getPoemStanzas().getStanzas();
for(int i = 0; i < poem_stanzas.size(); i++){
Stanza poem_stanza = poem_stanzas.get(i);
Rectangle2D poem_stanza_bounds = poem_stanza.getRawPixelBounds();
if(poem_stanza_bounds.intersects(pen_stroke_bounds)){
List<Line> stanza_lines = poem_stanza.getLines();
for(int j = 0; j < stanza_lines.size(); j++){
boolean has_annotated_word = false;
Line stanza_line = stanza_lines.get(j);
Rectangle2D stanza_line_bounds = stanza_line.getRawPixelBounds();
if(stanza_line_bounds.intersects(pen_stroke_bounds)){
Rectangle2D intersection = stanza_line_bounds.createIntersection(pen_stroke_bounds);
double intersection_area = intersection.getWidth() * intersection.getHeight();
if(intersection_area / pen_stroke_area > 0.4){
has_annotated_word = true;
//System.out.println("intersects line '" + j + "' with greater than 0.4");
List<Word> line_words = stanza_line.getWords();
for(int k = 0; k < line_words.size(); k++){
Word line_word = line_words.get(k);
Rectangle2D line_word_bounds = line_word.getRawPixelBounds();
if(line_word_bounds.intersects(pen_stroke_bounds)){
intersection = line_word_bounds.createIntersection(pen_stroke_bounds);
intersection_area = intersection.getWidth() * intersection.getHeight();
double word_area = line_word_bounds.getWidth() * line_word_bounds.getHeight();
//System.out.println("word area: " + word_area + " , intersection area: " + intersection_area + ", ratio: " + (intersection_area / pen_stroke_area));
if(intersection_area / word_area > 0.5){
words_annotated.add(i + "|" + j + "|" + k + "|" + line_word.getWord().trim().toLowerCase() + "|+|+|" + (intersection_area / pen_stroke_area));
//System.out.println("intersects word '" + line_word.getWord() + "' with greater than 0.5");
}
else{
words_annotated.add(i + "|" + j + "|" + k + "|" + line_word.getWord().trim().toLowerCase() + "|+|-|" + (intersection_area / pen_stroke_area));
//System.out.println("intersects word '" + line_word.getWord() + "' with less than 0.5");
}
}
}
}
else{
if(words_annotated.isEmpty() || !has_annotated_word){
//System.out.println("intersects line '" + j + "' with less than 0.4");
List<Word> line_words = stanza_line.getWords();
for(int k = 0; k < line_words.size(); k++){
Word line_word = line_words.get(k);
Rectangle2D line_word_bounds = line_word.getRawPixelBounds();
if(line_word_bounds.intersects(pen_stroke_bounds)){
intersection = line_word_bounds.createIntersection(pen_stroke_bounds);
intersection_area = intersection.getWidth() * intersection.getHeight();
double word_area = line_word_bounds.getWidth() * line_word_bounds.getHeight();
//System.out.println("word area: " + word_area + " , intersection area: " + intersection_area + ", ratio: " + (intersection_area / pen_stroke_area));
if(intersection_area / word_area > 0.5){
words_annotated.add(i + "|" + j + "|" + k + "|" + line_word.getWord().trim().toLowerCase() + "|-|+|" + (intersection_area / pen_stroke_area));
//System.out.println("intersects word '" + line_word.getWord() + "' with greater than 0.5");
//System.out.println(i + "|" + j + "|" + k + "|" + line_word.getWord().trim().toLowerCase() + "|-|+|" + (intersection_area / pen_stroke_area));
}
else{
words_annotated.add(i + "|" + j + "|" + k + "|" + line_word.getWord().trim().toLowerCase() + "|-|-|" + (intersection_area / pen_stroke_area));
//System.out.println("intersects word '" + line_word.getWord() + "' with less than 0.5");
}
}
}
}
}
}
}
break;
}
}
List<String> words_annotated_filtered = resolve_ellipse_plus_plus_words(words_annotated);
if(!words_annotated_filtered.isEmpty()){
return words_annotated_filtered;
}
else{
words_annotated_filtered = resolve_ellipse_plus_minus_words(words_annotated);
if(!words_annotated_filtered.isEmpty()){
return get_max_area_word(words_annotated_filtered);
}
else{
words_annotated_filtered = resolve_ellipse_minus_plus_words(words_annotated);
if(!words_annotated_filtered.isEmpty()){
return get_max_area_word(words_annotated_filtered);
}
else{
words_annotated_filtered = resolve_ellipse_minus_minus_words(words_annotated);
if(!words_annotated_filtered.isEmpty()){
return get_max_area_word(words_annotated_filtered);
}
else{
return words_annotated_filtered;
}
}
}
}
}
private List<String> resolve_ellipse_plus_plus_words(List<String> words_in_pen_stroke){
List<String> words = new ArrayList<String>();
for(int i = 0; i < words_in_pen_stroke.size(); i++){
String word_in_pen_stroke = words_in_pen_stroke.get(i);
String[] word_split = word_in_pen_stroke.split("\\|");
if(word_split[4].equals("+") && word_split[5].equals("+")){
words.add(word_split[0] + "|" + word_split[1] + "|" + word_split[2] + "|" + word_split[3]);
}
}
return words;
}
private List<String> resolve_ellipse_plus_minus_words(List<String> words_in_pen_stroke){
List<String> words = new ArrayList<String>();
for(int i = 0; i < words_in_pen_stroke.size(); i++){
String word_in_pen_stroke = words_in_pen_stroke.get(i);
String[] word_split = word_in_pen_stroke.split("\\|");
if(word_split[4].equals("+") && word_split[5].equals("-")){
words.add(word_in_pen_stroke);
}
}
return words;
}
private List<String> resolve_ellipse_minus_plus_words(List<String> words_in_pen_stroke){
List<String> words = new ArrayList<String>();
for(int i = 0; i < words_in_pen_stroke.size(); i++){
String word_in_pen_stroke = words_in_pen_stroke.get(i);
String[] word_split = word_in_pen_stroke.split("\\|");
if(word_split[4].equals("-") && word_split[5].equals("+")){
words.add(word_in_pen_stroke);
}
}
return words;
}
private List<String> resolve_ellipse_minus_minus_words(List<String> words_in_pen_stroke){
List<String> words = new ArrayList<String>();
for(int i = 0; i < words_in_pen_stroke.size(); i++){
String word_in_pen_stroke = words_in_pen_stroke.get(i);
String[] word_split = word_in_pen_stroke.split("\\|");
if(word_split[4].equals("-") && word_split[5].equals("-")){
words.add(word_in_pen_stroke);
}
}
return words;
}
private List<String> get_max_area_word(List<String> words){
List<String> max_area_words = new ArrayList<String>();
double max_area = Double.NEGATIVE_INFINITY;
String max_area_word = null;
for(int i = 0 ; i < words.size(); i++){
//System.out.println(words.get(i));
String[] word_split = words.get(i).split("\\|");
//System.out.println(word_split[0] + " " + word_split[1] + " " + word_split[2] + " " + word_split[3] + " " + word_split[4] + " " + word_split[5] + " " + word_split[6]);
double word_area = Double.parseDouble(word_split[6]);
if(word_area >= max_area){
max_area = word_area;
max_area_word = word_split[0] + "|" + word_split[1] + "|" + word_split[2] + "|" + word_split[3];
}
}
if(max_area_word != null){
max_area_words.add(max_area_word);
}
return max_area_words;
}
private List<String> words_marked_by_underline(PenStroke pen_stroke){
List<String> words_annotated = new ArrayList<String>();
Rectangle2D pen_stroke_bounds = pen_stroke.getStrokeBounds();
//double pen_stroke_area = pen_stroke_bounds.getWidth() * pen_stroke_bounds.getHeight();
double pen_start_x = pen_stroke_bounds.getX(), pen_end_x = pen_stroke_bounds.getWidth() + pen_stroke_bounds.getX();
List<Stanza> poem_stanzas = poem_content.getPoemStanzas().getStanzas();
for(int i = 0; i < poem_stanzas.size(); i++){
Stanza poem_stanza = poem_stanzas.get(i);
Rectangle2D poem_stanza_bounds = poem_stanza.getRawPixelBounds();
poem_stanza_bounds = new Rectangle2D.Double(poem_stanza_bounds.getX(), poem_stanza_bounds.getY(), poem_stanza_bounds.getWidth(), poem_stanza_bounds.getHeight() + CompositeGenerator.line_break_space);
if(poem_stanza_bounds.intersects(pen_stroke_bounds)){
List<Line> lines_in_stanza = poem_stanza.getLines();
for(int j = 0; j < lines_in_stanza.size(); j++){
Line line_in_stanza = lines_in_stanza.get(j);
Rectangle2D line_bounds = line_in_stanza.getRawPixelBounds();
if(j == lines_in_stanza.size() - 1){
line_bounds = new Rectangle2D.Double(line_bounds.getX(), line_bounds.getY(), line_bounds.getWidth(), line_bounds.getHeight() + CompositeGenerator.line_break_space);
}
else{
double next_line_start_y = lines_in_stanza.get(j + 1).getRawPixelBounds().getY();
double new_height = line_bounds.getHeight() + (next_line_start_y - (line_bounds.getY() + line_bounds.getHeight()));
line_bounds = new Rectangle2D.Double(line_bounds.getX(), line_bounds.getY(), line_bounds.getWidth(), new_height);
}
if(line_bounds.intersects(pen_stroke_bounds)){
//System.out.println("Intersects line " + j);
List<Word> words_in_line = line_in_stanza.getWords();
for(int k = 0 ; k < words_in_line.size(); k++){
Word word_in_line = words_in_line.get(k);
Rectangle2D word_bounds = word_in_line.getRawPixelBounds();
double word_start_x = word_bounds.getX(), word_end_x = word_bounds.getWidth() + word_bounds.getX();
if(check_if_overlap_for_underline(word_start_x, word_end_x, pen_start_x, pen_end_x)){
//System.out.println("Overlaps word '" + word_in_line.getWord() + "'");
words_annotated.add(i + "|" + j + "|" + k + "|" + word_in_line.getWord().trim().toLowerCase());
}
}
}
}
break;
}
}
return words_annotated;
}
private boolean check_if_overlap_for_underline(double word_start_x, double word_end_x, double pen_start_x, double pen_end_x){
Map<Double, String> end_points_sorted = new TreeMap<Double, String>();
end_points_sorted.put(word_start_x, "word_start");
end_points_sorted.put(word_end_x, "word_end");
end_points_sorted.put(pen_start_x, "pen_start");
end_points_sorted.put(pen_end_x, "pen_end");
boolean overlap = false;
String previous_end_point = null;
int end_points_compared = 0;
for (Map.Entry<Double, String> entry : end_points_sorted.entrySet())
{
if(end_points_compared < 2){
if(previous_end_point != null){
if(!entry.getValue().split("_")[0].equals(previous_end_point)){
overlap = true;
}
}
else{
previous_end_point = entry.getValue().split("_")[0];
}
}
else{
break;
}
end_points_compared++;
}
return overlap;
}
private List<List<PenStroke>> words_marked_by_connector(List<Cluster> pen_stroke_clusters, PenStroke connector_pen_stroke, List<PenStroke> all_pen_strokes_in_worksheet){
long connector_pen_stroke_id = connector_pen_stroke.getStrokeId();
List<List<PenStroke>> preceding_marks_to_look_up = find_marks_preceding_connector(connector_pen_stroke_id, all_pen_strokes_in_worksheet, connector_pen_stroke);
/*
for(int i = 0; i < preceding_marks_to_look_up.size(); i++){
List<PenStroke> set_of_pen_strokes = preceding_marks_to_look_up.get(i);
System.out.println("Connects stroke: ");
for(int j = 0; j < set_of_pen_strokes.size(); j++){
System.out.println(set_of_pen_strokes.get(j).getStrokeId());
}
}*/
return preceding_marks_to_look_up;
}
private List<List<PenStroke>> find_marks_preceding_connector(long connector_pen_stroke_id, List<PenStroke> all_pen_strokes_in_worksheet, PenStroke connector){
List<List<PenStroke>> pen_strokes_to_look_up = new ArrayList<List<PenStroke>>();
PenStroke connected_1, connected_2;
List<PenStroke> pair_of_pen_strokes = new ArrayList<PenStroke>();
if(connector_pen_stroke_id == 0){
/*
connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 1);
connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 2);
pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector);
if(!pair_of_pen_strokes.isEmpty()){
pen_strokes_to_look_up.add(pair_of_pen_strokes);
}
*/
}
else if(connector_pen_stroke_id == 1){
/*
connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id - 1);
connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 1);
pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector);
if(!pair_of_pen_strokes.isEmpty()){
pen_strokes_to_look_up.add(pair_of_pen_strokes);
}
connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 1);
connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 2);
pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector);
if(!pair_of_pen_strokes.isEmpty()){
pen_strokes_to_look_up.add(pair_of_pen_strokes);
}
*/
}
else{
/*
connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 1);
connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 2);
pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector);
if(!pair_of_pen_strokes.isEmpty()){
pen_strokes_to_look_up.add(pair_of_pen_strokes);
}
connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id - 1);
connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id + 1);
pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector);
if(!pair_of_pen_strokes.isEmpty()){
pen_strokes_to_look_up.add(pair_of_pen_strokes);
}
*/
connected_1 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id - 1);
connected_2 = get_pen_stroke_by_stroke_id(all_pen_strokes_in_worksheet, connector_pen_stroke_id - 2);
pair_of_pen_strokes = one_set_of_pen_strokes_to_check(connected_1, connected_2, connector);
if(!pair_of_pen_strokes.isEmpty()){
pen_strokes_to_look_up.add(pair_of_pen_strokes);
}
}
return pen_strokes_to_look_up;
}
private PenStroke get_pen_stroke_by_stroke_id(List<PenStroke> all_pen_strokes_in_worksheet, long pen_stroke_id){
PenStroke pen_stroke_found = null;
for(int i = 0 ; i < all_pen_strokes_in_worksheet.size(); i++){
PenStroke pen_stroke = all_pen_strokes_in_worksheet.get(i);
if(pen_stroke_id == pen_stroke.getStrokeId()){
pen_stroke_found = pen_stroke;
break;
}
}
return pen_stroke_found;
}
private List<PenStroke> one_set_of_pen_strokes_to_check(PenStroke connected_1, PenStroke connected_2, PenStroke connector){
List<PenStroke> connected_pen_strokes = new ArrayList<PenStroke>();
if(connected_1 != null && connected_2 != null){
ShapeRecognizer.penStrokeTypes connected_1_stroke_type = connected_1.getPenStrokeType();
ShapeRecognizer.penStrokeTypes connected_2_stroke_type = connected_2.getPenStrokeType();
if((connected_1_stroke_type != ShapeRecognizer.penStrokeTypes.Undefined) && (connected_2_stroke_type != ShapeRecognizer.penStrokeTypes.Undefined)){
Rectangle2D connector_bounds = connector.getStrokeBounds();
if(connector_bounds.intersects(connected_1.getStrokeBounds()) && connector_bounds.intersects(connected_2.getStrokeBounds())){
connected_pen_strokes.add(connected_1);
connected_pen_strokes.add(connected_2);
}
}
}
return connected_pen_strokes;
}
}
| pony-boy/AdamBradleyThesis | Metatation files/src/annotationInteraction/QueryGenerator.java | Java | apache-2.0 | 29,678 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-13 01:17
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('dash', '0002_remove_post_origin'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='id',
field=models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False),
),
]
| CMPUT404W17T06/CMPUT404-project | dash/migrations/0003_auto_20170313_0117.py | Python | apache-2.0 | 497 |
<?php
/**
* User: nathena
* Date: 2017/6/19 0019
* Time: 9:49
*/
include '../application/boot.php'; | nathena/zeus-php | webroot/index.php | PHP | apache-2.0 | 103 |
using System;
using System.Reflection;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using MongoDB;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
namespace DHDWeb.Models
{
public class SoftwareModel:ModelBase
{
public SoftwareModel()
{
}
[Required(ErrorMessage ="名称是必须的!")]
[Display(Name="名称")]
//[RegularExpression(@"\s\S{1,}", ErrorMessage ="必须填写内容")]
public String Name { get; set; } = String.Empty;
[Display(Name="作者")]
public String Author { get; set; } = String.Empty;
[Display(Name="描述")]
public String Description { get; set; } = String.Empty;
}
}
| sugartomato/AllProjects | daihaidong.com/DHDWeb/DHDWeb/Models/SoftwareModel.cs | C# | apache-2.0 | 770 |
package com.sva.model;
import java.math.BigDecimal;
public class LocationModel
{
private String idType;
private BigDecimal timestamp;
private String dataType;
private BigDecimal x;
private BigDecimal y;
private BigDecimal z;
private String userID;
private String path;
private String xo;
private String yo;
private String scale;
public String getXo()
{
return xo;
}
public void setXo(String xo)
{
this.xo = xo;
}
public String getYo()
{
return yo;
}
public void setYo(String yo)
{
this.yo = yo;
}
public String getScale()
{
return scale;
}
public void setScale(String scale)
{
this.scale = scale;
}
public String getPath()
{
return path;
}
public void setPath(String path)
{
this.path = path;
}
public String getIdType()
{
return idType;
}
public void setIdType(String idType)
{
this.idType = idType;
}
public BigDecimal getTimestamp()
{
return timestamp;
}
public void setTimestamp(BigDecimal timestamp)
{
this.timestamp = timestamp;
}
public String getDataType()
{
return dataType;
}
public void setDataType(String dataType)
{
this.dataType = dataType;
}
public BigDecimal getX()
{
return x;
}
public void setX(BigDecimal x)
{
this.x = x;
}
public BigDecimal getY()
{
return y;
}
public void setY(BigDecimal y)
{
this.y = y;
}
public BigDecimal getZ()
{
return z;
}
public void setZ(BigDecimal z)
{
this.z = z;
}
public String getUserID()
{
return userID;
}
public void setUserID(String userID)
{
this.userID = userID;
}
}
| SVADemoAPP/Server | model/com/sva/model/LocationModel.java | Java | apache-2.0 | 1,944 |
package org.nd4j.linalg.api.ops.impl.transforms.custom;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.base.Preconditions;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.DynamicCustomOp;
import org.tensorflow.framework.AttrValue;
import org.tensorflow.framework.GraphDef;
import org.tensorflow.framework.NodeDef;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Fake quantization operation.
* Quantized into range [0, 2^numBits - 1] when narrowRange is false, or [1, 2^numBits - 1] when narrowRange is true.
* Note that numBits must be in range 2 to 16 (inclusive).
* @author Alex Black
*/
public class FakeQuantWithMinMaxVars extends DynamicCustomOp {
protected boolean narrowRange;
protected int numBits;
public FakeQuantWithMinMaxVars(SameDiff sd, SDVariable input, SDVariable min, SDVariable max, boolean narrowRange, int numBits){
super(sd, new SDVariable[]{input, min, max});
Preconditions.checkState(numBits >= 2 && numBits <= 16, "NumBits arg must be in range 2 to 16 inclusive, got %s", numBits);
this.narrowRange = narrowRange;
this.numBits = numBits;
addArgs();
}
public FakeQuantWithMinMaxVars(INDArray x, INDArray min, INDArray max, int num_bits, boolean narrow) {
Preconditions.checkArgument(min.isVector() && max.isVector() &&
min.length() == max.length(),
"FakeQuantWithMinMaxVars: min and max should be 1D tensors with the same length");
addInputArgument(x,min,max);
addIArgument(num_bits);
addBArgument(narrow);
}
public FakeQuantWithMinMaxVars(){ }
protected void addArgs(){
iArguments.clear();
bArguments.clear();
addIArgument(numBits);
addBArgument(narrowRange);
}
@Override
public String opName(){
return "fake_quant_with_min_max_vars";
}
@Override
public String tensorflowName(){
return "FakeQuantWithMinMaxVars";
}
@Override
public void initFromTensorFlow(NodeDef nodeDef, SameDiff initWith, Map<String, AttrValue> attributesForNode, GraphDef graph) {
if(attributesForNode.containsKey("narrow_range")){
this.narrowRange = attributesForNode.get("narrow_range").getB();
}
this.numBits = (int)attributesForNode.get("num_bits").getI();
addArgs();
}
@Override
public List<DataType> calculateOutputDataTypes(List<DataType> inputDataTypes){
Preconditions.checkState(inputDataTypes != null && inputDataTypes.size() == 3, "Expected exactly 3 inputs, got %s", inputDataTypes);
return Collections.singletonList(inputDataTypes.get(0));
}
@Override
public List<SDVariable> doDiff(List<SDVariable> gradients){
return Arrays.asList(sameDiff.zerosLike(arg(0)), sameDiff.zerosLike(arg(1)), sameDiff.zerosLike(arg(2)));
}
}
| RobAltena/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/transforms/custom/FakeQuantWithMinMaxVars.java | Java | apache-2.0 | 3,062 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdds.scm;
import com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.hdds.scm.container.common.helpers.Pipeline;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.proto.ContainerProtos
.ContainerCommandRequestProto;
import org.apache.hadoop.hdds.protocol.proto.ContainerProtos
.ContainerCommandResponseProto;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A Client for the storageContainer protocol.
*/
public abstract class XceiverClientSpi implements Closeable {
final private AtomicInteger referenceCount;
private boolean isEvicted;
XceiverClientSpi() {
this.referenceCount = new AtomicInteger(0);
this.isEvicted = false;
}
void incrementReference() {
this.referenceCount.incrementAndGet();
}
void decrementReference() {
this.referenceCount.decrementAndGet();
cleanup();
}
void setEvicted() {
isEvicted = true;
cleanup();
}
// close the xceiverClient only if,
// 1) there is no refcount on the client
// 2) it has been evicted from the cache.
private void cleanup() {
if (referenceCount.get() == 0 && isEvicted) {
close();
}
}
@VisibleForTesting
public int getRefcount() {
return referenceCount.get();
}
/**
* Connects to the leader in the pipeline.
*/
public abstract void connect() throws Exception;
@Override
public abstract void close();
/**
* Returns the pipeline of machines that host the container used by this
* client.
*
* @return pipeline of machines that host the container
*/
public abstract Pipeline getPipeline();
/**
* Sends a given command to server and gets the reply back.
* @param request Request
* @return Response to the command
* @throws IOException
*/
public abstract ContainerCommandResponseProto sendCommand(
ContainerCommandRequestProto request) throws IOException;
/**
* Sends a given command to server gets a waitable future back.
*
* @param request Request
* @return Response to the command
* @throws IOException
*/
public abstract CompletableFuture<ContainerCommandResponseProto>
sendCommandAsync(ContainerCommandRequestProto request)
throws IOException, ExecutionException, InterruptedException;
/**
* Create a pipeline.
*
* @param pipelineID - Name of the pipeline.
* @param datanodes - Datanodes
*/
public abstract void createPipeline(String pipelineID,
List<DatanodeDetails> datanodes) throws IOException;
/**
* Returns pipeline Type.
*
* @return - {Stand_Alone, Ratis or Chained}
*/
public abstract HddsProtos.ReplicationType getPipelineType();
}
| ChetnaChaudhari/hadoop | hadoop-hdds/common/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientSpi.java | Java | apache-2.0 | 3,772 |
/**
* Copyright 2015 Alexander Erhard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.badw.strauss.glyphpicker.model;
import javax.swing.*;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* The data source combo box model.
*/
@XmlRootElement(name = "glyphTables")
@XmlAccessorType(XmlAccessType.FIELD)
public class DataSourceList extends AbstractListModel<String> implements
ComboBoxModel<String> {
private static final long serialVersionUID = 1L;
/**
* The maximum number of items in the list.
*/
private static final int ITEM_MAX = 20;
/**
* The selected item.
*/
@XmlTransient
private Object selectedItem;
/**
* The data sources.
*/
@XmlElement(name = "glyphTable")
private List<DataSource> data = new ArrayList<DataSource>();
/**
* Instantiates a new DataSourceList.
*/
public DataSourceList() {
}
/**
* Initializes the model.
*/
public void init() {
if (data != null && data.size() > 0) {
selectedItem = data.get(0).getLabel();
}
}
/**
* Sets the first index.
*
* @param index the new first index
*/
public void setFirstIndex(int index) {
DataSource item = getDataSourceAt(index);
data.add(0, item);
for (int i = data.size() - 1; i > 0; i--) {
if (item.equals(data.get(i)) || i > ITEM_MAX) {
data.remove(i);
}
}
fireContentsChanged(item, -1, -1);
}
/* (non-Javadoc)
* @see javax.swing.ComboBoxModel#getSelectedItem()
*/
public Object getSelectedItem() {
return selectedItem;
}
/* (non-Javadoc)
* @see javax.swing.ComboBoxModel#setSelectedItem(java.lang.Object)
*/
public void setSelectedItem(Object newValue) {
selectedItem = newValue;
fireContentsChanged(newValue, -1, -1);
}
/* (non-Javadoc)
* @see javax.swing.ListModel#getSize()
*/
public int getSize() {
return data.size();
}
/**
* Gets the data source's label at the specified index.
*
* @param i the index
* @return the label
*/
public String getElementAt(int i) {
return data.get(i).getLabel();
}
/**
* Gets the data source at the specified index.
*
* @param i the index
* @return the data source
*/
public DataSource getDataSourceAt(int i) {
return data.get(i);
}
/**
* Gets the data.
*
* @return the data
*/
public List<DataSource> getData() {
return data;
}
}
| richard-strauss-werke/glyphpicker | src/main/java/de/badw/strauss/glyphpicker/model/DataSourceList.java | Java | apache-2.0 | 3,199 |
using DigitalImageProcessingLib.ImageType;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DigitalImageProcessingLib.Interface
{
public interface IGlobalTresholdBinarization: IBinarization
{
int Treshold { get; set; }
int Countreshold(GreyImage image);
}
}
| ValeriyaSyomina/TextDetector | src/DigitalImageProcessingLib/Interface/IGlobalTresholdBinarization.cs | C# | apache-2.0 | 367 |
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"fmt"
"io"
"net"
"os"
"path"
"strings"
"github.com/spf13/pflag"
"k8s.io/klog/v2"
"k8s.io/kops/dns-controller/pkg/dns"
"k8s.io/kops/dnsprovider/pkg/dnsprovider"
"k8s.io/kops/pkg/wellknownports"
"k8s.io/kops/protokube/pkg/gossip"
gossipdns "k8s.io/kops/protokube/pkg/gossip/dns"
_ "k8s.io/kops/protokube/pkg/gossip/memberlist"
_ "k8s.io/kops/protokube/pkg/gossip/mesh"
"k8s.io/kops/protokube/pkg/protokube"
// Load DNS plugins
_ "k8s.io/kops/dnsprovider/pkg/dnsprovider/providers/aws/route53"
_ "k8s.io/kops/dnsprovider/pkg/dnsprovider/providers/do"
_ "k8s.io/kops/dnsprovider/pkg/dnsprovider/providers/google/clouddns"
)
var (
flags = pflag.NewFlagSet("", pflag.ExitOnError)
// BuildVersion is overwritten during build. This can be used to resolve issues.
BuildVersion = "0.1"
)
func main() {
klog.InitFlags(nil)
fmt.Printf("protokube version %s\n", BuildVersion)
if err := run(); err != nil {
klog.Errorf("Error: %v", err)
os.Exit(1)
}
os.Exit(0)
}
// run is responsible for running the protokube service controller
func run() error {
var zones []string
var containerized, master bool
var cloud, clusterID, dnsProviderID, dnsInternalSuffix, gossipSecret, gossipListen, gossipProtocol, gossipSecretSecondary, gossipListenSecondary, gossipProtocolSecondary string
var flagChannels string
var dnsUpdateInterval int
flag.BoolVar(&containerized, "containerized", containerized, "Set if we are running containerized.")
flag.BoolVar(&master, "master", master, "Whether or not this node is a master")
flag.StringVar(&cloud, "cloud", "aws", "CloudProvider we are using (aws,digitalocean,gce,openstack)")
flag.StringVar(&clusterID, "cluster-id", clusterID, "Cluster ID")
flag.StringVar(&dnsInternalSuffix, "dns-internal-suffix", dnsInternalSuffix, "DNS suffix for internal domain names")
flags.IntVar(&dnsUpdateInterval, "dns-update-interval", 5, "Configure interval at which to update DNS records.")
flag.StringVar(&flagChannels, "channels", flagChannels, "channels to install")
flag.StringVar(&gossipProtocol, "gossip-protocol", "mesh", "mesh/memberlist")
flag.StringVar(&gossipListen, "gossip-listen", fmt.Sprintf("0.0.0.0:%d", wellknownports.ProtokubeGossipWeaveMesh), "address:port on which to bind for gossip")
flags.StringVar(&gossipSecret, "gossip-secret", gossipSecret, "Secret to use to secure gossip")
flag.StringVar(&gossipProtocolSecondary, "gossip-protocol-secondary", "memberlist", "mesh/memberlist")
flag.StringVar(&gossipListenSecondary, "gossip-listen-secondary", fmt.Sprintf("0.0.0.0:%d", wellknownports.ProtokubeGossipMemberlist), "address:port on which to bind for gossip")
flags.StringVar(&gossipSecretSecondary, "gossip-secret-secondary", gossipSecret, "Secret to use to secure gossip")
flags.StringSliceVarP(&zones, "zone", "z", []string{}, "Configure permitted zones and their mappings")
flags.StringVar(&dnsProviderID, "dns", "aws-route53", "DNS provider we should use (aws-route53, google-clouddns, digitalocean)")
bootstrapMasterNodeLabels := false
flag.BoolVar(&bootstrapMasterNodeLabels, "bootstrap-master-node-labels", bootstrapMasterNodeLabels, "Bootstrap the labels for master nodes (required in k8s 1.16)")
nodeName := ""
flag.StringVar(&nodeName, "node-name", nodeName, "name of the node as will be created in kubernetes; used with bootstrap-master-node-labels")
var removeDNSNames string
flag.StringVar(&removeDNSNames, "remove-dns-names", removeDNSNames, "If set, will remove the DNS records specified")
// Trick to avoid 'logging before flag.Parse' warning
flag.CommandLine.Parse([]string{})
flag.Set("logtostderr", "true")
flags.AddGoFlagSet(flag.CommandLine)
flags.Parse(os.Args)
var volumes protokube.Volumes
var internalIP net.IP
if cloud == "aws" {
awsVolumes, err := protokube.NewAWSVolumes()
if err != nil {
klog.Errorf("Error initializing AWS: %q", err)
os.Exit(1)
}
volumes = awsVolumes
internalIP = awsVolumes.InternalIP()
if clusterID == "" {
clusterID = awsVolumes.ClusterID()
}
} else if cloud == "digitalocean" {
doVolumes, err := protokube.NewDOVolumes()
if err != nil {
klog.Errorf("Error initializing DigitalOcean: %q", err)
os.Exit(1)
}
volumes = doVolumes
internalIP, err = protokube.GetDropletInternalIP()
if err != nil {
klog.Errorf("Error getting droplet internal IP: %s", err)
os.Exit(1)
}
if clusterID == "" {
clusterID, err = protokube.GetClusterID()
if err != nil {
klog.Errorf("Error getting clusterid: %s", err)
os.Exit(1)
}
}
} else if cloud == "gce" {
gceVolumes, err := protokube.NewGCEVolumes()
if err != nil {
klog.Errorf("Error initializing GCE: %q", err)
os.Exit(1)
}
volumes = gceVolumes
internalIP = gceVolumes.InternalIP()
if clusterID == "" {
clusterID = gceVolumes.ClusterID()
}
} else if cloud == "openstack" {
klog.Info("Initializing openstack volumes")
osVolumes, err := protokube.NewOpenstackVolumes()
if err != nil {
klog.Errorf("Error initializing openstack: %q", err)
os.Exit(1)
}
volumes = osVolumes
internalIP = osVolumes.InternalIP()
if clusterID == "" {
clusterID = osVolumes.ClusterID()
}
} else if cloud == "alicloud" {
klog.Info("Initializing AliCloud volumes")
aliVolumes, err := protokube.NewALIVolumes()
if err != nil {
klog.Errorf("Error initializing Aliyun: %q", err)
os.Exit(1)
}
volumes = aliVolumes
internalIP = aliVolumes.InternalIP()
if clusterID == "" {
clusterID = aliVolumes.ClusterID()
}
} else if cloud == "azure" {
klog.Info("Initializing Azure volumes")
azureVolumes, err := protokube.NewAzureVolumes()
if err != nil {
klog.Errorf("Error initializing Azure: %q", err)
os.Exit(1)
}
volumes = azureVolumes
internalIP = azureVolumes.InternalIP()
if clusterID == "" {
clusterID = azureVolumes.ClusterID()
}
} else {
klog.Errorf("Unknown cloud %q", cloud)
os.Exit(1)
}
if clusterID == "" {
return fmt.Errorf("cluster-id is required (cannot be determined from cloud)")
}
klog.Infof("cluster-id: %s", clusterID)
if internalIP == nil {
klog.Errorf("Cannot determine internal IP")
os.Exit(1)
}
if dnsInternalSuffix == "" {
// TODO: Maybe only master needs DNS?
dnsInternalSuffix = ".internal." + clusterID
klog.Infof("Setting dns-internal-suffix to %q", dnsInternalSuffix)
}
// Make sure it's actually a suffix (starts with .)
if !strings.HasPrefix(dnsInternalSuffix, ".") {
dnsInternalSuffix = "." + dnsInternalSuffix
}
rootfs := "/"
if containerized {
rootfs = "/rootfs/"
}
protokube.RootFS = rootfs
var dnsProvider protokube.DNSProvider
if dnsProviderID == "gossip" {
dnsTarget := &gossipdns.HostsFile{
Path: path.Join(rootfs, "etc/hosts"),
}
var gossipSeeds gossip.SeedProvider
var err error
var gossipName string
if cloud == "aws" {
gossipSeeds, err = volumes.(*protokube.AWSVolumes).GossipSeeds()
if err != nil {
return err
}
gossipName = volumes.(*protokube.AWSVolumes).InstanceID()
} else if cloud == "gce" {
gossipSeeds, err = volumes.(*protokube.GCEVolumes).GossipSeeds()
if err != nil {
return err
}
gossipName = volumes.(*protokube.GCEVolumes).InstanceName()
} else if cloud == "openstack" {
gossipSeeds, err = volumes.(*protokube.OpenstackVolumes).GossipSeeds()
if err != nil {
return err
}
gossipName = volumes.(*protokube.OpenstackVolumes).InstanceName()
} else if cloud == "alicloud" {
gossipSeeds, err = volumes.(*protokube.ALIVolumes).GossipSeeds()
if err != nil {
return err
}
gossipName = volumes.(*protokube.ALIVolumes).InstanceID()
} else if cloud == "digitalocean" {
gossipSeeds, err = volumes.(*protokube.DOVolumes).GossipSeeds()
if err != nil {
return err
}
gossipName = volumes.(*protokube.DOVolumes).InstanceName()
} else if cloud == "azure" {
gossipSeeds, err = volumes.(*protokube.AzureVolumes).GossipSeeds()
if err != nil {
return err
}
gossipName = volumes.(*protokube.AzureVolumes).InstanceID()
} else {
klog.Fatalf("seed provider for %q not yet implemented", cloud)
}
id := os.Getenv("HOSTNAME")
if id == "" {
klog.Warningf("Unable to fetch HOSTNAME for use as node identifier")
}
channelName := "dns"
var gossipState gossip.GossipState
gossipState, err = gossip.GetGossipState(gossipProtocol, gossipListen, channelName, gossipName, []byte(gossipSecret), gossipSeeds)
if err != nil {
klog.Errorf("Error initializing gossip: %v", err)
os.Exit(1)
}
if gossipProtocolSecondary != "" {
secondaryGossipState, err := gossip.GetGossipState(gossipProtocolSecondary, gossipListenSecondary, channelName, gossipName, []byte(gossipSecretSecondary), gossipSeeds)
if err != nil {
klog.Errorf("Error initializing secondary gossip: %v", err)
os.Exit(1)
}
gossipState = &gossip.MultiGossipState{
Primary: gossipState,
Secondary: secondaryGossipState,
}
}
go func() {
err := gossipState.Start()
if err != nil {
klog.Fatalf("gossip exited unexpectedly: %v", err)
} else {
klog.Fatalf("gossip exited unexpectedly, but without error")
}
}()
dnsView := gossipdns.NewDNSView(gossipState)
zoneInfo := gossipdns.DNSZoneInfo{
Name: gossipdns.DefaultZoneName,
}
if _, err := dnsView.AddZone(zoneInfo); err != nil {
klog.Fatalf("error creating zone: %v", err)
}
go func() {
gossipdns.RunDNSUpdates(dnsTarget, dnsView)
klog.Fatalf("RunDNSUpdates exited unexpectedly")
}()
dnsProvider = &protokube.GossipDnsProvider{DNSView: dnsView, Zone: zoneInfo}
} else {
var dnsScope dns.Scope
var dnsController *dns.DNSController
{
var file io.Reader
dnsProvider, err := dnsprovider.GetDnsProvider(dnsProviderID, file)
if err != nil {
return fmt.Errorf("Error initializing DNS provider %q: %v", dnsProviderID, err)
}
if dnsProvider == nil {
return fmt.Errorf("DNS provider %q could not be initialized", dnsProviderID)
}
zoneRules, err := dns.ParseZoneRules(zones)
if err != nil {
return fmt.Errorf("unexpected zone flags: %q", err)
}
dnsController, err = dns.NewDNSController([]dnsprovider.Interface{dnsProvider}, zoneRules, dnsUpdateInterval)
if err != nil {
return err
}
dnsScope, err = dnsController.CreateScope("protokube")
if err != nil {
return err
}
// We don't really use readiness - our records are simple
dnsScope.MarkReady()
}
dnsProvider = &protokube.KopsDnsProvider{
DNSScope: dnsScope,
DNSController: dnsController,
}
}
go func() {
removeDNSRecords(removeDNSNames, dnsProvider)
}()
var channels []string
if flagChannels != "" {
channels = strings.Split(flagChannels, ",")
}
k := &protokube.KubeBoot{
BootstrapMasterNodeLabels: bootstrapMasterNodeLabels,
NodeName: nodeName,
Channels: channels,
DNS: dnsProvider,
InternalDNSSuffix: dnsInternalSuffix,
InternalIP: internalIP,
Kubernetes: protokube.NewKubernetesContext(),
Master: master,
}
if dnsProvider != nil {
go dnsProvider.Run()
}
k.RunSyncLoop()
return fmt.Errorf("Unexpected exit")
}
| justinsb/kops | protokube/cmd/protokube/main.go | GO | apache-2.0 | 11,852 |
/*
* Copyright 2011 Oleg Elifantiev
*
* 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 ru.elifantiev.yandex.oauth;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import ru.elifantiev.yandex.oauth.tokenstorage.AccessTokenStorage;
abstract public class OAuthActivity extends Activity {
/**
* Intent's Extra holding auth result
*/
public static final String EXTRA_AUTH_RESULT = "ru.elifantiev.yandex.oauth.AUTH_RESULT_EXTRA";
/**
* Intent's Extra holding error message (in case of error)
*/
public static final String EXTRA_AUTH_RESULT_ERROR = "ru.elifantiev.yandex.oauth.AUTH_RESULT_ERROR_EXTRA";
/**
* An action, which will be used to start activity, which must handle an authentication result.
* Must not be the same, as OAuthActivity.
* Intent's data field contains Uri 'oauth://{appId}' where appId is application Id returned with getAppId method.
*/
public static final String ACTION_AUTH_RESULT = "ru.elifantiev.yandex.oauth.AUTH_RESULT";
public static final int AUTH_RESULT_OK = 0;
public static final int AUTH_RESULT_ERROR = 1;
@Override
protected void onResume() {
authorize();
super.onResume(); //To change body of overridden methods use File | Settings | File Templates.
}
protected void authorize() {
Uri data = getIntent().getData();
if (data != null) {
AuthSequence
.newInstance(getServer(), getAppId())
.continueSequence(data, getContinuationHandler());
}
else
AuthSequence
.newInstance(getServer(), getAppId())
.start(getClientId(), getRequiredPermissions(), this);
}
/**
* This method must return PermissionsScope object declaring permission, required to current application
* @return PermissionsScope instance
*/
abstract protected PermissionsScope getRequiredPermissions();
/**
* Client ID by OAuth specification
* @return OAuth client ID
*/
abstract protected String getClientId();
/**
* This method must return an unique string ID of an application
* It is usually an application's package name
* This will be used to separate different application OAuth calls and token storage
* @return Unique ID of calling application
*/
abstract protected String getAppId();
/**
* Method to declare a server, which will handle OAuth calls
* @return URL of target server
*/
abstract protected Uri getServer();
/**
* Implementation of AccessTokenStorage to use for store application's access token
* Now implemented:
* - SharedPreferencesStorage - uses shared preferences to store token
* - EncryptedSharedPreferencesStorage - uses shared preferences but token is encrypted with 3DES and user-supplied key
* @return Token storage to use
*/
abstract protected AccessTokenStorage getTokenStorage();
protected AsyncContinuationHandler getContinuationHandler() {
return new AsyncContinuationHandler(getClientId(), getDefaultStatusHandler());
}
protected AuthStatusHandler getDefaultStatusHandler() {
return new AuthStatusHandler() {
public void onResult(AuthResult result) {
Intent callHome = new Intent(ACTION_AUTH_RESULT);
callHome.setData(Uri.parse(AuthSequence.OAUTH_SCHEME + "://" + getAppId()));
if(result.isSuccess()) {
getTokenStorage().storeToken(result.getToken(), getAppId());
callHome.putExtra(EXTRA_AUTH_RESULT, AUTH_RESULT_OK);
}
else {
callHome
.putExtra(EXTRA_AUTH_RESULT, AUTH_RESULT_ERROR)
.putExtra(EXTRA_AUTH_RESULT_ERROR, result.getError());
}
try {
startActivity(callHome);
} catch (ActivityNotFoundException e) {
// ignore
}
finish();
}
};
}
}
| Olegas/YandexAPI | src/ru/elifantiev/yandex/oauth/OAuthActivity.java | Java | apache-2.0 | 4,910 |
import { connect } from 'react-redux'
import { increment, doubleAsync,callApiAsync } from '../modules/Login'
/* This is a container component. Notice it does not contain any JSX,
nor does it import React. This component is **only** responsible for
wiring in the actions and state necessary to render a presentational
component - in this case, the counter: */
import Login from '../views/LoginView'
/* Object of action creators (can also be function that returns object).
Keys will be passed as props to presentational components. Here we are
implementing our wrapper around increment; the component doesn't care */
const mapDispatchToProps = {
increment : () => increment(1),
doubleAsync,
callApiAsync
}
const mapStateToProps = (state) => ({
counter : state.counter,
jsonResult: state.jsonResult
})
/* Note: mapStateToProps is where you should use `reselect` to create selectors, ie:
import { createSelector } from 'reselect'
const counter = (state) => state.counter
const tripleCount = createSelector(counter, (count) => count * 3)
const mapStateToProps = (state) => ({
counter: tripleCount(state)
})
Selectors can compute derived data, allowing Redux to store the minimal possible state.
Selectors are efficient. A selector is not recomputed unless one of its arguments change.
Selectors are composable. They can be used as input to other selectors.
https://github.com/reactjs/reselect */
export default connect(mapStateToProps, mapDispatchToProps)(Login)
| vio-lets/Larkyo-Client | src/components/login/controllers/LoginController.js | JavaScript | apache-2.0 | 1,549 |
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openspaces.admin.gsa;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.gigaspaces.grid.gsa.GSProcessOptions;
/**
* {@link org.openspaces.admin.esm.ElasticServiceManager} process options to be started by the
* {@link org.openspaces.admin.gsa.GridServiceAgent}.
*
* @author Moran Avigdor
* @see org.openspaces.admin.gsa.GridServiceAgent#startGridService(ElasticServiceManagerOptions)
*/
public class ElasticServiceManagerOptions {
private final List<String> vmInputArguments = new ArrayList<String>();
private boolean overrideVmInputArguments = false;
private boolean useScript = false;
private final Map<String, String> environmentVariables = new HashMap<String, String>();
/**
* Constructs a new elastic service manager options. By default will use JVM process execution.
*/
public ElasticServiceManagerOptions() {
}
/**
* Will cause the {@link org.openspaces.admin.esm.ElasticServiceManager} to be started using a script
* and not a pure Java process.
*/
public ElasticServiceManagerOptions useScript() {
this.useScript = true;
return this;
}
/**
* Will cause JVM options added using {@link #vmInputArgument(String)} to override all the vm arguments
* that the JVM will start by default with.
*/
public ElasticServiceManagerOptions overrideVmInputArguments() {
overrideVmInputArguments = true;
return this;
}
/**
* Will add a JVM level argument when the process is executed using pure JVM. For example, the memory
* can be controlled using <code>-Xmx512m</code>.
*/
public ElasticServiceManagerOptions vmInputArgument(String vmInputArgument) {
vmInputArguments.add(vmInputArgument);
return this;
}
/**
* Sets an environment variable that will be passed to forked process.
*/
public ElasticServiceManagerOptions environmentVariable(String name, String value) {
environmentVariables.put(name, value);
return this;
}
/**
* Returns the agent process options that represents what was set on this ESM options.
*/
public GSProcessOptions getOptions() {
GSProcessOptions options = new GSProcessOptions("esm");
options.setUseScript(useScript);
if (overrideVmInputArguments) {
options.setVmInputArguments(vmInputArguments.toArray(new String[vmInputArguments.size()]));
} else {
options.setVmAppendableInputArguments(vmInputArguments.toArray(new String[vmInputArguments.size()]));
}
options.setEnvironmentVariables(environmentVariables);
return options;
}
} | Gigaspaces/xap-openspaces | src/main/java/org/openspaces/admin/gsa/ElasticServiceManagerOptions.java | Java | apache-2.0 | 3,376 |
# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Container for Google Cloud Bigtable Cells and Streaming Row Contents."""
import copy
import six
from gcloud._helpers import _datetime_from_microseconds
from gcloud._helpers import _to_bytes
class Cell(object):
"""Representation of a Google Cloud Bigtable Cell.
:type value: bytes
:param value: The value stored in the cell.
:type timestamp: :class:`datetime.datetime`
:param timestamp: The timestamp when the cell was stored.
:type labels: list
:param labels: (Optional) List of strings. Labels applied to the cell.
"""
def __init__(self, value, timestamp, labels=()):
self.value = value
self.timestamp = timestamp
self.labels = list(labels)
@classmethod
def from_pb(cls, cell_pb):
"""Create a new cell from a Cell protobuf.
:type cell_pb: :class:`._generated.data_pb2.Cell`
:param cell_pb: The protobuf to convert.
:rtype: :class:`Cell`
:returns: The cell corresponding to the protobuf.
"""
timestamp = _datetime_from_microseconds(cell_pb.timestamp_micros)
if cell_pb.labels:
return cls(cell_pb.value, timestamp, labels=cell_pb.labels)
else:
return cls(cell_pb.value, timestamp)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return (other.value == self.value and
other.timestamp == self.timestamp and
other.labels == self.labels)
def __ne__(self, other):
return not self.__eq__(other)
class PartialCellData(object):
"""Representation of partial cell in a Google Cloud Bigtable Table.
These are expected to be updated directly from a
:class:`._generated.bigtable_service_messages_pb2.ReadRowsResponse`
:type row_key: bytes
:param row_key: The key for the row holding the (partial) cell.
:type family_name: str
:param family_name: The family name of the (partial) cell.
:type qualifier: bytes
:param qualifier: The column qualifier of the (partial) cell.
:type timestamp_micros: int
:param timestamp_micros: The timestamp (in microsecods) of the
(partial) cell.
:type labels: list of str
:param labels: labels assigned to the (partial) cell
:type value: bytes
:param value: The (accumulated) value of the (partial) cell.
"""
def __init__(self, row_key, family_name, qualifier, timestamp_micros,
labels=(), value=b''):
self.row_key = row_key
self.family_name = family_name
self.qualifier = qualifier
self.timestamp_micros = timestamp_micros
self.labels = labels
self.value = value
def append_value(self, value):
"""Append bytes from a new chunk to value.
:type value: bytes
:param value: bytes to append
"""
self.value += value
class PartialRowData(object):
"""Representation of partial row in a Google Cloud Bigtable Table.
These are expected to be updated directly from a
:class:`._generated.bigtable_service_messages_pb2.ReadRowsResponse`
:type row_key: bytes
:param row_key: The key for the row holding the (partial) data.
"""
def __init__(self, row_key):
self._row_key = row_key
self._cells = {}
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return (other._row_key == self._row_key and
other._cells == self._cells)
def __ne__(self, other):
return not self.__eq__(other)
def to_dict(self):
"""Convert the cells to a dictionary.
This is intended to be used with HappyBase, so the column family and
column qualiers are combined (with ``:``).
:rtype: dict
:returns: Dictionary containing all the data in the cells of this row.
"""
result = {}
for column_family_id, columns in six.iteritems(self._cells):
for column_qual, cells in six.iteritems(columns):
key = (_to_bytes(column_family_id) + b':' +
_to_bytes(column_qual))
result[key] = cells
return result
@property
def cells(self):
"""Property returning all the cells accumulated on this partial row.
:rtype: dict
:returns: Dictionary of the :class:`Cell` objects accumulated. This
dictionary has two-levels of keys (first for column families
and second for column names/qualifiers within a family). For
a given column, a list of :class:`Cell` objects is stored.
"""
return copy.deepcopy(self._cells)
@property
def row_key(self):
"""Getter for the current (partial) row's key.
:rtype: bytes
:returns: The current (partial) row's key.
"""
return self._row_key
class InvalidReadRowsResponse(RuntimeError):
"""Exception raised to to invalid response data from back-end."""
class InvalidChunk(RuntimeError):
"""Exception raised to to invalid chunk data from back-end."""
class PartialRowsData(object):
"""Convenience wrapper for consuming a ``ReadRows`` streaming response.
:type response_iterator:
:class:`grpc.framework.alpha._reexport._CancellableIterator`
:param response_iterator: A streaming iterator returned from a
``ReadRows`` request.
"""
START = "Start" # No responses yet processed.
NEW_ROW = "New row" # No cells yet complete for row
ROW_IN_PROGRESS = "Row in progress" # Some cells complete for row
CELL_IN_PROGRESS = "Cell in progress" # Incomplete cell for row
def __init__(self, response_iterator):
self._response_iterator = response_iterator
# Fully-processed rows, keyed by `row_key`
self._rows = {}
# Counter for responses pulled from iterator
self._counter = 0
# Maybe cached from previous response
self._last_scanned_row_key = None
# In-progress row, unset until first response, after commit/reset
self._row = None
# Last complete row, unset until first commit
self._previous_row = None
# In-progress cell, unset until first response, after completion
self._cell = None
# Last complete cell, unset until first completion, after new row
self._previous_cell = None
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return other._response_iterator == self._response_iterator
def __ne__(self, other):
return not self.__eq__(other)
@property
def state(self):
"""State machine state.
:rtype: str
:returns: name of state corresponding to currrent row / chunk
processing.
"""
if self._last_scanned_row_key is None:
return self.START
if self._row is None:
assert self._cell is None
assert self._previous_cell is None
return self.NEW_ROW
if self._cell is not None:
return self.CELL_IN_PROGRESS
if self._previous_cell is not None:
return self.ROW_IN_PROGRESS
return self.NEW_ROW # row added, no chunk yet processed
@property
def rows(self):
"""Property returning all rows accumulated from the stream.
:rtype: dict
:returns: row_key -> :class:`PartialRowData`.
"""
# NOTE: To avoid duplicating large objects, this is just the
# mutable private data.
return self._rows
def cancel(self):
"""Cancels the iterator, closing the stream."""
self._response_iterator.cancel()
def consume_next(self):
"""Consume the next ``ReadRowsResponse`` from the stream.
Parse the response and its chunks into a new/existing row in
:attr:`_rows`
"""
response = six.next(self._response_iterator)
self._counter += 1
if self._last_scanned_row_key is None: # first response
if response.last_scanned_row_key:
raise InvalidReadRowsResponse()
self._last_scanned_row_key = response.last_scanned_row_key
row = self._row
cell = self._cell
for chunk in response.chunks:
self._validate_chunk(chunk)
if chunk.reset_row:
row = self._row = None
cell = self._cell = self._previous_cell = None
continue
if row is None:
row = self._row = PartialRowData(chunk.row_key)
if cell is None:
cell = self._cell = PartialCellData(
chunk.row_key,
chunk.family_name.value,
chunk.qualifier.value,
chunk.timestamp_micros,
chunk.labels,
chunk.value)
self._copy_from_previous(cell)
else:
cell.append_value(chunk.value)
if chunk.commit_row:
self._save_current_row()
row = cell = None
continue
if chunk.value_size == 0:
self._save_current_cell()
cell = None
def consume_all(self, max_loops=None):
"""Consume the streamed responses until there are no more.
This simply calls :meth:`consume_next` until there are no
more to consume.
:type max_loops: int
:param max_loops: (Optional) Maximum number of times to try to consume
an additional ``ReadRowsResponse``. You can use this
to avoid long wait times.
"""
curr_loop = 0
if max_loops is None:
max_loops = float('inf')
while curr_loop < max_loops:
curr_loop += 1
try:
self.consume_next()
except StopIteration:
break
@staticmethod
def _validate_chunk_status(chunk):
"""Helper for :meth:`_validate_chunk_row_in_progress`, etc."""
# No reseet with other keys
if chunk.reset_row:
_raise_if(chunk.row_key)
_raise_if(chunk.HasField('family_name'))
_raise_if(chunk.HasField('qualifier'))
_raise_if(chunk.timestamp_micros)
_raise_if(chunk.labels)
_raise_if(chunk.value_size)
_raise_if(chunk.value)
# No commit with value size
_raise_if(chunk.commit_row and chunk.value_size > 0)
# No negative value_size (inferred as a general constraint).
_raise_if(chunk.value_size < 0)
def _validate_chunk_new_row(self, chunk):
"""Helper for :meth:`_validate_chunk`."""
assert self.state == self.NEW_ROW
_raise_if(chunk.reset_row)
_raise_if(not chunk.row_key)
_raise_if(not chunk.family_name)
_raise_if(not chunk.qualifier)
# This constraint is not enforced in the Go example.
_raise_if(chunk.value_size > 0 and chunk.commit_row is not False)
# This constraint is from the Go example, not the spec.
_raise_if(self._previous_row is not None and
chunk.row_key <= self._previous_row.row_key)
def _same_as_previous(self, chunk):
"""Helper for :meth:`_validate_chunk_row_in_progress`"""
previous = self._previous_cell
return (chunk.row_key == previous.row_key and
chunk.family_name == previous.family_name and
chunk.qualifier == previous.qualifier and
chunk.labels == previous.labels)
def _validate_chunk_row_in_progress(self, chunk):
"""Helper for :meth:`_validate_chunk`"""
assert self.state == self.ROW_IN_PROGRESS
self._validate_chunk_status(chunk)
if not chunk.HasField('commit_row') and not chunk.reset_row:
_raise_if(not chunk.timestamp_micros or not chunk.value)
_raise_if(chunk.row_key and
chunk.row_key != self._row.row_key)
_raise_if(chunk.HasField('family_name') and
not chunk.HasField('qualifier'))
previous = self._previous_cell
_raise_if(self._same_as_previous(chunk) and
chunk.timestamp_micros <= previous.timestamp_micros)
def _validate_chunk_cell_in_progress(self, chunk):
"""Helper for :meth:`_validate_chunk`"""
assert self.state == self.CELL_IN_PROGRESS
self._validate_chunk_status(chunk)
self._copy_from_current(chunk)
def _validate_chunk(self, chunk):
"""Helper for :meth:`consume_next`."""
if self.state == self.NEW_ROW:
self._validate_chunk_new_row(chunk)
if self.state == self.ROW_IN_PROGRESS:
self._validate_chunk_row_in_progress(chunk)
if self.state == self.CELL_IN_PROGRESS:
self._validate_chunk_cell_in_progress(chunk)
def _save_current_cell(self):
"""Helper for :meth:`consume_next`."""
row, cell = self._row, self._cell
family = row._cells.setdefault(cell.family_name, {})
qualified = family.setdefault(cell.qualifier, [])
complete = Cell.from_pb(self._cell)
qualified.append(complete)
self._cell, self._previous_cell = None, cell
def _copy_from_current(self, chunk):
"""Helper for :meth:`consume_next`."""
current = self._cell
if current is not None:
if not chunk.row_key:
chunk.row_key = current.row_key
if not chunk.HasField('family_name'):
chunk.family_name.value = current.family_name
if not chunk.HasField('qualifier'):
chunk.qualifier.value = current.qualifier
if not chunk.timestamp_micros:
chunk.timestamp_micros = current.timestamp_micros
if not chunk.labels:
chunk.labels.extend(current.labels)
def _copy_from_previous(self, cell):
"""Helper for :meth:`consume_next`."""
previous = self._previous_cell
if previous is not None:
if not cell.row_key:
cell.row_key = previous.row_key
if not cell.family_name:
cell.family_name = previous.family_name
if not cell.qualifier:
cell.qualifier = previous.qualifier
def _save_current_row(self):
"""Helper for :meth:`consume_next`."""
if self._cell:
self._save_current_cell()
self._rows[self._row.row_key] = self._row
self._row, self._previous_row = None, self._row
self._previous_cell = None
def _raise_if(predicate, *args):
"""Helper for validation methods."""
if predicate:
raise InvalidChunk(*args)
| elibixby/gcloud-python | gcloud/bigtable/row_data.py | Python | apache-2.0 | 15,589 |
/*
* Copyright 2012 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "gazebo_config.h"
#include "gazebo/gui/TopicSelector.hh"
#include "gazebo/gui/DataLogger.hh"
#include "gazebo/gui/viewers/ViewFactory.hh"
#include "gazebo/gui/viewers/TopicView.hh"
#include "gazebo/gui/viewers/ImageView.hh"
#include "gazebo/gazebo.hh"
#include "gazebo/common/Console.hh"
#include "gazebo/common/Exception.hh"
#include "gazebo/common/Events.hh"
#include "gazebo/transport/Node.hh"
#include "gazebo/transport/Transport.hh"
#include "gazebo/rendering/UserCamera.hh"
#include "gazebo/rendering/RenderEvents.hh"
#include "gazebo/gui/Actions.hh"
#include "gazebo/gui/Gui.hh"
#include "gazebo/gui/InsertModelWidget.hh"
#include "gazebo/gui/ModelListWidget.hh"
#include "gazebo/gui/RenderWidget.hh"
#include "gazebo/gui/ToolsWidget.hh"
#include "gazebo/gui/GLWidget.hh"
#include "gazebo/gui/MainWindow.hh"
#include "gazebo/gui/GuiEvents.hh"
#include "gazebo/gui/building/BuildingEditorPalette.hh"
#include "gazebo/gui/building/EditorEvents.hh"
#include "sdf/sdf.hh"
#ifdef HAVE_QWT
#include "gazebo/gui/Diagnostics.hh"
#endif
using namespace gazebo;
using namespace gui;
extern bool g_fullscreen;
/////////////////////////////////////////////////
MainWindow::MainWindow()
: renderWidget(0)
{
this->menuBar = NULL;
this->setObjectName("mainWindow");
this->requestMsg = NULL;
this->node = transport::NodePtr(new transport::Node());
this->node->Init();
gui::set_world(this->node->GetTopicNamespace());
(void) new QShortcut(Qt::CTRL + Qt::Key_Q, this, SLOT(close()));
this->CreateActions();
this->CreateMenus();
QWidget *mainWidget = new QWidget;
QVBoxLayout *mainLayout = new QVBoxLayout;
mainWidget->show();
this->setCentralWidget(mainWidget);
this->setDockOptions(QMainWindow::AnimatedDocks);
this->modelListWidget = new ModelListWidget(this);
InsertModelWidget *insertModel = new InsertModelWidget(this);
int minimumTabWidth = 250;
this->tabWidget = new QTabWidget();
this->tabWidget->setObjectName("mainTab");
this->tabWidget->addTab(this->modelListWidget, "World");
this->tabWidget->addTab(insertModel, "Insert");
this->tabWidget->setSizePolicy(QSizePolicy::Expanding,
QSizePolicy::Expanding);
this->tabWidget->setMinimumWidth(minimumTabWidth);
this->buildingEditorPalette = new BuildingEditorPalette(this);
this->buildingEditorTabWidget = new QTabWidget();
this->buildingEditorTabWidget->setObjectName("buildingEditorTab");
this->buildingEditorTabWidget->addTab(
this->buildingEditorPalette, "Building Editor");
this->buildingEditorTabWidget->setSizePolicy(QSizePolicy::Expanding,
QSizePolicy::Expanding);
this->buildingEditorTabWidget->setMinimumWidth(minimumTabWidth);
this->buildingEditorTabWidget->hide();
this->toolsWidget = new ToolsWidget();
this->renderWidget = new RenderWidget(mainWidget);
QHBoxLayout *centerLayout = new QHBoxLayout;
QSplitter *splitter = new QSplitter(this);
splitter->addWidget(this->tabWidget);
splitter->addWidget(this->buildingEditorTabWidget);
splitter->addWidget(this->renderWidget);
splitter->addWidget(this->toolsWidget);
QList<int> sizes;
sizes.push_back(250);
sizes.push_back(250);
sizes.push_back(this->width() - 250);
sizes.push_back(0);
splitter->setSizes(sizes);
splitter->setStretchFactor(0, 0);
splitter->setStretchFactor(1, 0);
splitter->setStretchFactor(2, 2);
splitter->setStretchFactor(3, 0);
splitter->setCollapsible(2, false);
splitter->setHandleWidth(10);
centerLayout->addWidget(splitter);
centerLayout->setContentsMargins(0, 0, 0, 0);
centerLayout->setSpacing(0);
mainLayout->setSpacing(0);
mainLayout->addLayout(centerLayout, 1);
mainLayout->addWidget(new QSizeGrip(mainWidget), 0,
Qt::AlignBottom | Qt::AlignRight);
mainWidget->setLayout(mainLayout);
this->setWindowIcon(QIcon(":/images/gazebo.svg"));
std::string title = "Gazebo : ";
title += gui::get_world();
this->setWindowIconText(tr(title.c_str()));
this->setWindowTitle(tr(title.c_str()));
this->connections.push_back(
gui::Events::ConnectFullScreen(
boost::bind(&MainWindow::OnFullScreen, this, _1)));
this->connections.push_back(
gui::Events::ConnectMoveMode(
boost::bind(&MainWindow::OnMoveMode, this, _1)));
this->connections.push_back(
gui::Events::ConnectManipMode(
boost::bind(&MainWindow::OnManipMode, this, _1)));
this->connections.push_back(
event::Events::ConnectSetSelectedEntity(
boost::bind(&MainWindow::OnSetSelectedEntity, this, _1, _2)));
this->connections.push_back(
gui::editor::Events::ConnectFinishBuildingModel(
boost::bind(&MainWindow::OnFinishBuilding, this)));
gui::ViewFactory::RegisterAll();
}
/////////////////////////////////////////////////
MainWindow::~MainWindow()
{
}
/////////////////////////////////////////////////
void MainWindow::Load()
{
this->guiSub = this->node->Subscribe("~/gui", &MainWindow::OnGUI, this, true);
}
/////////////////////////////////////////////////
void MainWindow::Init()
{
this->renderWidget->show();
// Set the initial size of the window to 0.75 the desktop size,
// with a minimum value of 1024x768.
QSize winSize = QApplication::desktop()->size() * 0.75;
winSize.setWidth(std::max(1024, winSize.width()));
winSize.setHeight(std::max(768, winSize.height()));
this->resize(winSize);
this->worldControlPub =
this->node->Advertise<msgs::WorldControl>("~/world_control");
this->serverControlPub =
this->node->Advertise<msgs::ServerControl>("/gazebo/server/control");
this->selectionPub =
this->node->Advertise<msgs::Selection>("~/selection");
this->scenePub =
this->node->Advertise<msgs::Scene>("~/scene");
this->newEntitySub = this->node->Subscribe("~/model/info",
&MainWindow::OnModel, this, true);
this->statsSub =
this->node->Subscribe("~/world_stats", &MainWindow::OnStats, this);
this->requestPub = this->node->Advertise<msgs::Request>("~/request");
this->responseSub = this->node->Subscribe("~/response",
&MainWindow::OnResponse, this);
this->worldModSub = this->node->Subscribe("/gazebo/world/modify",
&MainWindow::OnWorldModify, this);
this->requestMsg = msgs::CreateRequest("entity_list");
this->requestPub->Publish(*this->requestMsg);
}
/////////////////////////////////////////////////
void MainWindow::closeEvent(QCloseEvent * /*_event*/)
{
gazebo::stop();
this->renderWidget->hide();
this->tabWidget->hide();
this->toolsWidget->hide();
this->connections.clear();
delete this->renderWidget;
}
/////////////////////////////////////////////////
void MainWindow::New()
{
msgs::ServerControl msg;
msg.set_new_world(true);
this->serverControlPub->Publish(msg);
}
/////////////////////////////////////////////////
void MainWindow::Diagnostics()
{
#ifdef HAVE_QWT
gui::Diagnostics *diag = new gui::Diagnostics(this);
diag->show();
#endif
}
/////////////////////////////////////////////////
void MainWindow::SelectTopic()
{
TopicSelector *selector = new TopicSelector(this);
selector->exec();
std::string topic = selector->GetTopic();
std::string msgType = selector->GetMsgType();
delete selector;
if (!topic.empty())
{
TopicView *view = ViewFactory::NewView(msgType, topic, this);
if (view)
view->show();
else
gzerr << "Unable to create viewer for message type[" << msgType << "]\n";
}
}
/////////////////////////////////////////////////
void MainWindow::Open()
{
std::string filename = QFileDialog::getOpenFileName(this,
tr("Open World"), "",
tr("SDF Files (*.xml *.sdf *.world)")).toStdString();
if (!filename.empty())
{
msgs::ServerControl msg;
msg.set_open_filename(filename);
this->serverControlPub->Publish(msg);
}
}
/////////////////////////////////////////////////
void MainWindow::Import()
{
std::string filename = QFileDialog::getOpenFileName(this,
tr("Import Collada Mesh"), "",
tr("SDF Files (*.dae *.zip)")).toStdString();
if (!filename.empty())
{
if (filename.find(".dae") != std::string::npos)
{
gui::Events::createEntity("mesh", filename);
}
else
gzerr << "Unable to import mesh[" << filename << "]\n";
}
}
/////////////////////////////////////////////////
void MainWindow::SaveAs()
{
std::string filename = QFileDialog::getSaveFileName(this,
tr("Save World"), QString(),
tr("SDF Files (*.xml *.sdf *.world)")).toStdString();
// Return if the user has canceled.
if (filename.empty())
return;
g_saveAct->setEnabled(true);
this->saveFilename = filename;
this->Save();
}
/////////////////////////////////////////////////
void MainWindow::Save()
{
// Get the latest world in SDF.
boost::shared_ptr<msgs::Response> response =
transport::request(get_world(), "world_sdf");
msgs::GzString msg;
std::string msgData;
// Make sure the response is correct
if (response->response() != "error" && response->type() == msg.GetTypeName())
{
// Parse the response message
msg.ParseFromString(response->serialized_data());
// Parse the string into sdf, so that we can insert user camera settings.
sdf::SDF sdf_parsed;
sdf_parsed.SetFromString(msg.data());
// Check that sdf contains world
if (sdf_parsed.root->HasElement("world"))
{
sdf::ElementPtr world = sdf_parsed.root->GetElement("world");
sdf::ElementPtr guiElem = world->GetElement("gui");
if (guiElem->HasAttribute("fullscreen"))
guiElem->GetAttribute("fullscreen")->Set(g_fullscreen);
sdf::ElementPtr cameraElem = guiElem->GetElement("camera");
rendering::UserCameraPtr cam = gui::get_active_camera();
cameraElem->GetElement("pose")->Set(cam->GetWorldPose());
cameraElem->GetElement("view_controller")->Set(
cam->GetViewControllerTypeString());
// TODO: export track_visual properties as well.
msgData = sdf_parsed.root->ToString("");
}
else
{
msgData = msg.data();
gzerr << "Unable to parse world file to add user camera settings.\n";
}
// Open the file
std::ofstream out(this->saveFilename.c_str(), std::ios::out);
if (!out)
{
QMessageBox msgBox;
std::string str = "Unable to open file: " + this->saveFilename + "\n";
str += "Check file permissions.";
msgBox.setText(str.c_str());
msgBox.exec();
}
else
out << msgData;
out.close();
}
else
{
QMessageBox msgBox;
msgBox.setText("Unable to save world.\n"
"Unable to retrieve SDF world description from server.");
msgBox.exec();
}
}
/////////////////////////////////////////////////
void MainWindow::About()
{
std::string helpTxt;
helpTxt = "<table>"
"<tr><td style='padding-right:20px'>"
"<img src=':images/gazebo_neg_60x71.png'/></td>"
"<td>";
helpTxt += GAZEBO_VERSION_HEADER;
helpTxt += "</td></tr></table>";
helpTxt += "<div style='margin-left: 10px'>"
"<div>"
"<table>"
"<tr>"
"<td style='padding-right: 10px;'>Tutorials:</td>"
"<td><a href='http://gazebosim.org/wiki/tutorials' "
"style='text-decoration: none; color: #f58113'>"
"http://gazebosim.org/wiki/tutorials</a></td>"
"</tr>"
"<tr>"
"<td style='padding-right: 10px;'>User Guide:</td>"
"<td><a href='http://gazebosim.org/user_guide' "
"style='text-decoration: none; color: #f58113'>"
"http://gazebosim.org/user_guide</a></td>"
"</tr>"
"<tr>"
"<td style='padding-right: 10px;'>API:</td>"
"<td><a href='http://gazebosim.org/api' "
"style='text-decoration: none; color: #f58113'>"
"http://gazebosim.org/api</a></td>"
"</tr>"
"<tr>"
"<td style='padding-right: 10px;'>SDF:</td>"
"<td><a href='http://gazebosim.org/sdf' "
"style='text-decoration: none; color: #f58113'>"
"http://gazebosim.org/sdf</a></td>"
"</tr>"
"<tr>"
"<td style='padding-right: 10px;'>Messages:</td>"
"<td><a href='http://gazebosim.org/msgs' "
"style='text-decoration: none; color: #f58113'>"
"http://gazebosim.org/msgs</a></td>"
"</tr>"
"</table>"
"</div>";
QPixmap icon(":images/gazebo_neg_60x71.png");
QMessageBox aboutBox(this);
aboutBox.setWindowTitle("About Gazebo");
aboutBox.setTextFormat(Qt::RichText);
aboutBox.setText(QString::fromStdString(helpTxt));
aboutBox.exec();
}
/////////////////////////////////////////////////
void MainWindow::Play()
{
msgs::WorldControl msg;
msg.set_pause(false);
g_pauseAct->setChecked(false);
this->worldControlPub->Publish(msg);
}
/////////////////////////////////////////////////
void MainWindow::Pause()
{
msgs::WorldControl msg;
msg.set_pause(true);
g_playAct->setChecked(false);
this->worldControlPub->Publish(msg);
}
/////////////////////////////////////////////////
void MainWindow::Step()
{
msgs::WorldControl msg;
msg.set_step(true);
this->worldControlPub->Publish(msg);
}
/////////////////////////////////////////////////
void MainWindow::NewModel()
{
/*ModelBuilderWidget *modelBuilder = new ModelBuilderWidget();
modelBuilder->Init();
modelBuilder->show();
modelBuilder->resize(800, 600);
*/
}
/////////////////////////////////////////////////
void MainWindow::OnResetModelOnly()
{
msgs::WorldControl msg;
msg.mutable_reset()->set_all(false);
msg.mutable_reset()->set_time_only(false);
msg.mutable_reset()->set_model_only(true);
this->worldControlPub->Publish(msg);
}
/////////////////////////////////////////////////
void MainWindow::OnResetWorld()
{
msgs::WorldControl msg;
msg.mutable_reset()->set_all(true);
this->worldControlPub->Publish(msg);
}
/////////////////////////////////////////////////
void MainWindow::OnEditBuilding()
{
bool isChecked = g_editBuildingAct->isChecked();
if (isChecked)
{
this->Pause();
this->renderWidget->ShowEditor(true);
this->tabWidget->hide();
this->buildingEditorTabWidget->show();
this->AttachEditorMenuBar();
}
else
{
this->renderWidget->ShowEditor(false);
this->tabWidget->show();
this->buildingEditorTabWidget->hide();
this->AttachMainMenuBar();
this->Play();
}
}
/////////////////////////////////////////////////
void MainWindow::Arrow()
{
gui::Events::manipMode("select");
}
/////////////////////////////////////////////////
void MainWindow::Translate()
{
gui::Events::manipMode("translate");
}
/////////////////////////////////////////////////
void MainWindow::Rotate()
{
gui::Events::manipMode("rotate");
}
/////////////////////////////////////////////////
void MainWindow::CreateBox()
{
g_arrowAct->setChecked(true);
gui::Events::createEntity("box", "");
}
/////////////////////////////////////////////////
void MainWindow::CreateSphere()
{
g_arrowAct->setChecked(true);
gui::Events::createEntity("sphere", "");
}
/////////////////////////////////////////////////
void MainWindow::CreateCylinder()
{
g_arrowAct->setChecked(true);
gui::Events::createEntity("cylinder", "");
}
/////////////////////////////////////////////////
void MainWindow::CreateMesh()
{
g_arrowAct->setChecked(true);
gui::Events::createEntity("mesh", "mesh");
}
/////////////////////////////////////////////////
void MainWindow::CreatePointLight()
{
g_arrowAct->setChecked(true);
gui::Events::createEntity("pointlight", "");
}
/////////////////////////////////////////////////
void MainWindow::CreateSpotLight()
{
g_arrowAct->setChecked(true);
gui::Events::createEntity("spotlight", "");
}
/////////////////////////////////////////////////
void MainWindow::CreateDirectionalLight()
{
g_arrowAct->setChecked(true);
gui::Events::createEntity("directionallight", "");
}
/////////////////////////////////////////////////
void MainWindow::CaptureScreenshot()
{
rendering::UserCameraPtr cam = gui::get_active_camera();
cam->SetCaptureDataOnce();
this->renderWidget->DisplayOverlayMsg(
"Screenshot saved in: " + cam->GetScreenshotPath(), 2000);
}
/////////////////////////////////////////////////
void MainWindow::InsertModel()
{
}
/////////////////////////////////////////////////
void MainWindow::OnFullScreen(bool _value)
{
if (_value)
{
this->showFullScreen();
this->renderWidget->showFullScreen();
this->tabWidget->hide();
this->toolsWidget->hide();
this->menuBar->hide();
}
else
{
this->showNormal();
this->renderWidget->showNormal();
if (!g_editBuildingAct->isChecked())
this->tabWidget->show();
this->toolsWidget->show();
this->menuBar->show();
}
}
/////////////////////////////////////////////////
void MainWindow::Reset()
{
rendering::UserCameraPtr cam = gui::get_active_camera();
math::Vector3 camPos(5, -5, 2);
math::Vector3 lookAt(0, 0, 0);
math::Vector3 delta = camPos - lookAt;
double yaw = atan2(delta.x, delta.y);
double pitch = atan2(delta.z, sqrt(delta.x*delta.x + delta.y*delta.y));
cam->SetWorldPose(math::Pose(camPos, math::Vector3(0, pitch, yaw)));
}
/////////////////////////////////////////////////
void MainWindow::ShowCollisions()
{
if (g_showCollisionsAct->isChecked())
transport::requestNoReply(this->node->GetTopicNamespace(),
"show_collision", "all");
else
transport::requestNoReply(this->node->GetTopicNamespace(),
"hide_collision", "all");
}
/////////////////////////////////////////////////
void MainWindow::ShowGrid()
{
msgs::Scene msg;
msg.set_name("default");
msg.set_grid(g_showGridAct->isChecked());
this->scenePub->Publish(msg);
}
/////////////////////////////////////////////////
void MainWindow::ShowJoints()
{
if (g_showJointsAct->isChecked())
transport::requestNoReply(this->node->GetTopicNamespace(),
"show_joints", "all");
else
transport::requestNoReply(this->node->GetTopicNamespace(),
"hide_joints", "all");
}
/////////////////////////////////////////////////
void MainWindow::SetTransparent()
{
if (g_transparentAct->isChecked())
transport::requestNoReply(this->node->GetTopicNamespace(),
"set_transparent", "all");
else
transport::requestNoReply(this->node->GetTopicNamespace(),
"set_opaque", "all");
}
/////////////////////////////////////////////////
void MainWindow::SetWireframe()
{
if (g_viewWireframeAct->isChecked())
transport::requestNoReply(this->node->GetTopicNamespace(),
"set_wireframe", "all");
else
transport::requestNoReply(this->node->GetTopicNamespace(),
"set_solid", "all");
}
/////////////////////////////////////////////////
void MainWindow::ShowCOM()
{
if (g_showCOMAct->isChecked())
transport::requestNoReply(this->node->GetTopicNamespace(),
"show_com", "all");
else
transport::requestNoReply(this->node->GetTopicNamespace(),
"hide_com", "all");
}
/////////////////////////////////////////////////
void MainWindow::ShowContacts()
{
if (g_showContactsAct->isChecked())
transport::requestNoReply(this->node->GetTopicNamespace(),
"show_contact", "all");
else
transport::requestNoReply(this->node->GetTopicNamespace(),
"hide_contact", "all");
}
/////////////////////////////////////////////////
void MainWindow::FullScreen()
{
g_fullscreen = !g_fullscreen;
gui::Events::fullScreen(g_fullscreen);
}
/////////////////////////////////////////////////
void MainWindow::FPS()
{
gui::Events::fps();
}
/////////////////////////////////////////////////
void MainWindow::Orbit()
{
gui::Events::orbit();
}
/////////////////////////////////////////////////
void MainWindow::DataLogger()
{
gui::DataLogger *dataLogger = new gui::DataLogger(this);
dataLogger->show();
}
////////////////////////////////////////////////
void MainWindow::BuildingEditorSave()
{
gui::editor::Events::saveBuildingEditor();
}
/////////////////////////////////////////////////
void MainWindow::BuildingEditorDiscard()
{
gui::editor::Events::discardBuildingEditor();
}
/////////////////////////////////////////////////
void MainWindow::BuildingEditorDone()
{
gui::editor::Events::doneBuildingEditor();
}
/////////////////////////////////////////////////
void MainWindow::BuildingEditorExit()
{
gui::editor::Events::exitBuildingEditor();
}
/////////////////////////////////////////////////
void MainWindow::CreateActions()
{
/*g_newAct = new QAction(tr("&New World"), this);
g_newAct->setShortcut(tr("Ctrl+N"));
g_newAct->setStatusTip(tr("Create a new world"));
connect(g_newAct, SIGNAL(triggered()), this, SLOT(New()));
*/
g_topicVisAct = new QAction(tr("Topic Visualization"), this);
g_topicVisAct->setShortcut(tr("Ctrl+T"));
g_topicVisAct->setStatusTip(tr("Select a topic to visualize"));
connect(g_topicVisAct, SIGNAL(triggered()), this, SLOT(SelectTopic()));
#ifdef HAVE_QWT
/*g_diagnosticsAct = new QAction(tr("Diagnostic Plot"), this);
g_diagnosticsAct->setShortcut(tr("Ctrl+U"));
g_diagnosticsAct->setStatusTip(tr("Plot diagnostic information"));
connect(g_diagnosticsAct, SIGNAL(triggered()), this, SLOT(Diagnostics()));
*/
#endif
g_openAct = new QAction(tr("&Open World"), this);
g_openAct->setShortcut(tr("Ctrl+O"));
g_openAct->setStatusTip(tr("Open an world file"));
connect(g_openAct, SIGNAL(triggered()), this, SLOT(Open()));
/*g_importAct = new QAction(tr("&Import Mesh"), this);
g_importAct->setShortcut(tr("Ctrl+I"));
g_importAct->setStatusTip(tr("Import a Collada mesh"));
connect(g_importAct, SIGNAL(triggered()), this, SLOT(Import()));
*/
g_saveAct = new QAction(tr("&Save World"), this);
g_saveAct->setShortcut(tr("Ctrl+S"));
g_saveAct->setStatusTip(tr("Save world"));
g_saveAct->setEnabled(false);
connect(g_saveAct, SIGNAL(triggered()), this, SLOT(Save()));
g_saveAsAct = new QAction(tr("Save World &As"), this);
g_saveAsAct->setShortcut(tr("Ctrl+Shift+S"));
g_saveAsAct->setStatusTip(tr("Save world to new file"));
connect(g_saveAsAct, SIGNAL(triggered()), this, SLOT(SaveAs()));
g_aboutAct = new QAction(tr("&About"), this);
g_aboutAct->setStatusTip(tr("Show the about info"));
connect(g_aboutAct, SIGNAL(triggered()), this, SLOT(About()));
g_quitAct = new QAction(tr("&Quit"), this);
g_quitAct->setStatusTip(tr("Quit"));
connect(g_quitAct, SIGNAL(triggered()), this, SLOT(close()));
g_newModelAct = new QAction(tr("New &Model"), this);
g_newModelAct->setShortcut(tr("Ctrl+M"));
g_newModelAct->setStatusTip(tr("Create a new model"));
connect(g_newModelAct, SIGNAL(triggered()), this, SLOT(NewModel()));
g_resetModelsAct = new QAction(tr("&Reset Model Poses"), this);
g_resetModelsAct->setShortcut(tr("Ctrl+Shift+R"));
g_resetModelsAct->setStatusTip(tr("Reset model poses"));
connect(g_resetModelsAct, SIGNAL(triggered()), this,
SLOT(OnResetModelOnly()));
g_resetWorldAct = new QAction(tr("&Reset World"), this);
g_resetWorldAct->setShortcut(tr("Ctrl+R"));
g_resetWorldAct->setStatusTip(tr("Reset the world"));
connect(g_resetWorldAct, SIGNAL(triggered()), this, SLOT(OnResetWorld()));
g_editBuildingAct = new QAction(tr("&Building Editor"), this);
g_editBuildingAct->setShortcut(tr("Ctrl+B"));
g_editBuildingAct->setStatusTip(tr("Enter Building Editor Mode"));
g_editBuildingAct->setCheckable(true);
g_editBuildingAct->setChecked(false);
connect(g_editBuildingAct, SIGNAL(triggered()), this, SLOT(OnEditBuilding()));
g_playAct = new QAction(QIcon(":/images/play.png"), tr("Play"), this);
g_playAct->setStatusTip(tr("Run the world"));
g_playAct->setCheckable(true);
g_playAct->setChecked(true);
connect(g_playAct, SIGNAL(triggered()), this, SLOT(Play()));
g_pauseAct = new QAction(QIcon(":/images/pause.png"), tr("Pause"), this);
g_pauseAct->setStatusTip(tr("Pause the world"));
g_pauseAct->setCheckable(true);
g_pauseAct->setChecked(false);
connect(g_pauseAct, SIGNAL(triggered()), this, SLOT(Pause()));
g_stepAct = new QAction(QIcon(":/images/end.png"), tr("Step"), this);
g_stepAct->setStatusTip(tr("Step the world"));
connect(g_stepAct, SIGNAL(triggered()), this, SLOT(Step()));
g_arrowAct = new QAction(QIcon(":/images/arrow.png"),
tr("Selection Mode"), this);
g_arrowAct->setStatusTip(tr("Move camera"));
g_arrowAct->setCheckable(true);
g_arrowAct->setChecked(true);
connect(g_arrowAct, SIGNAL(triggered()), this, SLOT(Arrow()));
g_translateAct = new QAction(QIcon(":/images/translate.png"),
tr("Translation Mode"), this);
g_translateAct->setStatusTip(tr("Translate an object"));
g_translateAct->setCheckable(true);
g_translateAct->setChecked(false);
connect(g_translateAct, SIGNAL(triggered()), this, SLOT(Translate()));
g_rotateAct = new QAction(QIcon(":/images/rotate.png"),
tr("Rotation Mode"), this);
g_rotateAct->setStatusTip(tr("Rotate an object"));
g_rotateAct->setCheckable(true);
g_rotateAct->setChecked(false);
connect(g_rotateAct, SIGNAL(triggered()), this, SLOT(Rotate()));
g_boxCreateAct = new QAction(QIcon(":/images/box.png"), tr("Box"), this);
g_boxCreateAct->setStatusTip(tr("Create a box"));
g_boxCreateAct->setCheckable(true);
connect(g_boxCreateAct, SIGNAL(triggered()), this, SLOT(CreateBox()));
g_sphereCreateAct = new QAction(QIcon(":/images/sphere.png"),
tr("Sphere"), this);
g_sphereCreateAct->setStatusTip(tr("Create a sphere"));
g_sphereCreateAct->setCheckable(true);
connect(g_sphereCreateAct, SIGNAL(triggered()), this,
SLOT(CreateSphere()));
g_cylinderCreateAct = new QAction(QIcon(":/images/cylinder.png"),
tr("Cylinder"), this);
g_cylinderCreateAct->setStatusTip(tr("Create a sphere"));
g_cylinderCreateAct->setCheckable(true);
connect(g_cylinderCreateAct, SIGNAL(triggered()), this,
SLOT(CreateCylinder()));
g_meshCreateAct = new QAction(QIcon(":/images/cylinder.png"),
tr("Mesh"), this);
g_meshCreateAct->setStatusTip(tr("Create a mesh"));
g_meshCreateAct->setCheckable(true);
connect(g_meshCreateAct, SIGNAL(triggered()), this,
SLOT(CreateMesh()));
g_pointLghtCreateAct = new QAction(QIcon(":/images/pointlight.png"),
tr("Point Light"), this);
g_pointLghtCreateAct->setStatusTip(tr("Create a point light"));
g_pointLghtCreateAct->setCheckable(true);
connect(g_pointLghtCreateAct, SIGNAL(triggered()), this,
SLOT(CreatePointLight()));
g_spotLghtCreateAct = new QAction(QIcon(":/images/spotlight.png"),
tr("Spot Light"), this);
g_spotLghtCreateAct->setStatusTip(tr("Create a spot light"));
g_spotLghtCreateAct->setCheckable(true);
connect(g_spotLghtCreateAct, SIGNAL(triggered()), this,
SLOT(CreateSpotLight()));
g_dirLghtCreateAct = new QAction(QIcon(":/images/directionallight.png"),
tr("Directional Light"), this);
g_dirLghtCreateAct->setStatusTip(tr("Create a directional light"));
g_dirLghtCreateAct->setCheckable(true);
connect(g_dirLghtCreateAct, SIGNAL(triggered()), this,
SLOT(CreateDirectionalLight()));
g_resetAct = new QAction(tr("Reset Camera"), this);
g_resetAct->setStatusTip(tr("Move camera to pose"));
connect(g_resetAct, SIGNAL(triggered()), this,
SLOT(Reset()));
g_showCollisionsAct = new QAction(tr("Collisions"), this);
g_showCollisionsAct->setStatusTip(tr("Show Collisions"));
g_showCollisionsAct->setCheckable(true);
g_showCollisionsAct->setChecked(false);
connect(g_showCollisionsAct, SIGNAL(triggered()), this,
SLOT(ShowCollisions()));
g_showGridAct = new QAction(tr("Grid"), this);
g_showGridAct->setStatusTip(tr("Show Grid"));
g_showGridAct->setCheckable(true);
g_showGridAct->setChecked(true);
connect(g_showGridAct, SIGNAL(triggered()), this,
SLOT(ShowGrid()));
g_transparentAct = new QAction(tr("Transparent"), this);
g_transparentAct->setStatusTip(tr("Transparent"));
g_transparentAct->setCheckable(true);
g_transparentAct->setChecked(false);
connect(g_transparentAct, SIGNAL(triggered()), this,
SLOT(SetTransparent()));
g_viewWireframeAct = new QAction(tr("Wireframe"), this);
g_viewWireframeAct->setStatusTip(tr("Wireframe"));
g_viewWireframeAct->setCheckable(true);
g_viewWireframeAct->setChecked(false);
connect(g_viewWireframeAct, SIGNAL(triggered()), this,
SLOT(SetWireframe()));
g_showCOMAct = new QAction(tr("Center of Mass"), this);
g_showCOMAct->setStatusTip(tr("Show COM"));
g_showCOMAct->setCheckable(true);
g_showCOMAct->setChecked(false);
connect(g_showCOMAct, SIGNAL(triggered()), this,
SLOT(ShowCOM()));
g_showContactsAct = new QAction(tr("Contacts"), this);
g_showContactsAct->setStatusTip(tr("Show Contacts"));
g_showContactsAct->setCheckable(true);
g_showContactsAct->setChecked(false);
connect(g_showContactsAct, SIGNAL(triggered()), this,
SLOT(ShowContacts()));
g_showJointsAct = new QAction(tr("Joints"), this);
g_showJointsAct->setStatusTip(tr("Show Joints"));
g_showJointsAct->setCheckable(true);
g_showJointsAct->setChecked(false);
connect(g_showJointsAct, SIGNAL(triggered()), this,
SLOT(ShowJoints()));
g_fullScreenAct = new QAction(tr("Full Screen"), this);
g_fullScreenAct->setStatusTip(tr("Full Screen(F-11 to exit)"));
connect(g_fullScreenAct, SIGNAL(triggered()), this,
SLOT(FullScreen()));
// g_fpsAct = new QAction(tr("FPS View Control"), this);
// g_fpsAct->setStatusTip(tr("First Person Shooter View Style"));
// connect(g_fpsAct, SIGNAL(triggered()), this, SLOT(FPS()));
g_orbitAct = new QAction(tr("Orbit View Control"), this);
g_orbitAct->setStatusTip(tr("Orbit View Style"));
connect(g_orbitAct, SIGNAL(triggered()), this, SLOT(Orbit()));
g_dataLoggerAct = new QAction(tr("&Log Data"), this);
g_dataLoggerAct->setShortcut(tr("Ctrl+D"));
g_dataLoggerAct->setStatusTip(tr("Data Logging Utility"));
connect(g_dataLoggerAct, SIGNAL(triggered()), this, SLOT(DataLogger()));
g_buildingEditorSaveAct = new QAction(tr("&Save (As)"), this);
g_buildingEditorSaveAct->setStatusTip(tr("Save (As)"));
g_buildingEditorSaveAct->setShortcut(tr("Ctrl+S"));
g_buildingEditorSaveAct->setCheckable(false);
connect(g_buildingEditorSaveAct, SIGNAL(triggered()), this,
SLOT(BuildingEditorSave()));
g_buildingEditorDiscardAct = new QAction(tr("&Discard"), this);
g_buildingEditorDiscardAct->setStatusTip(tr("Discard"));
g_buildingEditorDiscardAct->setShortcut(tr("Ctrl+D"));
g_buildingEditorDiscardAct->setCheckable(false);
connect(g_buildingEditorDiscardAct, SIGNAL(triggered()), this,
SLOT(BuildingEditorDiscard()));
g_buildingEditorDoneAct = new QAction(tr("Don&e"), this);
g_buildingEditorDoneAct->setShortcut(tr("Ctrl+E"));
g_buildingEditorDoneAct->setStatusTip(tr("Done"));
g_buildingEditorDoneAct->setCheckable(false);
connect(g_buildingEditorDoneAct, SIGNAL(triggered()), this,
SLOT(BuildingEditorDone()));
g_buildingEditorExitAct = new QAction(tr("E&xit Building Editor"), this);
g_buildingEditorExitAct->setStatusTip(tr("Exit Building Editor"));
g_buildingEditorExitAct->setShortcut(tr("Ctrl+X"));
g_buildingEditorExitAct->setCheckable(false);
connect(g_buildingEditorExitAct, SIGNAL(triggered()), this,
SLOT(BuildingEditorExit()));
g_screenshotAct = new QAction(QIcon(":/images/screenshot.png"),
tr("Screenshot"), this);
g_screenshotAct->setStatusTip(tr("Take a screenshot"));
connect(g_screenshotAct, SIGNAL(triggered()), this,
SLOT(CaptureScreenshot()));
}
/////////////////////////////////////////////////
void MainWindow::AttachEditorMenuBar()
{
if (this->menuBar)
{
this->menuLayout->removeWidget(this->menuBar);
delete this->menuBar;
}
this->menuBar = new QMenuBar;
this->menuBar->setSizePolicy(QSizePolicy::Fixed,
QSizePolicy::Fixed);
QMenu *buildingEditorFileMenu = this->menuBar->addMenu(
tr("&File"));
buildingEditorFileMenu->addAction(g_buildingEditorSaveAct);
buildingEditorFileMenu->addAction(g_buildingEditorDiscardAct);
buildingEditorFileMenu->addAction(g_buildingEditorDoneAct);
buildingEditorFileMenu->addAction(g_buildingEditorExitAct);
this->menuLayout->setMenuBar(this->menuBar);
}
/////////////////////////////////////////////////
void MainWindow::AttachMainMenuBar()
{
if (this->menuBar)
{
this->menuLayout->removeWidget(this->menuBar);
delete this->menuBar;
}
this->menuBar = new QMenuBar;
this->menuBar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
QMenu *fileMenu = this->menuBar->addMenu(tr("&File"));
// fileMenu->addAction(g_openAct);
// fileMenu->addAction(g_importAct);
// fileMenu->addAction(g_newAct);
fileMenu->addAction(g_saveAct);
fileMenu->addAction(g_saveAsAct);
fileMenu->addSeparator();
fileMenu->addAction(g_quitAct);
QMenu *editMenu = this->menuBar->addMenu(tr("&Edit"));
editMenu->addAction(g_resetModelsAct);
editMenu->addAction(g_resetWorldAct);
editMenu->addAction(g_editBuildingAct);
QMenu *viewMenu = this->menuBar->addMenu(tr("&View"));
viewMenu->addAction(g_showGridAct);
viewMenu->addSeparator();
viewMenu->addAction(g_transparentAct);
viewMenu->addAction(g_viewWireframeAct);
viewMenu->addSeparator();
viewMenu->addAction(g_showCollisionsAct);
viewMenu->addAction(g_showJointsAct);
viewMenu->addAction(g_showCOMAct);
viewMenu->addAction(g_showContactsAct);
viewMenu->addSeparator();
viewMenu->addAction(g_resetAct);
viewMenu->addAction(g_fullScreenAct);
viewMenu->addSeparator();
// viewMenu->addAction(g_fpsAct);
viewMenu->addAction(g_orbitAct);
QMenu *windowMenu = this->menuBar->addMenu(tr("&Window"));
windowMenu->addAction(g_topicVisAct);
windowMenu->addSeparator();
windowMenu->addAction(g_dataLoggerAct);
#ifdef HAVE_QWT
// windowMenu->addAction(g_diagnosticsAct);
#endif
this->menuBar->addSeparator();
QMenu *helpMenu = this->menuBar->addMenu(tr("&Help"));
helpMenu->addAction(g_aboutAct);
this->menuLayout->setMenuBar(this->menuBar);
}
/////////////////////////////////////////////////
void MainWindow::CreateMenus()
{
this->menuLayout = new QHBoxLayout;
QFrame *frame = new QFrame;
this->AttachMainMenuBar();
this->menuLayout->addStretch(5);
this->menuLayout->setContentsMargins(0, 0, 0, 0);
frame->setLayout(this->menuLayout);
frame->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
this->setMenuWidget(frame);
}
/////////////////////////////////////////////////
void MainWindow::CreateToolbars()
{
this->playToolbar = this->addToolBar(tr("Play"));
this->playToolbar->addAction(g_playAct);
this->playToolbar->addAction(g_pauseAct);
this->playToolbar->addAction(g_stepAct);
}
/////////////////////////////////////////////////
void MainWindow::OnMoveMode(bool _mode)
{
if (_mode)
{
g_boxCreateAct->setChecked(false);
g_sphereCreateAct->setChecked(false);
g_cylinderCreateAct->setChecked(false);
g_meshCreateAct->setChecked(false);
g_pointLghtCreateAct->setChecked(false);
g_spotLghtCreateAct->setChecked(false);
g_dirLghtCreateAct->setChecked(false);
}
}
/////////////////////////////////////////////////
void MainWindow::OnGUI(ConstGUIPtr &_msg)
{
if (_msg->has_fullscreen() && _msg->fullscreen())
{
this->FullScreen();
}
if (_msg->has_camera())
{
rendering::UserCameraPtr cam = gui::get_active_camera();
if (_msg->camera().has_pose())
{
const msgs::Pose &msg_pose = _msg->camera().pose();
math::Vector3 cam_pose_pos = math::Vector3(
msg_pose.position().x(),
msg_pose.position().y(),
msg_pose.position().z());
math::Quaternion cam_pose_rot = math::Quaternion(
msg_pose.orientation().w(),
msg_pose.orientation().x(),
msg_pose.orientation().y(),
msg_pose.orientation().z());
math::Pose cam_pose(cam_pose_pos, cam_pose_rot);
cam->SetWorldPose(cam_pose);
}
if (_msg->camera().has_view_controller())
{
cam->SetViewController(_msg->camera().view_controller());
}
if (_msg->camera().has_track())
{
std::string name = _msg->camera().track().name();
double minDist = 0.0;
double maxDist = 0.0;
if (_msg->camera().track().has_min_dist())
minDist = _msg->camera().track().min_dist();
if (_msg->camera().track().has_max_dist())
maxDist = _msg->camera().track().max_dist();
cam->AttachToVisual(name, false, minDist, maxDist);
}
}
}
/////////////////////////////////////////////////
void MainWindow::OnModel(ConstModelPtr &_msg)
{
this->entities[_msg->name()] = _msg->id();
for (int i = 0; i < _msg->link_size(); i++)
{
this->entities[_msg->link(i).name()] = _msg->link(i).id();
for (int j = 0; j < _msg->link(i).collision_size(); j++)
{
this->entities[_msg->link(i).collision(j).name()] =
_msg->link(i).collision(j).id();
}
}
gui::Events::modelUpdate(*_msg);
}
/////////////////////////////////////////////////
void MainWindow::OnResponse(ConstResponsePtr &_msg)
{
if (!this->requestMsg || _msg->id() != this->requestMsg->id())
return;
msgs::Model_V modelVMsg;
if (_msg->has_type() && _msg->type() == modelVMsg.GetTypeName())
{
modelVMsg.ParseFromString(_msg->serialized_data());
for (int i = 0; i < modelVMsg.models_size(); i++)
{
this->entities[modelVMsg.models(i).name()] = modelVMsg.models(i).id();
for (int j = 0; j < modelVMsg.models(i).link_size(); j++)
{
this->entities[modelVMsg.models(i).link(j).name()] =
modelVMsg.models(i).link(j).id();
for (int k = 0; k < modelVMsg.models(i).link(j).collision_size(); k++)
{
this->entities[modelVMsg.models(i).link(j).collision(k).name()] =
modelVMsg.models(i).link(j).collision(k).id();
}
}
gui::Events::modelUpdate(modelVMsg.models(i));
}
}
delete this->requestMsg;
this->requestMsg = NULL;
}
/////////////////////////////////////////////////
unsigned int MainWindow::GetEntityId(const std::string &_name)
{
unsigned int result = 0;
std::string name = _name;
boost::replace_first(name, gui::get_world()+"::", "");
std::map<std::string, unsigned int>::iterator iter;
iter = this->entities.find(name);
if (iter != this->entities.end())
result = iter->second;
return result;
}
/////////////////////////////////////////////////
bool MainWindow::HasEntityName(const std::string &_name)
{
bool result = false;
std::string name = _name;
boost::replace_first(name, gui::get_world()+"::", "");
std::map<std::string, unsigned int>::iterator iter;
iter = this->entities.find(name);
if (iter != this->entities.end())
result = true;
return result;
}
/////////////////////////////////////////////////
void MainWindow::OnWorldModify(ConstWorldModifyPtr &_msg)
{
if (_msg->has_create() && _msg->create())
{
this->renderWidget->CreateScene(_msg->world_name());
this->requestMsg = msgs::CreateRequest("entity_list");
this->requestPub->Publish(*this->requestMsg);
}
else if (_msg->has_remove() && _msg->remove())
this->renderWidget->RemoveScene(_msg->world_name());
}
/////////////////////////////////////////////////
void MainWindow::OnManipMode(const std::string &_mode)
{
if (_mode == "select" || _mode == "make_entity")
g_arrowAct->setChecked(true);
}
/////////////////////////////////////////////////
void MainWindow::OnSetSelectedEntity(const std::string &_name,
const std::string &/*_mode*/)
{
if (!_name.empty())
{
this->tabWidget->setCurrentIndex(0);
}
}
/////////////////////////////////////////////////
void MainWindow::OnStats(ConstWorldStatisticsPtr &_msg)
{
if (_msg->paused() && g_playAct->isChecked())
{
g_playAct->setChecked(false);
g_pauseAct->setChecked(true);
}
else if (!_msg->paused() && !g_playAct->isChecked())
{
g_playAct->setChecked(true);
g_pauseAct->setChecked(false);
}
}
/////////////////////////////////////////////////
void MainWindow::OnFinishBuilding()
{
g_editBuildingAct->setChecked(!g_editBuildingAct->isChecked());
this->OnEditBuilding();
}
/////////////////////////////////////////////////
void MainWindow::ItemSelected(QTreeWidgetItem *_item, int)
{
_item->setExpanded(!_item->isExpanded());
}
/////////////////////////////////////////////////
TreeViewDelegate::TreeViewDelegate(QTreeView *_view, QWidget *_parent)
: QItemDelegate(_parent), view(_view)
{
}
/////////////////////////////////////////////////
void TreeViewDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
const QAbstractItemModel *model = index.model();
Q_ASSERT(model);
if (!model->parent(index).isValid())
{
QRect r = option.rect;
QColor orange(245, 129, 19);
QColor blue(71, 99, 183);
QColor grey(100, 100, 100);
if (option.state & QStyle::State_Open ||
option.state & QStyle::State_MouseOver)
{
painter->setPen(blue);
painter->setBrush(QBrush(blue));
}
else
{
painter->setPen(grey);
painter->setBrush(QBrush(grey));
}
if (option.state & QStyle::State_Open)
painter->drawLine(r.left()+8, r.top() + (r.height()*0.5 - 5),
r.left()+8, r.top() + r.height()-1);
painter->save();
painter->setRenderHints(QPainter::Antialiasing |
QPainter::TextAntialiasing);
painter->drawRoundedRect(r.left()+4, r.top() + (r.height()*0.5 - 5),
10, 10, 20.0, 10.0, Qt::RelativeSize);
// draw text
QRect textrect = QRect(r.left() + 20, r.top(),
r.width() - 40,
r.height());
QString text = elidedText(
option.fontMetrics,
textrect.width(),
Qt::ElideMiddle,
model->data(index, Qt::DisplayRole).toString());
if (option.state & QStyle::State_MouseOver)
painter->setPen(QPen(orange, 1));
else
painter->setPen(QPen(grey, 1));
this->view->style()->drawItemText(painter, textrect, Qt::AlignLeft,
option.palette, this->view->isEnabled(), text);
painter->restore();
}
else
{
QItemDelegate::paint(painter, option, index);
}
}
/////////////////////////////////////////////////
QSize TreeViewDelegate::sizeHint(const QStyleOptionViewItem &_opt,
const QModelIndex &_index) const
{
QStyleOptionViewItem option = _opt;
QSize sz = QItemDelegate::sizeHint(_opt, _index) + QSize(2, 2);
return sz;
}
| thomas-moulard/gazebo-deb | gazebo/gui/MainWindow.cc | C++ | apache-2.0 | 43,348 |
package se.tmeit.app.model;
import com.google.auto.value.AutoValue;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Model object for attendees of an external event.
*/
@AutoValue
public abstract class ExternalEventAttendee {
public static ExternalEventAttendee fromJson(JSONObject json) throws JSONException {
return builder()
.setDateOfBirth(json.optString(Keys.DOB, ""))
.setDrinkPreferences(json.optString(Keys.DRINK_PREFS, ""))
.setFoodPreferences(json.optString(Keys.FOOD_PREFS, ""))
.setName(json.optString(Keys.NAME, ""))
.setNotes(json.optString(Keys.NOTES, ""))
.setId(json.optInt(Keys.ID))
.build();
}
public static List<ExternalEventAttendee> fromJsonArray(JSONArray json) throws JSONException {
ArrayList<ExternalEventAttendee> result = new ArrayList<>(json.length());
for (int i = 0; i < json.length(); i++) {
result.add(fromJson(json.getJSONObject(i)));
}
return result;
}
public static Builder builder() {
return new AutoValue_ExternalEventAttendee.Builder()
.setId(0)
.setName("");
}
public abstract String dateOfBirth();
public abstract String drinkPreferences();
public abstract String foodPreferences();
public abstract String name();
public abstract String notes();
public abstract int id();
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder setDateOfBirth(String value);
public abstract Builder setDrinkPreferences(String value);
public abstract Builder setFoodPreferences(String value);
abstract Builder setName(String value);
public abstract Builder setNotes(String value);
abstract Builder setId(int id);
public abstract ExternalEventAttendee build();
}
public static class Keys {
public static final String DOB = "dob";
public static final String DRINK_PREFS = "drink_prefs";
public static final String FOOD_PREFS = "food_prefs";
public static final String ID = "id";
public static final String NAME = "user_name";
public static final String NOTES = "notes";
private Keys() {
}
}
}
| wsv-accidis/tmeit-android | app/src/main/java/se/tmeit/app/model/ExternalEventAttendee.java | Java | apache-2.0 | 2,147 |
<?php
namespace WonderPush\Obj;
if (count(get_included_files()) === 1) { http_response_code(403); exit(); } // Prevent direct access
/**
* DTO part for `installation.device`.
* @see Installation
* @codeCoverageIgnore
*/
class InstallationDevice extends BaseObject {
/** @var string */
private $id;
/** @var string */
private $platform;
/** @var string */
private $osVersion;
/** @var string */
private $brand;
/** @var string */
private $model;
/** @var string */
private $name;
/** @var int */
private $screenWidth;
/** @var int */
private $screenHeight;
/** @var int */
private $screenDensity;
/** @var InstallationDeviceCapabilities */
private $capabilities;
/** @var InstallationDeviceConfiguration */
private $configuration;
/**
* @return string
*/
public function getId() {
return $this->id;
}
/**
* @param string $id
* @return InstallationDevice
*/
public function setId($id) {
$this->id = $id;
return $this;
}
/**
* @return string
*/
public function getPlatform() {
return $this->platform;
}
/**
* @param string $platform
* @return InstallationDevice
*/
public function setPlatform($platform) {
$this->platform = $platform;
return $this;
}
/**
* @return string
*/
public function getOsVersion() {
return $this->osVersion;
}
/**
* @param string $osVersion
* @return InstallationDevice
*/
public function setOsVersion($osVersion) {
$this->osVersion = $osVersion;
return $this;
}
/**
* @return string
*/
public function getBrand() {
return $this->brand;
}
/**
* @param string $brand
* @return InstallationDevice
*/
public function setBrand($brand) {
$this->brand = $brand;
return $this;
}
/**
* @return string
*/
public function getModel() {
return $this->model;
}
/**
* @param string $model
* @return InstallationDevice
*/
public function setModel($model) {
$this->model = $model;
return $this;
}
/**
* @return string
*/
public function getName() {
return $this->name;
}
/**
* @param string $name
* @return InstallationDevice
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* @return int
*/
public function getScreenWidth() {
return $this->screenWidth;
}
/**
* @param int $screenWidth
* @return InstallationDevice
*/
public function setScreenWidth($screenWidth) {
$this->screenWidth = $screenWidth;
return $this;
}
/**
* @return int
*/
public function getScreenHeight() {
return $this->screenHeight;
}
/**
* @param int $screenHeight
* @return InstallationDevice
*/
public function setScreenHeight($screenHeight) {
$this->screenHeight = $screenHeight;
return $this;
}
/**
* @return int
*/
public function getScreenDensity() {
return $this->screenDensity;
}
/**
* @param int $screenDensity
* @return InstallationDevice
*/
public function setScreenDensity($screenDensity) {
$this->screenDensity = $screenDensity;
return $this;
}
/**
* @return InstallationDeviceCapabilities
*/
public function getCapabilities() {
return $this->capabilities;
}
/**
* @param InstallationDeviceCapabilities|array $capabilities
* @return InstallationDevice
*/
public function setCapabilities($capabilities) {
$this->capabilities = BaseObject::instantiateForSetter('\WonderPush\Obj\InstallationDeviceCapabilities', $capabilities);
return $this;
}
/**
* @return InstallationDeviceConfiguration
*/
public function getConfiguration() {
return $this->configuration;
}
/**
* @param InstallationDeviceConfiguration $configuration
* @return InstallationDevice
*/
public function setConfiguration($configuration) {
$this->configuration = BaseObject::instantiateForSetter('\WonderPush\Obj\InstallationDeviceConfiguration', $configuration);
return $this;
}
}
| wonderpush/wonderpush-php-lib | lib/Obj/InstallationDevice.php | PHP | apache-2.0 | 4,063 |
/*
* Copyright 2016 Code Above Lab LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codeabovelab.dm.cluman.cluster.docker.model.swarm;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class DispatcherConfig {
@JsonProperty("HeartbeatPeriod")
private Long heartbeatPeriod;
}
| codeabovelab/haven-platform | cluster-manager/src/main/java/com/codeabovelab/dm/cluman/cluster/docker/model/swarm/DispatcherConfig.java | Java | apache-2.0 | 854 |
# Copyright 2015 The Meson development team
# 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.
'''This module provides helper functions for Gnome/GLib related
functionality such as gobject-introspection and gresources.'''
import build
import os, sys
import subprocess
from coredata import MesonException
import mlog
class GnomeModule:
def compile_resources(self, state, args, kwargs):
cmd = ['glib-compile-resources', '@INPUT@', '--generate']
if 'source_dir' in kwargs:
d = os.path.join(state.build_to_src, state.subdir, kwargs.pop('source_dir'))
cmd += ['--sourcedir', d]
if 'c_name' in kwargs:
cmd += ['--c-name', kwargs.pop('c_name')]
cmd += ['--target', '@OUTPUT@']
kwargs['command'] = cmd
output_c = args[0] + '.c'
output_h = args[0] + '.h'
kwargs['input'] = args[1]
kwargs['output'] = output_c
target_c = build.CustomTarget(args[0]+'_c', state.subdir, kwargs)
kwargs['output'] = output_h
target_h = build.CustomTarget(args[0] + '_h', state.subdir, kwargs)
return [target_c, target_h]
def generate_gir(self, state, args, kwargs):
if len(args) != 1:
raise MesonException('Gir takes one argument')
girtarget = args[0]
while hasattr(girtarget, 'held_object'):
girtarget = girtarget.held_object
if not isinstance(girtarget, (build.Executable, build.SharedLibrary)):
raise MesonException('Gir target must be an executable or shared library')
pkgstr = subprocess.check_output(['pkg-config', '--cflags', 'gobject-introspection-1.0'])
pkgargs = pkgstr.decode().strip().split()
ns = kwargs.pop('namespace')
nsversion = kwargs.pop('nsversion')
libsources = kwargs.pop('sources')
girfile = '%s-%s.gir' % (ns, nsversion)
depends = [girtarget]
scan_command = ['g-ir-scanner', '@INPUT@']
scan_command += pkgargs
scan_command += ['--namespace='+ns, '--nsversion=' + nsversion, '--warn-all',
'--output', '@OUTPUT@']
for incdirs in girtarget.include_dirs:
for incdir in incdirs.get_incdirs():
scan_command += ['-I%s' % os.path.join(state.environment.get_source_dir(), incdir)]
if 'link_with' in kwargs:
link_with = kwargs.pop('link_with')
for link in link_with:
lib = link.held_object
scan_command += ['-l%s' % lib.name]
if isinstance(lib, build.SharedLibrary):
scan_command += ['-L%s' %
os.path.join(state.environment.get_build_dir(),
lib.subdir)]
depends.append(lib)
if 'includes' in kwargs:
includes = kwargs.pop('includes')
if isinstance(includes, str):
scan_command += ['--include=%s' % includes]
elif isinstance(includes, list):
scan_command += ['--include=%s' % inc for inc in includes]
else:
raise MesonException('Gir includes must be str or list')
if state.global_args.get('c'):
scan_command += ['--cflags-begin']
scan_command += state.global_args['c']
scan_command += ['--cflags-end']
if kwargs.get('symbol_prefix'):
sym_prefix = kwargs.pop('symbol_prefix')
if not isinstance(sym_prefix, str):
raise MesonException('Gir symbol prefix must be str')
scan_command += ['--symbol-prefix=%s' % sym_prefix]
if kwargs.get('identifier_prefix'):
identifier_prefix = kwargs.pop('identifier_prefix')
if not isinstance(identifier_prefix, str):
raise MesonException('Gir identifier prefix must be str')
scan_command += ['--identifier-prefix=%s' % identifier_prefix]
if kwargs.get('export_packages'):
pkgs = kwargs.pop('export_packages')
if isinstance(pkgs, str):
scan_command += ['--pkg-export=%s' % pkgs]
elif isinstance(pkgs, list):
scan_command += ['--pkg-export=%s' % pkg for pkg in pkgs]
else:
raise MesonException('Gir export packages must be str or list')
deps = None
if 'dependencies' in kwargs:
deps = kwargs.pop('dependencies')
if not isinstance (deps, list):
deps = [deps]
for dep in deps:
girdir = dep.held_object.get_variable ("girdir")
if girdir:
scan_command += ["--add-include-path=%s" % girdir]
inc_dirs = None
if kwargs.get('include_directories'):
inc_dirs = kwargs.pop('include_directories')
if isinstance(inc_dirs.held_object, build.IncludeDirs):
scan_command += ['--add-include-path=%s' % inc for inc in inc_dirs.held_object.get_incdirs()]
else:
raise MesonException('Gir include dirs should be include_directories()')
if isinstance(girtarget, build.Executable):
scan_command += ['--program', girtarget]
elif isinstance(girtarget, build.SharedLibrary):
scan_command += ["-L", os.path.join (state.environment.get_build_dir(), girtarget.subdir)]
libname = girtarget.get_basename()
scan_command += ['--library', libname]
scankwargs = {'output' : girfile,
'input' : libsources,
'command' : scan_command,
'depends' : depends,
}
if kwargs.get('install'):
scankwargs['install'] = kwargs['install']
scankwargs['install_dir'] = os.path.join(state.environment.get_datadir(), 'gir-1.0')
scan_target = GirTarget(girfile, state.subdir, scankwargs)
typelib_output = '%s-%s.typelib' % (ns, nsversion)
typelib_cmd = ['g-ir-compiler', scan_target, '--output', '@OUTPUT@']
if inc_dirs:
typelib_cmd += ['--includedir=%s' % inc for inc in
inc_dirs.held_object.get_incdirs()]
if deps:
for dep in deps:
girdir = dep.held_object.get_variable ("girdir")
if girdir:
typelib_cmd += ["--includedir=%s" % girdir]
kwargs['output'] = typelib_output
kwargs['command'] = typelib_cmd
# Note that this can't be libdir, because e.g. on Debian it points to
# lib/x86_64-linux-gnu but the girepo dir is always under lib.
kwargs['install_dir'] = 'lib/girepository-1.0'
typelib_target = TypelibTarget(typelib_output, state.subdir, kwargs)
return [scan_target, typelib_target]
def compile_schemas(self, state, args, kwargs):
if len(args) != 0:
raise MesonException('Compile_schemas does not take positional arguments.')
srcdir = os.path.join(state.build_to_src, state.subdir)
outdir = state.subdir
cmd = ['glib-compile-schemas', '--targetdir', outdir, srcdir]
kwargs['command'] = cmd
kwargs['input'] = []
kwargs['output'] = 'gschemas.compiled'
if state.subdir == '':
targetname = 'gsettings-compile'
else:
targetname = 'gsettings-compile-' + state.subdir
target_g = build.CustomTarget(targetname, state.subdir, kwargs)
return target_g
def gtkdoc(self, state, args, kwargs):
if len(args) != 1:
raise MesonException('Gtkdoc must have one positional argument.')
modulename = args[0]
if not isinstance(modulename, str):
raise MesonException('Gtkdoc arg must be string.')
if not 'src_dir' in kwargs:
raise MesonException('Keyword argument src_dir missing.')
main_file = kwargs.get('main_sgml', '')
if not isinstance(main_file, str):
raise MesonException('Main sgml keyword argument must be a string.')
main_xml = kwargs.get('main_xml', '')
if not isinstance(main_xml, str):
raise MesonException('Main xml keyword argument must be a string.')
if main_xml != '':
if main_file != '':
raise MesonException('You can only specify main_xml or main_sgml, not both.')
main_file = main_xml
src_dir = kwargs['src_dir']
targetname = modulename + '-doc'
command = os.path.normpath(os.path.join(os.path.split(__file__)[0], "../gtkdochelper.py"))
args = [state.environment.get_source_dir(),
state.environment.get_build_dir(),
state.subdir,
os.path.normpath(os.path.join(state.subdir, src_dir)),
main_file,
modulename]
res = [build.RunTarget(targetname, command, args, state.subdir)]
if kwargs.get('install', True):
res.append(build.InstallScript([command] + args))
return res
def gdbus_codegen(self, state, args, kwargs):
if len(args) != 2:
raise MesonException('Gdbus_codegen takes two arguments, name and xml file.')
namebase = args[0]
xml_file = args[1]
cmd = ['gdbus-codegen']
if 'interface_prefix' in kwargs:
cmd += ['--interface-prefix', kwargs.pop('interface_prefix')]
if 'namespace' in kwargs:
cmd += ['--c-namespace', kwargs.pop('namespace')]
cmd += ['--generate-c-code', os.path.join(state.subdir, namebase), '@INPUT@']
outputs = [namebase + '.c', namebase + '.h']
custom_kwargs = {'input' : xml_file,
'output' : outputs,
'command' : cmd
}
return build.CustomTarget(namebase + '-gdbus', state.subdir, custom_kwargs)
def initialize():
mlog.log('Warning, glib compiled dependencies will not work until this upstream issue is fixed:',
mlog.bold('https://bugzilla.gnome.org/show_bug.cgi?id=745754'))
return GnomeModule()
class GirTarget(build.CustomTarget):
def __init__(self, name, subdir, kwargs):
super().__init__(name, subdir, kwargs)
class TypelibTarget(build.CustomTarget):
def __init__(self, name, subdir, kwargs):
super().__init__(name, subdir, kwargs)
| evgenyz/meson | modules/gnome.py | Python | apache-2.0 | 10,923 |
package es.upm.oeg.farolapi.model;
import lombok.Data;
import lombok.ToString;
import java.util.Arrays;
import java.util.List;
/**
* Created on 23/05/16:
*
* @author cbadenes
*/
@Data
@ToString (callSuper = true)
public class LightAttribute extends Attribute {
@Override
public List<String> getRange() {
return Arrays.asList(new String[]{"P", "F", "E", "AA", "AC", "ER", "O"});
}
}
| cbadenes/farolapi | src/main/java/es/upm/oeg/farolapi/model/LightAttribute.java | Java | apache-2.0 | 410 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/redis/v1/cloud_redis.proto
package com.google.cloud.redis.v1;
public interface CreateInstanceRequestOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.redis.v1.CreateInstanceRequest)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Required. The resource name of the instance location using the form:
* `projects/{project_id}/locations/{location_id}`
* where `location_id` refers to a GCP region.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
java.lang.String getParent();
/**
*
*
* <pre>
* Required. The resource name of the instance location using the form:
* `projects/{project_id}/locations/{location_id}`
* where `location_id` refers to a GCP region.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
com.google.protobuf.ByteString getParentBytes();
/**
*
*
* <pre>
* Required. The logical name of the Redis instance in the customer project
* with the following restrictions:
* * Must contain only lowercase letters, numbers, and hyphens.
* * Must start with a letter.
* * Must be between 1-40 characters.
* * Must end with a number or a letter.
* * Must be unique within the customer project / location
* </pre>
*
* <code>string instance_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The instanceId.
*/
java.lang.String getInstanceId();
/**
*
*
* <pre>
* Required. The logical name of the Redis instance in the customer project
* with the following restrictions:
* * Must contain only lowercase letters, numbers, and hyphens.
* * Must start with a letter.
* * Must be between 1-40 characters.
* * Must end with a number or a letter.
* * Must be unique within the customer project / location
* </pre>
*
* <code>string instance_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for instanceId.
*/
com.google.protobuf.ByteString getInstanceIdBytes();
/**
*
*
* <pre>
* Required. A Redis [Instance] resource
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the instance field is set.
*/
boolean hasInstance();
/**
*
*
* <pre>
* Required. A Redis [Instance] resource
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
com.google.cloud.redis.v1.Instance getInstance();
/**
*
*
* <pre>
* Required. A Redis [Instance] resource
* </pre>
*
* <code>.google.cloud.redis.v1.Instance instance = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
com.google.cloud.redis.v1.InstanceOrBuilder getInstanceOrBuilder();
}
| googleapis/java-redis | proto-google-cloud-redis-v1/src/main/java/com/google/cloud/redis/v1/CreateInstanceRequestOrBuilder.java | Java | apache-2.0 | 3,827 |
/*
* Copyright © 2021 Cask Data, 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 io.cdap.delta.store;
import com.google.gson.Gson;
import io.cdap.cdap.spi.data.StructuredRow;
import io.cdap.cdap.spi.data.StructuredTable;
import io.cdap.cdap.spi.data.StructuredTableContext;
import io.cdap.cdap.spi.data.TableNotFoundException;
import io.cdap.cdap.spi.data.table.StructuredTableId;
import io.cdap.cdap.spi.data.table.StructuredTableSpecification;
import io.cdap.cdap.spi.data.table.field.Field;
import io.cdap.cdap.spi.data.table.field.FieldType;
import io.cdap.cdap.spi.data.table.field.Fields;
import io.cdap.delta.app.DeltaWorkerId;
import io.cdap.delta.app.OffsetAndSequence;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
/**
* A StructuredTable based database table to store replication offset and sequence data.
*/
public class DBReplicationOffsetStore {
private static final StructuredTableId TABLE_ID = new StructuredTableId("delta_offset_store");
private static final String NAMESPACE_COL = "namespace";
private static final String APP_GENERATION_COL = "app_generation";
private static final String APP_NAME_COL = "app_name";
private static final String INSTANCE_ID_COL = "instance_id";
private static final String OFFSET_COL = "offset_sequence";
private static final String UPDATED_COL = "last_updated";
public static final StructuredTableSpecification TABLE_SPEC = new StructuredTableSpecification.Builder()
.withId(TABLE_ID)
.withFields(new FieldType(NAMESPACE_COL, FieldType.Type.STRING),
new FieldType(APP_GENERATION_COL, FieldType.Type.LONG),
new FieldType(APP_NAME_COL, FieldType.Type.STRING),
new FieldType(INSTANCE_ID_COL, FieldType.Type.INTEGER),
new FieldType(OFFSET_COL, FieldType.Type.STRING),
new FieldType(UPDATED_COL, FieldType.Type.LONG))
.withPrimaryKeys(NAMESPACE_COL, APP_NAME_COL, APP_GENERATION_COL, INSTANCE_ID_COL)
.build();
private final StructuredTable table;
private static final Gson GSON = new Gson();
private DBReplicationOffsetStore(StructuredTable table) {
this.table = table;
}
static DBReplicationOffsetStore get(StructuredTableContext context) {
try {
StructuredTable table = context.getTable(TABLE_ID);
return new DBReplicationOffsetStore(table);
} catch (TableNotFoundException e) {
throw new IllegalStateException(String.format(
"System table '%s' does not exist. Please check your system environment.", TABLE_ID.getName()), e);
}
}
@Nullable
public OffsetAndSequence getOffsets(DeltaWorkerId id)
throws IOException {
List<Field<?>> keys = getKey(id);
Optional<StructuredRow> row = table.read(keys);
if (!row.isPresent() || row.get().getString(OFFSET_COL) == null) {
return null;
}
String offsetStrJson = row.get().getString(OFFSET_COL);
return GSON.fromJson(offsetStrJson, OffsetAndSequence.class);
}
public void writeOffset(DeltaWorkerId id, OffsetAndSequence data)
throws IOException {
Collection<Field<?>> fields = getKey(id);
fields.add(Fields.stringField(OFFSET_COL, GSON.toJson(data)));
fields.add(Fields.longField(UPDATED_COL, System.currentTimeMillis()));
table.upsert(fields);
}
private List<Field<?>> getKey(DeltaWorkerId id) {
List<Field<?>> keyFields = new ArrayList<>(4);
keyFields.add(Fields.stringField(NAMESPACE_COL, id.getPipelineId().getNamespace()));
keyFields.add(Fields.stringField(APP_NAME_COL, id.getPipelineId().getApp()));
keyFields.add(Fields.longField(APP_GENERATION_COL, id.getPipelineId().getGeneration()));
keyFields.add(Fields.intField(INSTANCE_ID_COL, id.getInstanceId()));
return keyFields;
}
}
| data-integrations/delta | delta-app/src/main/java/io/cdap/delta/store/DBReplicationOffsetStore.java | Java | apache-2.0 | 4,397 |
/*-
* Copyright (C) 2013-2014 The JBromo Authors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jbromo.common.test.common;
import java.lang.reflect.Method;
import org.jbromo.common.EnumUtil;
import org.jbromo.common.invocation.InvocationException;
import org.jbromo.common.invocation.InvocationUtil;
import org.junit.Assert;
import org.junit.Ignore;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* Enum test util class.
* @author qjafcunuas
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Ignore
public final class EnumTestUtil {
/**
* Tests valueOf method.
* @param <E> the enum type.
* @param enumClass the enum class.
*/
public static <E extends Enum<E>> void valueOf(final Class<E> enumClass) {
E value;
try {
final Method method = InvocationUtil.getMethod(enumClass, "valueOf", String.class);
for (final E one : EnumUtil.getValues(enumClass)) {
value = InvocationUtil.invokeMethod(method, one, one.name());
Assert.assertEquals(one, value);
}
} catch (final InvocationException e) {
Assert.fail(e.getMessage());
}
}
}
| qjafcunuas/jbromo | jbromo-lib/src/test/java/org/jbromo/common/test/common/EnumTestUtil.java | Java | apache-2.0 | 2,245 |
package build
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"runtime"
"github.com/BurntSushi/toml"
"github.com/buildpacks/lifecycle/platform"
"github.com/docker/docker/api/types"
dcontainer "github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/pkg/errors"
"github.com/buildpacks/pack/internal/builder"
"github.com/buildpacks/pack/internal/container"
"github.com/buildpacks/pack/internal/paths"
"github.com/buildpacks/pack/pkg/archive"
)
type ContainerOperation func(ctrClient client.CommonAPIClient, ctx context.Context, containerID string, stdout, stderr io.Writer) error
// CopyDir copies a local directory (src) to the destination on the container while filtering files and changing it's UID/GID.
// if includeRoot is set the UID/GID will be set on the dst directory.
func CopyDir(src, dst string, uid, gid int, os string, includeRoot bool, fileFilter func(string) bool) ContainerOperation {
return func(ctrClient client.CommonAPIClient, ctx context.Context, containerID string, stdout, stderr io.Writer) error {
tarPath := dst
if os == "windows" {
tarPath = paths.WindowsToSlash(dst)
}
reader, err := createReader(src, tarPath, uid, gid, includeRoot, fileFilter)
if err != nil {
return errors.Wrapf(err, "create tar archive from '%s'", src)
}
defer reader.Close()
if os == "windows" {
return copyDirWindows(ctx, ctrClient, containerID, reader, dst, stdout, stderr)
}
return copyDir(ctx, ctrClient, containerID, reader)
}
}
func copyDir(ctx context.Context, ctrClient client.CommonAPIClient, containerID string, appReader io.Reader) error {
var clientErr, err error
doneChan := make(chan interface{})
pr, pw := io.Pipe()
go func() {
clientErr = ctrClient.CopyToContainer(ctx, containerID, "/", pr, types.CopyToContainerOptions{})
close(doneChan)
}()
func() {
defer pw.Close()
_, err = io.Copy(pw, appReader)
}()
<-doneChan
if err == nil {
err = clientErr
}
return err
}
// copyDirWindows provides an alternate, Windows container-specific implementation of copyDir.
// This implementation is needed because copying directly to a mounted volume is currently buggy
// for Windows containers and does not work. Instead, we perform the copy from inside a container
// using xcopy.
// See: https://github.com/moby/moby/issues/40771
func copyDirWindows(ctx context.Context, ctrClient client.CommonAPIClient, containerID string, reader io.Reader, dst string, stdout, stderr io.Writer) error {
info, err := ctrClient.ContainerInspect(ctx, containerID)
if err != nil {
return err
}
baseName := paths.WindowsBasename(dst)
mnt, err := findMount(info, dst)
if err != nil {
return err
}
ctr, err := ctrClient.ContainerCreate(ctx,
&dcontainer.Config{
Image: info.Image,
Cmd: []string{
"cmd",
"/c",
// xcopy args
// e - recursively create subdirectories
// h - copy hidden and system files
// b - copy symlinks, do not dereference
// x - copy attributes
// y - suppress prompting
fmt.Sprintf(`xcopy c:\windows\%s %s /e /h /b /x /y`, baseName, dst),
},
WorkingDir: "/",
User: windowsContainerAdmin,
},
&dcontainer.HostConfig{
Binds: []string{fmt.Sprintf("%s:%s", mnt.Name, mnt.Destination)},
Isolation: dcontainer.IsolationProcess,
},
nil, nil, "",
)
if err != nil {
return errors.Wrapf(err, "creating prep container")
}
defer ctrClient.ContainerRemove(context.Background(), ctr.ID, types.ContainerRemoveOptions{Force: true})
err = ctrClient.CopyToContainer(ctx, ctr.ID, "/windows", reader, types.CopyToContainerOptions{})
if err != nil {
return errors.Wrap(err, "copy app to container")
}
return container.RunWithHandler(
ctx,
ctrClient,
ctr.ID,
container.DefaultHandler(
ioutil.Discard, // Suppress xcopy output
stderr,
),
)
}
func findMount(info types.ContainerJSON, dst string) (types.MountPoint, error) {
for _, m := range info.Mounts {
if m.Destination == dst {
return m, nil
}
}
return types.MountPoint{}, fmt.Errorf("no matching mount found for %s", dst)
}
//WriteProjectMetadata
func WriteProjectMetadata(p string, metadata platform.ProjectMetadata, os string) ContainerOperation {
return func(ctrClient client.CommonAPIClient, ctx context.Context, containerID string, stdout, stderr io.Writer) error {
buf := &bytes.Buffer{}
err := toml.NewEncoder(buf).Encode(metadata)
if err != nil {
return errors.Wrap(err, "marshaling project metadata")
}
tarBuilder := archive.TarBuilder{}
tarPath := p
if os == "windows" {
tarPath = paths.WindowsToSlash(p)
}
tarBuilder.AddFile(tarPath, 0755, archive.NormalizedDateTime, buf.Bytes())
reader := tarBuilder.Reader(archive.DefaultTarWriterFactory())
defer reader.Close()
if os == "windows" {
dirName := paths.WindowsDir(p)
return copyDirWindows(ctx, ctrClient, containerID, reader, dirName, stdout, stderr)
}
return ctrClient.CopyToContainer(ctx, containerID, "/", reader, types.CopyToContainerOptions{})
}
}
// WriteStackToml writes a `stack.toml` based on the StackMetadata provided to the destination path.
func WriteStackToml(dstPath string, stack builder.StackMetadata, os string) ContainerOperation {
return func(ctrClient client.CommonAPIClient, ctx context.Context, containerID string, stdout, stderr io.Writer) error {
buf := &bytes.Buffer{}
err := toml.NewEncoder(buf).Encode(stack)
if err != nil {
return errors.Wrap(err, "marshaling stack metadata")
}
tarBuilder := archive.TarBuilder{}
tarPath := dstPath
if os == "windows" {
tarPath = paths.WindowsToSlash(dstPath)
}
tarBuilder.AddFile(tarPath, 0755, archive.NormalizedDateTime, buf.Bytes())
reader := tarBuilder.Reader(archive.DefaultTarWriterFactory())
defer reader.Close()
if os == "windows" {
dirName := paths.WindowsDir(dstPath)
return copyDirWindows(ctx, ctrClient, containerID, reader, dirName, stdout, stderr)
}
return ctrClient.CopyToContainer(ctx, containerID, "/", reader, types.CopyToContainerOptions{})
}
}
func createReader(src, dst string, uid, gid int, includeRoot bool, fileFilter func(string) bool) (io.ReadCloser, error) {
fi, err := os.Stat(src)
if err != nil {
return nil, err
}
if fi.IsDir() {
var mode int64 = -1
if runtime.GOOS == "windows" {
mode = 0777
}
return archive.ReadDirAsTar(src, dst, uid, gid, mode, false, includeRoot, fileFilter), nil
}
return archive.ReadZipAsTar(src, dst, uid, gid, -1, false, fileFilter), nil
}
// EnsureVolumeAccess grants full access permissions to volumes for UID/GID-based user
// When UID/GID are 0 it grants explicit full access to BUILTIN\Administrators and any other UID/GID grants full access to BUILTIN\Users
// Changing permissions on volumes through stopped containers does not work on Docker for Windows so we start the container and make change using icacls
// See: https://github.com/moby/moby/issues/40771
func EnsureVolumeAccess(uid, gid int, os string, volumeNames ...string) ContainerOperation {
return func(ctrClient client.CommonAPIClient, ctx context.Context, containerID string, stdout, stderr io.Writer) error {
if os != "windows" {
return nil
}
containerInfo, err := ctrClient.ContainerInspect(ctx, containerID)
if err != nil {
return err
}
cmd := ""
binds := []string{}
for i, volumeName := range volumeNames {
containerPath := fmt.Sprintf("c:/volume-mnt-%d", i)
binds = append(binds, fmt.Sprintf("%s:%s", volumeName, containerPath))
if cmd != "" {
cmd += "&&"
}
// icacls args
// /grant - add new permissions instead of replacing
// (OI) - object inherit
// (CI) - container inherit
// F - full access
// /t - recursively apply
// /l - perform on a symbolic link itself versus its target
// /q - suppress success messages
cmd += fmt.Sprintf(`icacls %s /grant *%s:(OI)(CI)F /t /l /q`, containerPath, paths.WindowsPathSID(uid, gid))
}
ctr, err := ctrClient.ContainerCreate(ctx,
&dcontainer.Config{
Image: containerInfo.Image,
Cmd: []string{"cmd", "/c", cmd},
WorkingDir: "/",
User: windowsContainerAdmin,
},
&dcontainer.HostConfig{
Binds: binds,
Isolation: dcontainer.IsolationProcess,
},
nil, nil, "",
)
if err != nil {
return err
}
defer ctrClient.ContainerRemove(context.Background(), ctr.ID, types.ContainerRemoveOptions{Force: true})
return container.RunWithHandler(
ctx,
ctrClient,
ctr.ID,
container.DefaultHandler(
ioutil.Discard, // Suppress icacls output
stderr,
),
)
}
}
| knative-sandbox/kn-plugin-func | vendor/github.com/buildpacks/pack/internal/build/container_ops.go | GO | apache-2.0 | 8,619 |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/fusion/lib/data_association/hm_data_association/track_object_distance.h"
#include <algorithm>
#include <limits>
#include <map>
#include <utility>
#include "boost/format.hpp"
#include "modules/perception/base/camera.h"
#include "modules/perception/base/point.h"
#include "modules/perception/base/sensor_meta.h"
#include "modules/perception/common/geometry/camera_homography.h"
#include "modules/perception/fusion/lib/data_association/hm_data_association/chi_squared_cdf_1_0.0500_0.999900.h"
#include "modules/perception/fusion/lib/data_association/hm_data_association/chi_squared_cdf_2_0.0500_0.999900.h"
namespace apollo {
namespace perception {
namespace fusion {
double TrackObjectDistance::s_lidar2lidar_association_center_dist_threshold_ =
10.0;
double TrackObjectDistance::s_lidar2radar_association_center_dist_threshold_ =
10.0;
double TrackObjectDistance::s_radar2radar_association_center_dist_threshold_ =
10.0;
size_t
TrackObjectDistance::s_lidar2camera_projection_downsample_target_pts_num_ =
100;
size_t TrackObjectDistance::s_lidar2camera_projection_vertices_check_pts_num_ =
20;
void TrackObjectDistance::GetModified2DRadarBoxVertices(
const std::vector<Eigen::Vector3d>& radar_box_vertices,
const SensorObjectConstPtr& camera,
const base::BaseCameraModelPtr& camera_intrinsic,
const Eigen::Matrix4d& world2camera_pose,
std::vector<Eigen::Vector2d>* radar_box2d_vertices) {
const double camera_height = camera->GetBaseObject()->size(2);
std::vector<Eigen::Vector3d> modified_radar_box_vertices = radar_box_vertices;
for (size_t i = 0; i < 4; ++i) {
modified_radar_box_vertices[i + 4].z() =
modified_radar_box_vertices[i].z() + camera_height;
}
radar_box2d_vertices->reserve(radar_box_vertices.size());
for (const auto& box_vertex_3d : modified_radar_box_vertices) {
Eigen::Vector4d local_box_vertex =
world2camera_pose * box_vertex_3d.homogeneous();
Eigen::Vector2f temp_vertex =
camera_intrinsic->Project(local_box_vertex.head(3).cast<float>());
radar_box2d_vertices->push_back(temp_vertex.cast<double>());
}
return;
}
base::BaseCameraModelPtr TrackObjectDistance::QueryCameraModel(
const SensorObjectConstPtr& camera) {
return SensorDataManager::Instance()->GetCameraIntrinsic(
camera->GetSensorId());
}
bool TrackObjectDistance::QueryWorld2CameraPose(
const SensorObjectConstPtr& camera, Eigen::Matrix4d* pose) {
Eigen::Affine3d camera2world_pose;
bool status = SensorDataManager::Instance()->GetPose(
camera->GetSensorId(), camera->GetTimestamp(), &camera2world_pose);
if (!status) {
return false;
}
(*pose) = camera2world_pose.matrix().inverse();
return true;
}
bool TrackObjectDistance::QueryLidar2WorldPose(
const SensorObjectConstPtr& lidar, Eigen::Matrix4d* pose) {
Eigen::Affine3d velo2world_pose;
if (!lidar->GetRelatedFramePose(&velo2world_pose)) {
return false;
}
(*pose) = velo2world_pose.matrix();
return true;
}
ProjectionCacheObject* TrackObjectDistance::BuildProjectionCacheObject(
const SensorObjectConstPtr& lidar, const SensorObjectConstPtr& camera,
const base::BaseCameraModelPtr& camera_model,
const std::string& measurement_sensor_id, double measurement_timestamp,
const std::string& projection_sensor_id, double projection_timestamp) {
// 1. get lidar2camera_pose
Eigen::Matrix4d world2camera_pose;
if (!QueryWorld2CameraPose(camera, &world2camera_pose)) {
return nullptr;
}
Eigen::Matrix4d lidar2world_pose;
if (!QueryLidar2WorldPose(lidar, &lidar2world_pose)) {
return nullptr;
}
Eigen::Matrix4d lidar2camera_pose =
static_cast<Eigen::Matrix<double, 4, 4, 0, 4, 4>>(world2camera_pose *
lidar2world_pose);
// 2. compute offset
double time_diff = camera->GetTimestamp() - lidar->GetTimestamp();
Eigen::Vector3d offset =
lidar->GetBaseObject()->velocity.cast<double>() * time_diff;
// 3. build projection cache
const base::PointFCloud& cloud =
lidar->GetBaseObject()->lidar_supplement.cloud;
double width = static_cast<double>(camera_model->get_width());
double height = static_cast<double>(camera_model->get_height());
const int lidar_object_id = lidar->GetBaseObject()->id;
ProjectionCacheObject* cache_object = projection_cache_.BuildObject(
measurement_sensor_id, measurement_timestamp, projection_sensor_id,
projection_timestamp, lidar_object_id);
if (cache_object == nullptr) {
AERROR << "Failed to build projection cache object";
return nullptr;
}
size_t start_ind = projection_cache_.GetPoint2dsSize();
size_t end_ind = projection_cache_.GetPoint2dsSize();
float xmin = FLT_MAX;
float ymin = FLT_MAX;
float xmax = -FLT_MAX;
float ymax = -FLT_MAX;
// 4. check whether all lidar's 8 3d vertices would projected outside frustum,
// if not, build projection object of its cloud and cache it
// else, build empty projection object and cache it
bool is_all_lidar_3d_vertices_outside_frustum = false;
if (cloud.size() > s_lidar2camera_projection_vertices_check_pts_num_) {
is_all_lidar_3d_vertices_outside_frustum = true;
std::vector<Eigen::Vector3d> lidar_box_vertices;
GetObjectEightVertices(lidar->GetBaseObject(), &lidar_box_vertices);
for (size_t i = 0; i < lidar_box_vertices.size(); ++i) {
Eigen::Vector3d& vt = lidar_box_vertices[i];
Eigen::Vector4d project_vt =
static_cast<Eigen::Matrix<double, 4, 1, 0, 4, 1>>(
world2camera_pose * Eigen::Vector4d(vt(0) + offset(0),
vt(1) + offset(1),
vt(2) + offset(2), 1.0));
if (project_vt(2) <= 0) continue;
Eigen::Vector2f project_vt2f = camera_model->Project(Eigen::Vector3f(
static_cast<float>(project_vt(0)), static_cast<float>(project_vt(1)),
static_cast<float>(project_vt(2))));
if (!IsPtInFrustum(project_vt2f, width, height)) continue;
is_all_lidar_3d_vertices_outside_frustum = false;
break;
}
}
// 5. if not all lidar 3d vertices outside frustum, build projection object
// of its cloud and cache it, else build & cache an empty one.
if (!is_all_lidar_3d_vertices_outside_frustum) {
// 5.1 check whehter downsampling needed
size_t every_n = 1;
if (cloud.size() > s_lidar2camera_projection_downsample_target_pts_num_) {
every_n =
cloud.size() / s_lidar2camera_projection_downsample_target_pts_num_;
}
for (size_t i = 0; i < cloud.size(); ++i) {
if ((every_n > 1) && (i % every_n != 0)) continue;
const base::PointF& pt = cloud.at(i);
Eigen::Vector4d project_pt =
static_cast<Eigen::Matrix<double, 4, 1, 0, 4, 1>>(
lidar2camera_pose * Eigen::Vector4d(pt.x + offset(0),
pt.y + offset(1),
pt.z + offset(2), 1.0));
if (project_pt(2) <= 0) continue;
Eigen::Vector2f project_pt2f = camera_model->Project(Eigen::Vector3f(
static_cast<float>(project_pt(0)), static_cast<float>(project_pt(1)),
static_cast<float>(project_pt(2))));
if (!IsPtInFrustum(project_pt2f, width, height)) continue;
if (project_pt2f.x() < xmin) xmin = project_pt2f.x();
if (project_pt2f.y() < ymin) ymin = project_pt2f.y();
if (project_pt2f.x() > xmax) xmax = project_pt2f.x();
if (project_pt2f.y() > ymax) ymax = project_pt2f.y();
projection_cache_.AddPoint(project_pt2f);
}
}
end_ind = projection_cache_.GetPoint2dsSize();
cache_object->SetStartInd(start_ind);
cache_object->SetEndInd(end_ind);
base::BBox2DF box = base::BBox2DF(xmin, ymin, xmax, ymax);
cache_object->SetBox(box);
return cache_object;
}
ProjectionCacheObject* TrackObjectDistance::QueryProjectionCacheObject(
const SensorObjectConstPtr& lidar, const SensorObjectConstPtr& camera,
const base::BaseCameraModelPtr& camera_model,
const bool measurement_is_lidar) {
// 1. try to query existed projection cache object
const std::string& measurement_sensor_id =
measurement_is_lidar ? lidar->GetSensorId() : camera->GetSensorId();
const double measurement_timestamp =
measurement_is_lidar ? lidar->GetTimestamp() : camera->GetTimestamp();
const std::string& projection_sensor_id =
measurement_is_lidar ? camera->GetSensorId() : lidar->GetSensorId();
const double projection_timestamp =
measurement_is_lidar ? camera->GetTimestamp() : lidar->GetTimestamp();
const int lidar_object_id = lidar->GetBaseObject()->id;
ProjectionCacheObject* cache_object = projection_cache_.QueryObject(
measurement_sensor_id, measurement_timestamp, projection_sensor_id,
projection_timestamp, lidar_object_id);
if (cache_object != nullptr) return cache_object;
// 2. if query failed, build projection and cache it
return BuildProjectionCacheObject(
lidar, camera, camera_model, measurement_sensor_id, measurement_timestamp,
projection_sensor_id, projection_timestamp);
}
void TrackObjectDistance::QueryProjectedVeloCtOnCamera(
const SensorObjectConstPtr& velodyne64, const SensorObjectConstPtr& camera,
const Eigen::Matrix4d& lidar2camera_pose, Eigen::Vector3d* projected_ct) {
double time_diff = camera->GetTimestamp() - velodyne64->GetTimestamp();
Eigen::Vector3d offset =
velodyne64->GetBaseObject()->velocity.cast<double>() * time_diff;
const Eigen::Vector3d& velo_ct = velodyne64->GetBaseObject()->center;
Eigen::Vector4d projected_ct_4d =
static_cast<Eigen::Matrix<double, 4, 1, 0, 4, 1>>(
lidar2camera_pose * Eigen::Vector4d(velo_ct[0] + offset[0],
velo_ct[1] + offset[1],
velo_ct[2] + offset[2], 1.0));
*projected_ct = projected_ct_4d.head(3);
}
bool TrackObjectDistance::QueryPolygonDCenter(
const base::ObjectConstPtr& object, const Eigen::Vector3d& ref_pos,
const int range, Eigen::Vector3d* polygon_ct) {
if (object == nullptr) {
return false;
}
const base::PolygonDType& polygon = object->polygon;
if (!ComputePolygonCenter(polygon, ref_pos, range, polygon_ct)) {
return false;
}
return true;
}
bool TrackObjectDistance::IsTrackIdConsistent(
const SensorObjectConstPtr& object1, const SensorObjectConstPtr& object2) {
if (object1 == nullptr || object2 == nullptr) {
return false;
}
if (object1->GetBaseObject()->track_id ==
object2->GetBaseObject()->track_id) {
return true;
}
return false;
}
bool TrackObjectDistance::LidarCameraCenterDistanceExceedDynamicThreshold(
const SensorObjectConstPtr& lidar, const SensorObjectConstPtr& camera) {
double center_distance =
(lidar->GetBaseObject()->center - camera->GetBaseObject()->center)
.head(2)
.norm();
double local_distance = 60;
const base::PointFCloud& cloud =
lidar->GetBaseObject()->lidar_supplement.cloud;
if (cloud.size() > 0) {
const base::PointF& pt = cloud.at(0);
local_distance = std::sqrt(pt.x * pt.x + pt.y * pt.y);
}
double dynamic_threshold = 5 + 0.15 * local_distance;
if (center_distance > dynamic_threshold) {
return true;
}
return false;
}
// @brief: compute the distance between input fused track and sensor object
// @return track object distance
float TrackObjectDistance::Compute(const TrackPtr& fused_track,
const SensorObjectPtr& sensor_object,
const TrackObjectDistanceOptions& options) {
FusedObjectPtr fused_object = fused_track->GetFusedObject();
if (fused_object == nullptr) {
AERROR << "fused object is nullptr";
return (std::numeric_limits<float>::max)();
}
Eigen::Vector3d* ref_point = options.ref_point;
if (ref_point == nullptr) {
AERROR << "reference point is nullptr";
return (std::numeric_limits<float>::max)();
}
float distance = (std::numeric_limits<float>::max)();
float min_distance = (std::numeric_limits<float>::max)();
SensorObjectConstPtr lidar_object = fused_track->GetLatestLidarObject();
SensorObjectConstPtr radar_object = fused_track->GetLatestRadarObject();
SensorObjectConstPtr camera_object = fused_track->GetLatestCameraObject();
if (IsLidar(sensor_object)) {
if (lidar_object != nullptr) {
distance = ComputeLidarLidar(lidar_object, sensor_object, *ref_point);
min_distance = std::min(distance, min_distance);
}
if (radar_object != nullptr) {
distance = ComputeLidarRadar(radar_object, sensor_object, *ref_point);
min_distance = std::min(distance, min_distance);
}
if (camera_object != nullptr) {
bool is_lidar_track_id_consistent =
IsTrackIdConsistent(lidar_object, sensor_object);
distance = ComputeLidarCamera(sensor_object, camera_object, true,
is_lidar_track_id_consistent);
min_distance = std::min(distance, min_distance);
}
} else if (IsRadar(sensor_object)) {
if (lidar_object != nullptr) {
distance = ComputeLidarRadar(lidar_object, sensor_object, *ref_point);
min_distance = std::min(distance, min_distance);
}
// else if (radar_object != nullptr) {
// distance = std::numeric_limits<float>::max();
// min_distance = std::min(distance, min_distance);
// }
if (camera_object != nullptr) {
distance = ComputeRadarCamera(sensor_object, camera_object);
min_distance = std::min(distance, min_distance);
}
} else if (IsCamera(sensor_object)) {
if (lidar_object != nullptr) {
bool is_camera_track_id_consistent =
IsTrackIdConsistent(camera_object, sensor_object);
distance = ComputeLidarCamera(lidar_object, sensor_object, false,
is_camera_track_id_consistent);
min_distance = std::min(distance, min_distance);
}
} else {
AERROR << "fused sensor type is not support";
}
return min_distance;
}
// @brief: compute the distance between velodyne64 observation and
// velodyne64 observation
// @return the distance of velodyne64 vs. velodyne64
float TrackObjectDistance::ComputeLidarLidar(
const SensorObjectConstPtr& fused_object,
const SensorObjectPtr& sensor_object, const Eigen::Vector3d& ref_pos,
int range) {
double center_distance = (sensor_object->GetBaseObject()->center -
fused_object->GetBaseObject()->center)
.head(2)
.norm();
if (center_distance > s_lidar2lidar_association_center_dist_threshold_) {
ADEBUG << "center distance exceed lidar2lidar tight threshold: "
<< "center_dist@" << center_distance << ", "
<< "tight_threh@"
<< s_lidar2lidar_association_center_dist_threshold_;
return (std::numeric_limits<float>::max)();
}
float distance =
ComputePolygonDistance3d(fused_object, sensor_object, ref_pos, range);
ADEBUG << "ComputeLidarLidar distance: " << distance;
return distance;
}
// @brief: compute the distance between velodyne64 observation and
// radar observation
// @return distance of velodyne64 vs. radar
float TrackObjectDistance::ComputeLidarRadar(
const SensorObjectConstPtr& fused_object,
const SensorObjectPtr& sensor_object, const Eigen::Vector3d& ref_pos,
int range) {
double center_distance = (sensor_object->GetBaseObject()->center -
fused_object->GetBaseObject()->center)
.head(2)
.norm();
if (center_distance > s_lidar2radar_association_center_dist_threshold_) {
ADEBUG << "center distance exceed lidar2radar tight threshold: "
<< "center_dist@" << center_distance << ", "
<< "tight_threh@"
<< s_lidar2radar_association_center_dist_threshold_;
return (std::numeric_limits<float>::max)();
}
float distance =
ComputePolygonDistance3d(fused_object, sensor_object, ref_pos, range);
ADEBUG << "ComputeLidarRadar distance: " << distance;
return distance;
}
// @brief: compute the distance between radar observation and
// radar observation
// @return distance of radar vs. radar
float TrackObjectDistance::ComputeRadarRadar(
const SensorObjectPtr& fused_object, const SensorObjectPtr& sensor_object,
const Eigen::Vector3d& ref_pos, int range) {
double center_distance = (sensor_object->GetBaseObject()->center -
fused_object->GetBaseObject()->center)
.head(2)
.norm();
if (center_distance > s_radar2radar_association_center_dist_threshold_) {
ADEBUG << "center distance exceed radar2radar tight threshold: "
<< "center_dist@" << center_distance << ", "
<< "tight_threh@"
<< s_radar2radar_association_center_dist_threshold_;
return (std::numeric_limits<float>::max)();
}
float distance =
ComputePolygonDistance3d(fused_object, sensor_object, ref_pos, range);
ADEBUG << "ComputeRadarRadar distance: " << distance;
return distance;
}
// @brief: compute the distance between lidar observation and
// camera observation
// @return distance of lidar vs. camera
float TrackObjectDistance::ComputeLidarCamera(
const SensorObjectConstPtr& lidar, const SensorObjectConstPtr& camera,
const bool measurement_is_lidar, const bool is_track_id_consistent) {
if (!is_track_id_consistent) {
if (LidarCameraCenterDistanceExceedDynamicThreshold(lidar, camera)) {
return distance_thresh_;
}
}
float distance = distance_thresh_;
// 1. get camera intrinsic and pose
base::BaseCameraModelPtr camera_model = QueryCameraModel(camera);
if (camera_model == nullptr) {
AERROR << "Failed to get camera model for " << camera->GetSensorId();
return distance;
}
Eigen::Matrix4d world2camera_pose;
if (!QueryWorld2CameraPose(camera, &world2camera_pose)) {
AERROR << "Failed to query camera pose";
return distance;
}
Eigen::Matrix4d lidar2world_pose;
if (!QueryLidar2WorldPose(lidar, &lidar2world_pose)) {
AERROR << "Failed to query lidar pose";
return distance;
}
Eigen::Matrix4d lidar2camera_pose =
static_cast<Eigen::Matrix<double, 4, 4, 0, 4, 4>>(world2camera_pose *
lidar2world_pose);
// 2. compute distance of camera vs. lidar observation
const base::PointFCloud& cloud =
lidar->GetBaseObject()->lidar_supplement.cloud;
const base::BBox2DF& camera_bbox =
camera->GetBaseObject()->camera_supplement.box;
const base::Point2DF camera_bbox_ct = camera_bbox.Center();
const Eigen::Vector2d box2d_ct =
Eigen::Vector2d(camera_bbox_ct.x, camera_bbox_ct.y);
ADEBUG << "object cloud size : " << cloud.size();
if (cloud.size() > 0) {
// 2.1 if cloud is not empty, calculate distance according to pts box
// similarity
ProjectionCacheObject* cache_object = QueryProjectionCacheObject(
lidar, camera, camera_model, measurement_is_lidar);
if (cache_object == nullptr) {
AERROR << "Failed to query projection cached object";
return distance;
}
double similarity =
ComputePtsBoxSimilarity(&projection_cache_, cache_object, camera_bbox);
distance =
distance_thresh_ * ((1.0f - static_cast<float>(similarity)) /
(1.0f - vc_similarity2distance_penalize_thresh_));
} else {
// 2.2 if cloud is empty, calculate distance according to ct diff
Eigen::Vector3d projected_velo_ct;
QueryProjectedVeloCtOnCamera(lidar, camera, lidar2camera_pose,
&projected_velo_ct);
if (projected_velo_ct[2] > 0) {
Eigen::Vector2f project_pt2f = camera_model->Project(
Eigen::Vector3f(static_cast<float>(projected_velo_ct[0]),
static_cast<float>(projected_velo_ct[1]),
static_cast<float>(projected_velo_ct[2])));
Eigen::Vector2d project_pt2d = project_pt2f.cast<double>();
Eigen::Vector2d ct_diff = project_pt2d - box2d_ct;
distance =
static_cast<float>(ct_diff.norm()) * vc_diff2distance_scale_factor_;
} else {
distance = std::numeric_limits<float>::max();
}
}
ADEBUG << "ComputeLidarCamera distance: " << distance;
return distance;
}
// @brief: compute the distance between radar observation and
// camera observation
// @return distance of radar vs. camera
float TrackObjectDistance::ComputeRadarCamera(
const SensorObjectConstPtr& radar, const SensorObjectConstPtr& camera) {
float distance = distance_thresh_;
// 1. get camera model and pose
base::BaseCameraModelPtr camera_model = QueryCameraModel(camera);
if (camera_model == nullptr) {
AERROR << "Failed to get camera model for " << camera->GetSensorId();
return distance;
}
Eigen::Matrix4d world2camera_pose;
if (!QueryWorld2CameraPose(camera, &world2camera_pose)) {
return distance;
}
// get camera useful information
const base::BBox2DF& camera_bbox =
camera->GetBaseObject()->camera_supplement.box;
const base::Point2DF camera_bbox_ct = camera_bbox.Center();
const Eigen::Vector2d box2d_ct =
Eigen::Vector2d(camera_bbox_ct.x, camera_bbox_ct.y);
Eigen::Vector2d box2d_size = Eigen::Vector2d(
camera_bbox.xmax - camera_bbox.xmin, camera_bbox.ymax - camera_bbox.ymin);
box2d_size = box2d_size.cwiseMax(rc_min_box_size_);
double width = static_cast<double>(camera_model->get_width());
double height = static_cast<double>(camera_model->get_height());
// get radar useful information
double time_diff = camera->GetTimestamp() - radar->GetTimestamp();
Eigen::Vector3d offset =
radar->GetBaseObject()->velocity.cast<double>() * time_diff;
offset.setZero();
Eigen::Vector3d radar_ct = radar->GetBaseObject()->center + offset;
Eigen::Vector4d local_pt = static_cast<Eigen::Matrix<double, 4, 1, 0, 4, 1>>(
world2camera_pose *
Eigen::Vector4d(radar_ct[0], radar_ct[1], radar_ct[2], 1.0));
std::vector<Eigen::Vector3d> radar_box_vertices;
GetObjectEightVertices(radar->GetBaseObject(), &radar_box_vertices);
std::vector<Eigen::Vector2d> radar_box2d_vertices;
GetModified2DRadarBoxVertices(radar_box_vertices, camera, camera_model,
world2camera_pose, &radar_box2d_vertices);
// compute similarity
double fused_similarity = 0.0;
if (local_pt[2] > 0) {
Eigen::Vector3f pt3f;
pt3f << camera_model->Project(Eigen::Vector3f(
static_cast<float>(local_pt[0]), static_cast<float>(local_pt[1]),
static_cast<float>(local_pt[2]))),
static_cast<float>(local_pt[2]);
Eigen::Vector3d pt3d = pt3f.cast<double>();
if (IsPtInFrustum(pt3d, width, height)) {
// compute similarity on x direction
double x_similarity = ComputeRadarCameraXSimilarity(
pt3d.x(), box2d_ct.x(), box2d_size.x(), rc_x_similarity_params_);
// compute similarity on y direction
double y_similarity = ComputeRadarCameraYSimilarity(
pt3d.y(), box2d_ct.y(), box2d_size.y(), rc_y_similarity_params_);
// compute similarity on height
// use camera car height to modify the radar location
// double h_similarity = ComputeRadarCameraHSimilarity(
// radar, camera, box2d_size.y(), radar_box2d_vertices,
// rc_h_similarity_params_);
// compute similarity on width
// double w_similarity = ComputeRadarCameraWSimilarity(
// radar, width, box2d_size.x(), radar_box2d_vertices,
// rc_w_similarity_params_);
// compute similarity on offset 3d
double loc_similarity = ComputeRadarCameraLocSimilarity(
radar_ct, camera, world2camera_pose, rc_loc_similarity_params_);
// compute similarity on velocity
double velocity_similarity =
ComputeRadarCameraVelocitySimilarity(radar, camera);
// fuse similarity
std::vector<double> multiple_similarities = {
x_similarity, y_similarity, loc_similarity, velocity_similarity
// height_similarity, width_similarity,
};
fused_similarity = FuseMultipleProbabilities(multiple_similarities);
}
}
distance = distance_thresh_ * static_cast<float>(1.0 - fused_similarity) /
(1.0f - rc_similarity2distance_penalize_thresh_);
ADEBUG << "ComputeRadarCamera distance: " << distance;
return distance;
}
// @brief: compute the distance between camera observation and
// camera observation
// @return the distance of camera vs. camera
float TrackObjectDistance::ComputeCameraCamera(
const SensorObjectPtr& fused_camera, const SensorObjectPtr& sensor_camera) {
return (std::numeric_limits<float>::max());
}
// @brief: calculate the similarity between velodyne64 observation and
// camera observation
// @return the similarity which belongs to [0, 1]. When velodyne64
// observation is similar to the camera one, the similarity would
// close to 1. Otherwise, it would close to 0.
// @key idea:
// 1. get camera intrinsic and pose
// 2. compute similarity between camera's box and velodyne64's pts
// within camera's frustum
// @NOTE: original method name is compute_velodyne64_camera_dist_score
double TrackObjectDistance::ComputeLidarCameraSimilarity(
const SensorObjectConstPtr& lidar, const SensorObjectConstPtr& camera,
const bool measurement_is_lidar) {
double similarity = 0.0;
// 1. get camera intrinsic and pose
base::BaseCameraModelPtr camera_model = QueryCameraModel(camera);
if (camera_model == nullptr) {
AERROR << "Failed to get camera model for " << camera->GetSensorId();
return similarity;
}
Eigen::Matrix4d world2camera_pose;
if (!QueryWorld2CameraPose(camera, &world2camera_pose)) {
return similarity;
}
Eigen::Matrix4d lidar2world_pose;
if (!QueryLidar2WorldPose(lidar, &lidar2world_pose)) {
return similarity;
}
// Eigen::Matrix4d lidar2camera_pose = world2camera_pose * lidar2world_pose;
// 2. compute similarity of camera vs. velodyne64 observation
const base::PointFCloud& cloud =
lidar->GetBaseObject()->lidar_supplement.cloud;
const base::BBox2DF& camera_bbox =
camera->GetBaseObject()->camera_supplement.box;
if (cloud.size() > 0) {
ProjectionCacheObject* cache_object = QueryProjectionCacheObject(
lidar, camera, camera_model, measurement_is_lidar);
if (cache_object == nullptr) {
return similarity;
}
similarity =
ComputePtsBoxSimilarity(&projection_cache_, cache_object, camera_bbox);
}
return similarity;
}
// @brief: calculate the similarity between radar observation and
// camera observation
// @return the similarity which belongs to [0, 1]. When radar
// observation is similar to the camera one, the similarity would
// close to 1. Otherwise, it would close to 0.
// @NOTE: original method name is compute_radar_camera_dist_score
// @TODO: THIS METHOD SHOULD RETURN 0, IF RADAR IS IN FRONT OF CAMERA DETECTION
double TrackObjectDistance::ComputeRadarCameraSimilarity(
const SensorObjectConstPtr& radar, const SensorObjectConstPtr& camera) {
double similarity = 0.0;
// 1. get camera intrinsic and pose
base::BaseCameraModelPtr camera_model = QueryCameraModel(camera);
if (camera_model == nullptr) {
AERROR << "Failed to get camera model for " << camera->GetSensorId();
return similarity;
}
Eigen::Matrix4d world2camera_pose;
if (!QueryWorld2CameraPose(camera, &world2camera_pose)) {
return similarity;
}
// 2. get information of camera
const base::BBox2DF& camera_bbox =
camera->GetBaseObject()->camera_supplement.box;
const base::Point2DF camera_bbox_ct = camera_bbox.Center();
const Eigen::Vector2d box2d_ct =
Eigen::Vector2d(camera_bbox_ct.x, camera_bbox_ct.y);
Eigen::Vector2d box2d_size = Eigen::Vector2d(
camera_bbox.xmax - camera_bbox.xmin, camera_bbox.ymax - camera_bbox.ymin);
box2d_size = box2d_size.cwiseMax(rc_min_box_size_);
double width = static_cast<double>(camera_model->get_width());
double height = static_cast<double>(camera_model->get_height());
// 3. get information of radar
Eigen::Vector3d radar_ct = radar->GetBaseObject()->center;
Eigen::Vector4d local_pt = static_cast<Eigen::Matrix<double, 4, 1, 0, 4, 1>>(
world2camera_pose *
Eigen::Vector4d(radar_ct[0], radar_ct[1], radar_ct[2], 1.0));
// 4. similarity computation
Eigen::Vector3d camera_ct = camera->GetBaseObject()->center;
Eigen::Vector3d camera_ct_c =
(world2camera_pose * camera_ct.homogeneous()).head(3);
double depth_diff = local_pt.z() - camera_ct_c.z();
const double depth_diff_th = 0.1;
depth_diff /= camera_ct_c.z();
if (local_pt[2] > 0 && depth_diff > -depth_diff_th) {
Eigen::Vector3f pt3f;
pt3f << camera_model->Project(Eigen::Vector3f(
static_cast<float>(local_pt[0]), static_cast<float>(local_pt[1]),
static_cast<float>(local_pt[2]))),
static_cast<float>(local_pt[2]);
Eigen::Vector3d pt3d = pt3f.cast<double>();
if (IsPtInFrustum(pt3d, width, height)) {
rc_x_similarity_params_2_.welsh_loss_scale_ =
rc_x_similarity_params_2_welsh_loss_scale_;
// compute similarity on x direction
double x_similarity = ComputeRadarCameraXSimilarity(
pt3d.x(), box2d_ct.x(), box2d_size.x(), rc_x_similarity_params_2_);
// compute similarity on y direction
double y_similarity = ComputeRadarCameraXSimilarity(
pt3d.y(), box2d_ct.y(), box2d_size.y(), rc_x_similarity_params_2_);
std::vector<double> multiple_similarities = {x_similarity, y_similarity};
similarity = FuseMultipleProbabilities(multiple_similarities);
}
}
return similarity;
}
// @brief: compute polygon distance between fused object and sensor object
// @return 3d distance between fused object and sensor object
float TrackObjectDistance::ComputePolygonDistance3d(
const SensorObjectConstPtr& fused_object,
const SensorObjectPtr& sensor_object, const Eigen::Vector3d& ref_pos,
int range) {
const base::ObjectConstPtr& obj_f = fused_object->GetBaseObject();
Eigen::Vector3d fused_poly_center(0, 0, 0);
if (!QueryPolygonDCenter(obj_f, ref_pos, range, &fused_poly_center)) {
return (std::numeric_limits<float>::max());
}
const base::ObjectConstPtr obj_s = sensor_object->GetBaseObject();
Eigen::Vector3d sensor_poly_center(0, 0, 0);
if (!QueryPolygonDCenter(obj_s, ref_pos, range, &sensor_poly_center)) {
return (std::numeric_limits<float>::max());
}
double fusion_timestamp = fused_object->GetTimestamp();
double sensor_timestamp = sensor_object->GetTimestamp();
double time_diff = sensor_timestamp - fusion_timestamp;
fused_poly_center(0) += obj_f->velocity(0) * time_diff;
fused_poly_center(1) += obj_f->velocity(1) * time_diff;
float distance =
ComputeEuclideanDistance(fused_poly_center, sensor_poly_center);
return distance;
}
// @brief: compute euclidean distance of input pts
// @return eculidean distance of input pts
float TrackObjectDistance::ComputeEuclideanDistance(
const Eigen::Vector3d& des, const Eigen::Vector3d& src) {
Eigen::Vector3d diff_pos = des - src;
float distance = static_cast<float>(
std::sqrt(diff_pos.head(2).cwiseProduct(diff_pos.head(2)).sum()));
return distance;
}
// @brief: compute polygon center
// @return true if get center successfully, otherwise return false
bool TrackObjectDistance::ComputePolygonCenter(
const base::PolygonDType& polygon, Eigen::Vector3d* center) {
int size = static_cast<int>(polygon.size());
if (size == 0) {
return false;
}
*center = Eigen::Vector3d(0, 0, 0);
for (int i = 0; i < size; ++i) {
const auto& point = polygon.at(i);
(*center)[0] += point.x;
(*center)[1] += point.y;
}
(*center) /= size;
return true;
}
// @brief: compute polygon center
// @return true if get center successfully, otherwise return false
bool TrackObjectDistance::ComputePolygonCenter(
const base::PolygonDType& polygon, const Eigen::Vector3d& ref_pos,
int range, Eigen::Vector3d* center) {
base::PolygonDType polygon_part;
std::map<double, int> distance2idx;
for (size_t idx = 0; idx < polygon.size(); ++idx) {
const auto& point = polygon.at(idx);
double distance =
sqrt(pow(point.x - ref_pos(0), 2) + pow(point.y - ref_pos(1), 2));
distance2idx.insert(std::make_pair(distance, idx));
}
int size = static_cast<int>(distance2idx.size());
int nu = std::max(range, size / range + 1);
nu = std::min(nu, size);
int count = 0;
std::map<double, int>::iterator it = distance2idx.begin();
for (; it != distance2idx.end(), count < nu; ++it, ++count) {
polygon_part.push_back(polygon[it->second]);
}
bool state = ComputePolygonCenter(polygon_part, center);
return state;
}
} // namespace fusion
} // namespace perception
} // namespace apollo
| wanglei828/apollo | modules/perception/fusion/lib/data_association/hm_data_association/track_object_distance.cc | C++ | apache-2.0 | 33,912 |
package io.skysail.server.app.um.db.users.resources;
import io.skysail.api.links.Link;
import io.skysail.api.responses.SkysailResponse;
import io.skysail.server.app.um.db.UmApplication;
import io.skysail.server.app.um.db.domain.User;
import io.skysail.server.restlet.resources.EntityServerResource;
import java.util.List;
public class UserResource extends EntityServerResource<User> {
private UmApplication app;
protected void doInit() {
app = (UmApplication) getApplication();
}
public User getEntity() {
return app.getUserRepository().findOne(getAttribute("id"));
}
public List<Link> getLinks() {
return super.getLinks(PutUserResource.class);
}
public SkysailResponse<User> eraseEntity() {
app.getUserRepository().delete(getAttribute("id"));
return new SkysailResponse<>();
}
@Override
public String redirectTo() {
return super.redirectTo(UsersResource.class);
}
}
| evandor/skysail-framework | skysail.server.app.um.db/src/io/skysail/server/app/um/db/users/resources/UserResource.java | Java | apache-2.0 | 972 |
function getFunction(f,b){
return function myNextTick(){
console.log(f + " " + b);
};
}
process.nextTick(getFunction("foo", "bar"));
| marcos-goes/livro_node | 04/next-tick-gambi.js | JavaScript | apache-2.0 | 146 |
/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.devicefarm.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import com.amazonaws.services.devicefarm.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* CreateUploadResult JSON Unmarshaller
*/
public class CreateUploadResultJsonUnmarshaller implements
Unmarshaller<CreateUploadResult, JsonUnmarshallerContext> {
public CreateUploadResult unmarshall(JsonUnmarshallerContext context)
throws Exception {
CreateUploadResult createUploadResult = new CreateUploadResult();
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("upload", targetDepth)) {
context.nextToken();
createUploadResult.setUpload(UploadJsonUnmarshaller
.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 createUploadResult;
}
private static CreateUploadResultJsonUnmarshaller instance;
public static CreateUploadResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new CreateUploadResultJsonUnmarshaller();
return instance;
}
}
| dump247/aws-sdk-java | aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/transform/CreateUploadResultJsonUnmarshaller.java | Java | apache-2.0 | 2,813 |
from muntjac.ui.vertical_layout import VerticalLayout
from muntjac.ui.menu_bar import MenuBar, ICommand
from muntjac.terminal.external_resource import ExternalResource
class MenuBarItemStylesExample(VerticalLayout):
def __init__(self):
super(MenuBarItemStylesExample, self).__init__()
self._menubar = MenuBar()
menuCommand = MenuCommand(self)
# Save reference to individual items so we can add sub-menu items to
# them
f = self._menubar.addItem('File', None)
newItem = f.addItem('New', None)
f.addItem('Open f...', menuCommand)
f.addSeparator()
# Add a style name for a menu item, then use CSS to alter the visuals
f.setStyleName('file')
newItem.addItem('File', menuCommand)
newItem.addItem('Folder', menuCommand)
newItem.addItem('Project...', menuCommand)
f.addItem('Close', menuCommand)
f.addItem('Close All', menuCommand).setStyleName('close-all')
f.addSeparator()
f.addItem('Save', menuCommand)
f.addItem('Save As...', menuCommand)
f.addItem('Save All', menuCommand)
edit = self._menubar.addItem('Edit', None)
edit.addItem('Undo', menuCommand)
edit.addItem('Redo', menuCommand).setEnabled(False)
edit.addSeparator()
edit.addItem('Cut', menuCommand)
edit.addItem('Copy', menuCommand)
edit.addItem('Paste', menuCommand)
edit.addSeparator()
find = edit.addItem('Find/Replace', menuCommand)
# Actions can be added inline as well, of course
find.addItem('Google Search', SearchCommand(self))
find.addSeparator()
find.addItem('Find/Replace...', menuCommand)
find.addItem('Find Next', menuCommand)
find.addItem('Find Previous', menuCommand)
view = self._menubar.addItem('View', None)
view.addItem('Show/Hide Status Bar', menuCommand)
view.addItem('Customize Toolbar...', menuCommand)
view.addSeparator()
view.addItem('Actual Size', menuCommand)
view.addItem('Zoom In', menuCommand)
view.addItem('Zoom Out', menuCommand)
self.addComponent(self._menubar)
class SearchCommand(ICommand):
def __init__(self, c):
self._c = c
def menuSelected(self, selectedItem):
er = ExternalResource('http://www.google.com')
self._c.getWindow().open(er)
class MenuCommand(ICommand):
def __init__(self, c):
self._c = c
def menuSelected(self, selectedItem):
self._c.getWindow().showNotification('Action '
+ selectedItem.getText())
| rwl/muntjac | muntjac/demo/sampler/features/menubar/MenuBarItemStylesExample.py | Python | apache-2.0 | 2,645 |
package edu.towson.cis.cosc603.project2.monopoly.gui;
import edu.towson.cis.cosc603.project2.monopoly.Cell;
import edu.towson.cis.cosc603.project2.monopoly.Player;
import edu.towson.cis.cosc603.project2.monopoly.UtilityCell;
// TODO: Auto-generated Javadoc
/**
* The Class UtilCellInfoFormatter.
*/
public class UtilCellInfoFormatter extends OwnerName implements CellInfoFormatter {
/* (non-Javadoc)
* @see edu.towson.cis.cosc603.project2.monopoly.gui.CellInfoFormatter#format(edu.towson.cis.cosc603.project2.monopoly.Cell)
*/
public String format(Cell cell) {
UtilityCell c = (UtilityCell)cell;
StringBuffer buf = new StringBuffer();
String ownerName = getOwnerName(cell);
buf.append("<html><b><font color='olive'>")
.append(cell.getName())
.append("</font></b><br>")
.append("$").append(c.getPrice())
.append("<br>Owner: ").append(ownerName)
.append("</html>");
return buf.toString();
}
}
| mtendu/cosc603-tendulkar-project2 | Monopoly/Monopoly/src/edu/towson/cis/cosc603/project2/monopoly/gui/UtilCellInfoFormatter.java | Java | apache-2.0 | 1,011 |
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// == Global variables start
// -- screen info
var _wh = getScreenSize();
var gDevWidth = 1920;
var gDevHeight = 1080;
var gTargetWidth = 960;
var gTargetHeight = 540;
var gDeviceWidth = Math.max(_wh.width, _wh.height);
var gDeviceHeight = Math.min(_wh.width, _wh.height);
var gGameWidth = gDeviceWidth;
var gGameHeight = gDeviceHeight;
var gGameOffsetX = 0;
var gGameOffsetY = 0;
if (gDeviceWidth / gDeviceHeight > 1.78) {
gGameWidth = Math.round(gGameHeight * 1.777778);
gGameOffsetX = (gDeviceWidth - gGameWidth) / 2;
} else if (gDeviceWidth / gDeviceHeight < 1.77) {
gGameHeight = Math.round(gGameWidth / 1.777778);
gGameOffsetY = (gDeviceHeight - gGameHeight) / 2;
}
var gRatioTarget = gTargetWidth / gDevWidth;
var gRatioDevice = gGameWidth / gDevWidth;
// -- others
var gZeroColor = { r: 0, g: 0, b: 0 };
// == Global variables en
// Utils for sending message
var gUserPlan = -1;
var gLastSendingTime = 0;
var Utils = function () {
function Utils() {
_classCallCheck(this, Utils);
}
_createClass(Utils, null, [{
key: 'checkCanSendMessage',
value: function checkCanSendMessage() {
gUserPlan = -1;
if (getUserPlan !== undefined && sendNormalMessage !== undefined) {
gUserPlan = getUserPlan();
}
}
}, {
key: 'canSendMessage',
value: function canSendMessage() {
if (gUserPlan == -1) {
return;
}
var during = Date.now() - gLastSendingTime;
if (gUserPlan >= 0 && during > 60 * 60 * 1000) {
return true;
}
}
}, {
key: 'sendMessage',
value: function sendMessage(topMsg, msg, force) {
if (force || Utils.canSendMessage()) {
gLastSendingTime = Date.now();
if (force) {
console.log(sendUrgentMessage(topMsg, msg));
} else {
console.log(sendNormalMessage(topMsg, msg));
}
}
}
}, {
key: 'nearColor',
value: function nearColor(c, c1, c2) {
var d1 = Math.abs(c1.r - c.r) + Math.abs(c1.g - c.g) + Math.abs(c1.b - c.b);
var d2 = Math.abs(c2.r - c.r) + Math.abs(c2.g - c.g) + Math.abs(c2.b - c.b);
return d1 - d2;
}
}, {
key: 'mergeColor',
value: function mergeColor(c1, c2) {
return {
r: Math.round((c1.r + c2.r) / 2),
g: Math.round((c1.g + c2.g) / 2),
b: Math.round((c1.b + c2.b) / 2)
};
}
}, {
key: 'diffColor',
value: function diffColor(c, c1) {
return Math.abs(c1.r - c.r) + Math.abs(c1.g - c.g) + Math.abs(c1.b - c.b);
}
}, {
key: 'minMaxDiff',
value: function minMaxDiff(c) {
var max = Math.max(Math.max(c.r, c.g), c.b);
var min = Math.min(Math.min(c.r, c.g), c.b);
return max - min;
}
}, {
key: 'isSameColor',
value: function isSameColor(c1, c2) {
var d = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 25;
if (Math.abs(c1.r - c2.r) < d && Math.abs(c1.g - c2.g) < d && Math.abs(c1.b - c2.b) < d) {
return true;
}
return false;
}
}, {
key: 'targetToDevice',
value: function targetToDevice(xy) {
var r = gRatioDevice / gRatioTarget;
return { x: gGameOffsetX + xy.x * r, y: gGameOffsetY + xy.y * r };
}
}]);
return Utils;
}();
Utils.checkCanSendMessage();
var Rect = function () {
function Rect(x1, y1, x2, y2) {
_classCallCheck(this, Rect);
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.w = x2 - x1;
this.h = y2 - y1;
this.tx = this.x1 * gRatioTarget;
this.ty = this.y1 * gRatioTarget;
this.tw = (this.x2 - this.x1) * gRatioTarget;
this.th = (this.y2 - this.y1) * gRatioTarget;
}
_createClass(Rect, [{
key: 'crop',
value: function crop(img) {
return cropImage(img, this.tx, this.ty, this.tw, this.th);
}
}]);
return Rect;
}();
var Point = function () {
function Point(x, y) {
_classCallCheck(this, Point);
this.x = x;
this.y = y;
this.tx = this.x * gRatioTarget;
this.ty = this.y * gRatioTarget;
this.dx = gGameOffsetX + this.x * gRatioDevice;
this.dy = gGameOffsetY + this.y * gRatioDevice;
}
_createClass(Point, [{
key: 'tap',
value: function (_tap) {
function tap() {
return _tap.apply(this, arguments);
}
tap.toString = function () {
return _tap.toString();
};
return tap;
}(function () {
var times = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
while (times > 0) {
if (delay > 0) {
sleep(delay);
}
tap(this.dx, this.dy, 20);
times--;
}
})
}, {
key: 'tapDown',
value: function (_tapDown) {
function tapDown() {
return _tapDown.apply(this, arguments);
}
tapDown.toString = function () {
return _tapDown.toString();
};
return tapDown;
}(function () {
tapDown(this.dx, this.dy, 20);
})
}, {
key: 'tapUp',
value: function (_tapUp) {
function tapUp() {
return _tapUp.apply(this, arguments);
}
tapUp.toString = function () {
return _tapUp.toString();
};
return tapUp;
}(function () {
tapUp(this.dx, this.dy, 20);
})
}, {
key: 'moveTo',
value: function (_moveTo) {
function moveTo() {
return _moveTo.apply(this, arguments);
}
moveTo.toString = function () {
return _moveTo.toString();
};
return moveTo;
}(function () {
moveTo(this.dx, this.dy, 20);
})
}]);
return Point;
}();
var FeaturePoint = function (_Point) {
_inherits(FeaturePoint, _Point);
// need: true => should exist, false => should not exist
function FeaturePoint(x, y, r, g, b, need) {
var diff = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 25;
_classCallCheck(this, FeaturePoint);
var _this = _possibleConstructorReturn(this, (FeaturePoint.__proto__ || Object.getPrototypeOf(FeaturePoint)).call(this, x, y));
_this.r = r;
_this.g = g;
_this.b = b;
_this.d = diff;
_this.need = need;
return _this;
}
_createClass(FeaturePoint, [{
key: 'check',
value: function check(img) {
var c = getImageColor(img, this.tx, this.ty);
if (this.need && !Utils.isSameColor(c, this, this.d)) {
return false;
} else if (!this.need && Utils.isSameColor(c, this)) {
return false;
}
return true;
}
}, {
key: 'print',
value: function print(img) {
var c = getImageColor(img, this.tx, this.ty);
console.log('target', this.tx, this.ty, 'param', this.x + ', ' + this.y + ', ' + c.r + ', ' + c.g + ', ' + c.b + ', true');
}
}]);
return FeaturePoint;
}(Point);
var PageFeature = function () {
function PageFeature(name, featurPoints) {
_classCallCheck(this, PageFeature);
this.name = name || 'Unknown';
this.featurPoints = featurPoints || [];
}
_createClass(PageFeature, [{
key: 'check',
value: function check(img) {
for (var i = 0; i < this.featurPoints.length; i++) {
var _p = this.featurPoints[i];
if (!_p.check(img)) {
return false;
}
}
return true;
}
}, {
key: 'print',
value: function print(img) {
for (var i = 0; i < this.featurPoints.length; i++) {
var _p2 = this.featurPoints[i];
_p2.print(img);
}
}
}, {
key: 'tap',
value: function tap() {
var idx = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
this.featurPoints[idx].tap();
}
}]);
return PageFeature;
}();
var GameInfo = function GameInfo() {
_classCallCheck(this, GameInfo);
this.hpBarRect = new Rect(122, 30, 412, 51);
this.mpBarRect = new Rect(122, 58, 412, 72);
this.expBarRect = new Rect(16, 1070, 1904, 1072);
this.zeroRect = new Rect(0, 0, 1, 1);
this.mapRect = new Rect(384, 217, 1920, 937); // 1536, 720
this.regionTypeRect = new Rect(1710, 470, 1816, 498);
this.storeHpRect = new Rect(78, 274, 80 + 122, 276 + 122);
this.mapSelector = new Rect(56, 339, 350, 937); // h 112
this.moneyRect = new Rect(990, 40, 1150, 80);
this.centerRect = new Rect(600, 200, 1400, 800);
this.storeOther = new Point(510, 220);
this.store10 = new Point(670, 970);
this.store100 = new Point(900, 970);
this.store1000 = new Point(1100, 970);
this.storeMax = new Point(1300, 970);
this.storeHp = new Point(150, 330);
this.storeArrow = new Point(260, 560);
this.storeBuy = new Point(1600, 970);
this.storeBuy2 = new Point(1130, 882);
this.storeSelfOrder = new Point(200, 970);
this.storeBuyOrder = new Point(1500, 970);
this.storeBuyOrder2 = new Point(1750, 970);
this.storeSpecial = new Point(1140, 340);
this.getReward = new Point(1680, 320);
this.signAlliance = new Point(1820, 252);
this.itemBtns = [new Point(730, 960), new Point(840, 960), new Point(960, 960), new Point(1060, 960), new Point(1180, 960), new Point(1400, 960), new Point(1510, 960), new Point(1620, 960), new Point(1730, 960), new Point(1840, 960), new Point(1280, 960)];
this.unknownBtn = new Point(1100, 800);
this.mapBtn = new Point(1740, 300);
this.mapDetailBtn = new Point(700, 160);
this.mapController = new Point(290, 860);
this.mapControllerL = new Point(190, 860);
this.mapControllerR = new Point(390, 860);
this.mapControllerT = new Point(290, 760);
this.mapControllerB = new Point(290, 960);
this.mapMoveBtn = new Point(1588, 986);
this.mapFloorBtn = new Point(1120, 886);
this.storeMode = new PageFeature('storeMode', [new FeaturePoint(116, 862, 224, 155, 46, true, 32), new FeaturePoint(223, 862, 28, 45, 70, true, 32), new FeaturePoint(196, 946, 43, 33, 17, true, 32), new FeaturePoint(692, 710, 0, 0, 0, true, 32), new FeaturePoint(830, 710, 0, 0, 0, true, 32), new FeaturePoint(1487, 944, 25, 22, 16, true, 32)]);
this.menuOffEvent = new PageFeature('menuOffEvent', [new FeaturePoint(1850, 56, 173, 166, 147, true, 80), new FeaturePoint(1850, 66, 173, 166, 147, true, 80), new FeaturePoint(1860, 76, 173, 166, 147, true, 80), new FeaturePoint(1880, 42, 242, 30, 26, true, 30)]);
this.menuSign = new PageFeature('menuOpenSign', [new FeaturePoint(1652, 250, 242, 30, 26, true, 80)]);
this.menuMail = new PageFeature('menuOpenMail', [new FeaturePoint(1652, 466, 242, 30, 26, true, 80)]);
this.menuAlliance = new PageFeature('menuOpenAlliance', [new FeaturePoint(1418, 360, 242, 30, 26, true, 80)]);
this.menuOnBtn = new PageFeature('menuOn', [new FeaturePoint(1844, 56, 245, 245, 241, true, 30), new FeaturePoint(1844, 66, 128, 70, 56, true, 30), new FeaturePoint(1844, 76, 245, 220, 215, true, 30)]);
this.menuOffBtn = new PageFeature('menuOff', [new FeaturePoint(1850, 56, 173, 166, 147, true, 80), new FeaturePoint(1850, 66, 173, 166, 147, true, 80), new FeaturePoint(1860, 76, 173, 166, 147, true, 80)]);
this.autoPlayBtn = new PageFeature('autoPlayOff', [new FeaturePoint(1430, 768, 140, 154, 127, true, 60), new FeaturePoint(1476, 772, 140, 157, 130, true, 60)]);
this.killNumber = new PageFeature('killNumber', [new FeaturePoint(1678, 538, 65, 62, 45, true, 60), new FeaturePoint(1780, 554, 235, 83, 44, true, 40), new FeaturePoint(1810, 554, 220, 59, 39, true, 40), new FeaturePoint(1804, 532, 255, 186, 142, true, 40)]);
this.selfSkillBtn = new PageFeature('selfSkillOff', [new FeaturePoint(1594, 601, 141, 147, 137, true, 60), new FeaturePoint(1591, 624, 117, 128, 114, true, 60)]);
this.attackBtn = new PageFeature('attackOff', [new FeaturePoint(1634, 769, 165, 180, 170, true, 60)]);
this.disconnectBtn = new PageFeature('disconnect', [new FeaturePoint(840, 880, 34, 51, 79, true, 20), new FeaturePoint(1080, 880, 34, 51, 79, true, 20), new FeaturePoint(1170, 880, 31, 20, 14, true, 20), new FeaturePoint(1150, 916, 31, 24, 14, true, 20)]);
this.loginBtn = new PageFeature('login', [new FeaturePoint(335, 310, 236, 175, 110, true, 40), new FeaturePoint(430, 415, 161, 123, 78, true, 40), new FeaturePoint(140, 145, 60, 55, 55, true, 40), new FeaturePoint(280, 191, 140, 100, 90, true, 40)]);
this.enterBtn = new PageFeature('enter', [new FeaturePoint(1480, 990, 31, 47, 70, true, 20), new FeaturePoint(1750, 990, 31, 47, 70, true, 20), new FeaturePoint(1690, 990, 31, 47, 70, true, 20)]);
this.beAttacked = new PageFeature('beAttacked', [new FeaturePoint(1616, 744, 210, 90, 50, true, 45), new FeaturePoint(1676, 744, 210, 90, 50, true, 45), new FeaturePoint(1666, 756, 210, 90, 50, true, 45), new FeaturePoint(1624, 750, 210, 90, 50, true, 45), new FeaturePoint(1800, 818, 240, 160, 140, true, 30), new FeaturePoint(1634, 769, 165, 180, 170, false, 50)]);
this.storeExceed = new PageFeature('storeExceed', [new FeaturePoint(1102, 812, 33, 23, 0, true, 40)]);
};
var RoleState = function () {
function RoleState(gi) {
_classCallCheck(this, RoleState);
this.gi = gi;
this.lastHP = 0;
this.lastMP = 0;
this.hp = 0;
this.mp = 0;
this.exp = 0;
this.isDisconnect = false;
this.isLogin = false;
this.isEnter = false;
this.isMenuOn = false;
this.isMenuOff = false;
this.lastSafeRegion = false;
this.isSafeRegion = false;
this.isAutoPlay = false;
this.isAttacking = false;
this.isSelfSkill = false;
this.isAttacked = false;
this.hasKillNumber = false;
this.autoPlayOffCount = 5;
this.isPoison = false;
this.movingScore = 0.9;
this.isMovingCount = 0;
this.shouldTapMiddle = true; // determine to tap middle or tap back
}
_createClass(RoleState, [{
key: 'print',
value: function print() {
if (Math.abs(this.lastHP - this.hp) > 5 || Math.abs(this.lastMP - this.mp) > 5) {
console.log('\u8840\u91CF\uFF1A' + this.hp + '\uFF0C\u9B54\u91CF\uFF1A' + this.mp);
this.lastHP = this.hp;
this.lastMP = this.mp;
}
}
}]);
return RoleState;
}();
var LineageM = function () {
function LineageM(config) {
_classCallCheck(this, LineageM);
this.config = config || { conditions: [] };
this.gi = new GameInfo();
this.rState = new RoleState(this.gi);
this.localPath = getStoragePath() + '/scripts/com.r2studio.LineageM/images';
this._loop = false;
this._img = 0;
this.refreshScreen();
// load images
this.images = {
safeRegion: openImage(this.localPath + '/safeRegionType.png'),
normalRegion: openImage(this.localPath + '/normalRegionType.png'),
hpWater: openImage(this.localPath + '/hp.png'),
store: openImage(this.localPath + '/store.png'),
store2: openImage(this.localPath + '/store2.png'),
arrow: openImage(this.localPath + '/arrow.png'),
floor1: openImage(this.localPath + '/floor1.png'),
floor2: openImage(this.localPath + '/floor2.png')
};
// this.gi.menuOffEvent.print(this._img);
this.tmpExp = 0;
this.isRecordLocation = false;
}
_createClass(LineageM, [{
key: 'safeSleep',
value: function safeSleep(t) {
while (this._loop && t > 0) {
t -= 100;
sleep(100);
}
}
}, {
key: 'refreshScreen',
value: function refreshScreen() {
var startTime = Date.now();
var newImg = getScreenshotModify(gGameOffsetX, gGameOffsetY, gGameWidth, gGameHeight, gTargetWidth, gTargetHeight, 80);
if (this._img !== 0) {
if (this.config.grabMonster) {
var s = getIdentityScore(this._img, newImg);
if (this.rState.movingScore - s > 0.05) {
this.rState.isMovingCount++;
} else {
this.rState.isMovingCount = 0;
}
this.rState.movingScore = this.rState.movingScore * 0.95 + s * 0.05;
}
releaseImage(this._img);
this._img = 0;
}
this._img = newImg;
if (Date.now() - startTime < 120) {
sleep(120);
}
return this._img;
}
}, {
key: 'checkIsSystemPage',
value: function checkIsSystemPage() {
if (this.rState.isLogin) {
console.log('登入遊戲,等待 2 秒');
this.gi.loginBtn.tap();
this.safeSleep(2 * 1000);
return true;
}
if (this.rState.isEnter) {
console.log('進入遊戲,等待 10 秒');
this.gi.enterBtn.tap();
this.safeSleep(10 * 1000);
return true;
}
if (this.rState.isDisconnect) {
console.log('重新連線中,等待 10 秒');
this.gi.disconnectBtn.tap();
this.safeSleep(10 * 1000);
return true;
}
if (!this.rState.isMenuOn && !this.rState.isMenuOff) {
if (this.rState.shouldTapMiddle) {
console.log('未知狀態,隨便點看看,等待 5 秒');
this.gi.enterBtn.tap();
this.safeSleep(5 * 1000);
this.rState.shouldTapMiddle = false;
return true;
} else {
console.log('未知狀態,等待 5 秒');
keycode('BACK', 100);
this.safeSleep(5 * 1000);
this.rState.shouldTapMiddle = true;
return true;
}
}
return false;
}
}, {
key: 'checkBeAttacked',
value: function checkBeAttacked() {
if (this.config.beAttackedRandTeleport && this.gi.beAttacked.check(this._img)) {
var c = getImageColor(this._img, this.gi.zeroRect.tx, this.gi.zeroRect.ty);
if (c.r > (c.g + c.b) / 2) {
console.log('警告!你被攻擊了,使用按鈕 7');
this.gi.itemBtns[6].tap();
this.safeSleep(2000);
return true;
}
}
return false;
}
}, {
key: 'updateGlobalState',
value: function updateGlobalState() {
this.rState.isDisconnect = this.gi.disconnectBtn.check(this._img);
this.rState.isLogin = this.gi.loginBtn.check(this._img);
this.rState.isEnter = this.gi.enterBtn.check(this._img);
if (this.rState.isDisconnect || this.rState.isLogin || this.rState.isEnter) {
return;
}
this.rState.isMenuOn = this.gi.menuOnBtn.check(this._img);
this.rState.isMenuOff = this.gi.menuOffBtn.check(this._img);
// console.log(this.rState.isMenuOn, this.rState.isMenuOff);
if (!this.rState.isMenuOn && !this.rState.isMenuOff) {
return;
}
if (this.rState.isMenuOn) {
return;
}
this.rState.hp = this.getHpPercent();
if (this.rState.hp < 30 && this.rState.hp > 0.1) {
sleep(300);
this.refreshScreen();
this.rState.hp = this.getHpPercent();
}
this.rState.mp = this.getMpPercent();
// this.rState.exp = this.getExpPercent();
this.rState.isSafeRegion = this.isSafeRegionState();
this.rState.isAttacking = !this.gi.attackBtn.check(this._img);
this.rState.isSelfSkill = !this.gi.selfSkillBtn.check(this._img);
this.rState.hasKillNumber = this.gi.killNumber.check(this._img);
if (this.gi.autoPlayBtn.check(this._img)) {
this.rState.autoPlayOffCount++;
} else {
this.rState.autoPlayOffCount = 0;
}
if (this.rState.autoPlayOffCount > 4) {
this.rState.isAutoPlay = false;
} else {
this.rState.isAutoPlay = true;
}
this.rState.print();
}
}, {
key: 'checkCondiction',
value: function checkCondiction() {
for (var i = 0; i < this.config.conditions.length && this._loop; i++) {
var cd = this.config.conditions[i];
if (cd.useTime === undefined) {
cd.useTime = 0;
}
if (!cd.enabled) {
continue;
}
if (Date.now() - cd.useTime < cd.interval) {
continue;
}
var value = this.rState[cd.type];
if (value < 0.1) {
continue;
}
if (cd.type === 'exp') {
if (this.rState.exp !== this.tmpExp) {
this.gi.itemBtns[cd.btn].tap(1, 50);
console.log('\u4F7F\u7528\u6309\u9215 ' + (cd.btn + 1) + '\uFF0C\u689D\u4EF6 ' + cd.type + ' ' + (cd.op === 1 ? '大於' : '小於') + ' ' + cd.value + ' (' + value + ')');
cd.useTime = Date.now();
break;
}
} else if (value * cd.op > cd.value * cd.op) {
if (cd.btn >= 0 && cd.btn < this.gi.itemBtns.length) {
if (cd.btn === 7 && this.rState.isSafeRegion && !this.rState.isAttacking) {
continue;
}
this.gi.itemBtns[cd.btn].tap(1, 50);
console.log('\u4F7F\u7528\u6309\u9215 ' + (cd.btn + 1) + '\uFF0C\u689D\u4EF6 ' + cd.type + ' ' + (cd.op === 1 ? '大於' : '小於') + ' ' + cd.value + ' (' + value + ')');
cd.useTime = Date.now();
break;
}
}
}
}
}, {
key: 'start',
value: function start() {
this._loop = true;
var goBackTime = Date.now();
var useHomeTime = Date.now();
var poisonTime = Date.now();
var tmpTime = Date.now();
var noMonsterTime = Date.now();
var isBuy = false;
var receiveTime = 0;
while (this._loop) {
sleep(100);
this.refreshScreen();
if (this.checkBeAttacked()) {
this.sendDangerMessage('你被攻擊了,使用順卷');
continue;
}
this.updateGlobalState();
if (this.checkIsSystemPage()) {
continue;
}
if (this.rState.isMenuOn) {
console.log('關閉選單');
this.gi.menuOnBtn.tap();
this.safeSleep(500);
continue;
}
// go home (8th btn), rand teleport (7th btn)
if (this.rState.isSafeRegion && !this.rState.isAttacking) {
var isAttacking = true;
for (var i = 0; i < 2; i++) {
this.safeSleep(1000);
this.refreshScreen();
this.rState.isAttacking = !this.gi.attackBtn.check(this._img);
if (!this.rState.isAttacking) {
isAttacking = false;
break;
}
}
if (this.rState.isAutoPlay) {
console.log('安全區域,關閉自動攻擊', this.rState.autoPlayOffCount);
this.gi.autoPlayBtn.tap();
sleep(1000);
continue;
}
if (!isAttacking) {
if (!isBuy && this.config.autoBuyFirstSet) {
this.checkAndBuyItems();
isBuy = true;
} else if (this.config.inHomeUseBtn && Date.now() - useHomeTime > 4000) {
this.gi.itemBtns[6].tap();
useHomeTime = Date.now();
} else if (this.config.mapSelect > 0 && this.rState.hp > 40) {
console.log('移動到地圖', this.config.mapSelect);
this.goToMapPage();
this.slideMapSelector(this.config.mapSelect);
}
}
} else {
if (this.rState.isAttacking) {
noMonsterTime = Date.now();
}
isBuy = false;
if (this.config.dangerousGoHome && this.rState.hp < 25 && this.rState.hp > 0.1) {
this.gi.itemBtns[7].tap(1, 100);
this.safeSleep(1000);
console.log('危險,血量少於 25%,使用按鈕 8');
this.sendDangerMessage('危險,血量少於25%,回家');
continue;
}
if (!this.rState.isAutoPlay && this.config.autoAttack) {
console.log('開啟自動攻擊');
this.gi.autoPlayBtn.tap();
this.rState.autoPlayOffCount = 0;
sleep(600);
continue;
}
if (this.config.autoUseAntidote && this.gi.isPoison && Date.now() - poisonTime > 1500) {
console.log('中毒,使用解毒劑,使用按鈕 6');
sleep(500);
this.gi.itemBtns[5].tap();
poisonTime = Date.now();
continue;
}
var cd = this.config.conditions[0];
if (this.config.grabMonster && this.rState.isAttacking && this.rState.isMovingCount > 0 && Date.now() - tmpTime > cd.interval) {
tmpTime = Date.now();
var value = this.rState[cd.type];
if (value > 0.1 && value * cd.op > cd.value * cd.op) {
this.gi.itemBtns[cd.btn].tap(1, 50);
console.log('尋找怪物, 使用按鈕 1');
this.gi.itemBtns[0].tap();
} else {
console.log('尋找怪物, HP/MP 不滿足');
}
continue;
}
if (this.config.autoTeleport && Date.now() - noMonsterTime > 6000) {
console.log('沒有怪物, 使用按鈕 7');
noMonsterTime = Date.now();
this.gi.itemBtns[7 - 1].tap(2, 200);
continue;
}
}
// console.log('Check conditions');
this.checkCondiction();
if (this.config.autoReceiveReward && Date.now() - receiveTime > 300 * 1000) {
this.checkAndAutoGetReward();
receiveTime = Date.now();
}
this.sendMoneyInfo();
if (this.rState.lastSafeRegion != this.rState.isSafeRegion) {
this.rState.lastSafeRegion = this.rState.isSafeRegion;
if (this.rState.lastSafeRegion) {
console.log('安全區域');
}
}
if (this.rState.isSafeRegion) {
continue;
}
if (this.config.goBackInterval != 0 && !this.isRecordLocation) {
console.log('記錄現在位置');
this.goToMapPage();
this.recordCurrentLocation();
this.gi.menuOnBtn.tap();
this.isRecordLocation = true;
continue;
}
// go back to record location
if (this.config.goBackInterval != 0 && Date.now() - goBackTime > this.config.goBackInterval) {
console.log('嘗試走回紀錄點');
this.goToMapPage();
var diffXY = this.getDiffRecordLocation();
this.gi.menuOnBtn.tap();
sleep(1000);
console.log(JSON.stringify(diffXY));
if (diffXY !== undefined) {
this.goMap(-diffXY.x, -diffXY.y);
}
goBackTime = Date.now();
}
}
}
}, {
key: 'waitForChangeScreen',
value: function waitForChangeScreen() {
var score = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.8;
var maxSleep = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10000;
var oriImg = clone(this._img);
for (var i = 0; i < maxSleep / 500 && this._loop; i++) {
sleep(400);
this.refreshScreen();
var s = getIdentityScore(this._img, oriImg);
if (s < score) {
break;
}
}
releaseImage(oriImg);
}
}, {
key: 'goToMapPage',
value: function goToMapPage() {
this.gi.mapBtn.tap();
this.waitForChangeScreen();
this.gi.mapDetailBtn.tap();
this.waitForChangeScreen(0.8, 2000);
console.log('地圖畫面');
}
}, {
key: 'stop',
value: function stop() {
this._loop = false;
releaseImage(this._img);
for (var k in this.images) {
releaseImage(this.images[k]);
}
}
}, {
key: 'sendDangerMessage',
value: function sendDangerMessage(msg) {
console.log('送危險訊息中...');
var centerImg = this.gi.centerRect.crop(this._img);
var rmi = resizeImage(centerImg, this.gi.centerRect.w / 2, this.gi.centerRect.h / 2);
var base64 = getBase64FromImage(rmi);
releaseImage(rmi);
releaseImage(centerImg);
Utils.sendMessage('天堂M 危險', base64, true);
}
}, {
key: 'sendMoneyInfo',
value: function sendMoneyInfo() {
if (Utils.canSendMessage()) {
console.log('送錢訊息中...');
var moneyImg = this.gi.moneyRect.crop(this._img);
var rmi = resizeImage(moneyImg, this.gi.moneyRect.w / 2, this.gi.moneyRect.h / 2);
var base64 = getBase64FromImage(rmi);
releaseImage(rmi);
releaseImage(moneyImg);
Utils.sendMessage('天堂M', base64);
}
}
}, {
key: 'checkAndBuyItems',
value: function checkAndBuyItems() {
var tryTimes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10;
console.log('嘗試購買物品');sleep(500);
this.refreshScreen();
for (var i = 0; i < tryTimes && this._loop; i++) {
if (i == 4) {
console.log('移動到綠洲,確保有商人等待4秒');
this.goToMapPage();
this.slideMapSelector(41);
this.safeSleep(3000);
console.log('移動到綠洲,往上移動一些');
this.gi.mapController.tapDown();
this.safeSleep(1500);
this.gi.mapControllerT.moveTo();
this.safeSleep(1500);
this.gi.mapControllerT.tapUp();
this.safeSleep(2200);
this.refreshScreen();
console.log('尋找商店');
var _storeType = this.findStore();
console.log('storeType', _storeType);
if (_storeType === 1) {
this.buyItems();
this.refreshScreen();
this.gi.itemBtns[7].tap();
this.safeSleep(2000);
break;
}
this.gi.itemBtns[7].tap();
this.safeSleep(2000);
}
var storeType = this.findStore();
if (storeType === 1) {
this.safeSleep(1000);
this.buyItems();
this.refreshScreen();
break;
} else if (storeType === 2) {
this.buyItems();
this.refreshScreen();
// this.gi.itemBtns[7].tap();
// this.safeSleep(4000);
// this.refreshScreen();
} else if (i < tryTimes - 1) {
console.log('找不到商店,再試一次');
this.gi.itemBtns[7].tap();
this.safeSleep(4000);
this.refreshScreen();
}
}
}
// 0 = no store, 1 = 雜貨電. 2 = others
}, {
key: 'findStore',
value: function findStore() {
var stores1 = findImages(this._img, this.images.store, 0.89, 4, true);
var stores2 = findImages(this._img, this.images.store2, 0.89, 4, true);
var stores = stores1.concat(stores2);
for (var k in stores) {
if (!this._loop) {
return false;
}
var blueCount = 0;
var sx = stores[k].x;
var sy = stores[k].y;
if (sx < 280 && sy < 144) {
continue;
}
if (sx > 790 && sy < 260) {
continue;
}
// for check is right store
for (var i = 0; i < 10; i++) {
if (sx + 10 >= gTargetWidth || sy + 67 + i >= gTargetHeight) {
break;
}
var color = getImageColor(this._img, sx + 10, sy + 67 + i);
if (color.b * 2 > color.g + color.r && color.b > color.r + 30) {
blueCount++;
}
}
if (blueCount < 4) {
continue;
}
var dXY = Utils.targetToDevice(stores[k]);
console.log('可能是商店,打開看看');
tap(dXY.x + 5, dXY.y + 5, 50);
this.waitForChangeScreen(0.7, 7000);if (!this._loop) {
return false;
}
this.safeSleep(2000);
this.refreshScreen();
if (this.gi.storeMode.check(this._img)) {
var testHpImg = this.gi.storeHpRect.crop(this._img);
var results = findImages(testHpImg, this.images.hpWater, 0.88, 1);
releaseImage(testHpImg);
console.log('是雜貨店嗎', results.length > 0 ? results[0].score : 0);
if (results.length > 0 && results[0].score > 0.88) {
console.log('找到雜貨店1');
return 1;
} else {
// find method 2
var redCount = 0;
for (var y = 160; y < 176; y++) {
var _color = getImageColor(this._img, 70, y);
if (1.2 * _color.r > _color.g + _color.b) {
redCount++;
}
}
if (redCount > 10) {
console.log('找到雜貨店2');
return 1;
}
}
} else {
console.log('不是商店,換下一個');
}
if (this.gi.menuOnBtn.check(this._img)) {
this.gi.menuOnBtn.tap();
}
this.safeSleep(2000);
continue;
}
return 0;
}
}, {
key: 'buyItems',
value: function buyItems() {
console.log('購買自訂清單');
this.gi.storeSelfOrder.tap();
sleep(2000);if (!this._loop) {
return false;
}
this.gi.storeBuyOrder.tap();
sleep(2000);if (!this._loop) {
return false;
}
this.gi.storeBuyOrder2.tap();
sleep(2000);if (!this._loop) {
return false;
}
this.gi.storeBuy2.tap();
sleep(2000);if (!this._loop) {
return false;
}
console.log('購買自訂清單完成');
this.gi.menuOnBtn.tap();
return true;
}
// utils
}, {
key: 'cropAndSave',
value: function cropAndSave(filename, rect) {
var img = rect.crop(this._img);
saveImage(img, this.localPath + '/lineageM/' + filename);
releaseImage(img);
}
// globalState 764 240 812 240
}, {
key: 'isSafeRegionState',
value: function isSafeRegionState() {
var bColor = 0;
var rColor = 0;
var gColor = 0; //gray
for (var x = 850; x < 900; x += 2) {
var color = getImageColor(this._img, x, 241);
if (color.b > color.g + color.r) {
// 18
bColor++;
continue;
}
if (color.r > color.g + color.b) {
// 20
rColor++;
continue;
}
if (color.r > 80 && color.g > 80 && color.b > 80) {
// 12
gColor++;
}
}
if (gColor > bColor || rColor > bColor) {
return false;
}
var greenColor = 0;
var orangeColor = 0;
for (var _x9 = 764; _x9 < 812; _x9++) {
var _color2 = getImageColor(this._img, _x9, 240);
if (_color2.b > 86 && _color2.b < 110 && _color2.r < 60 && _color2.g > 140 && _color2.g < 200) {
greenColor++;
}
if (_color2.b < 30 && _color2.r > 200 && _color2.g > 90 && _color2.g < 130) {
orangeColor++;
}
}
if (greenColor > 6 || orangeColor > 6) {
return false;
}
return true;
}
}, {
key: 'checkAndAutoGetReward',
value: function checkAndAutoGetReward() {
if (!this.gi.menuOffEvent.check(this._img)) {
return;
}
this.gi.menuOffEvent.tap();
this.waitForChangeScreen(0.95, 3000);
if (!this._loop) {
return;
}
if (this.gi.menuMail.check(this._img)) {
console.log('自動收取獎勵:信箱');
this.gi.menuMail.tap();
this.waitForChangeScreen(0.9, 5000);
if (!this._loop) {
return;
}
this.gi.getReward.tap();this.safeSleep(1000);
this.gi.getReward.tap();this.safeSleep(1000);
this.gi.getReward.tap();this.safeSleep(1000);
this.gi.getReward.tap();this.safeSleep(1000);
this.gi.menuOnBtn.tap();
this.waitForChangeScreen(0.95, 5000);
}
if (this.gi.menuSign.check(this._img)) {
console.log('自動收取獎勵:登入');
this.gi.menuSign.tap();
this.waitForChangeScreen(0.95, 5000);
if (!this._loop) {
return;
}
this.gi.getReward.tap();this.safeSleep(500);
this.safeSleep(5000);
if (!this._loop) {
return;
}
this.gi.getReward.tap();this.safeSleep(500);
this.gi.menuOnBtn.tap();
this.waitForChangeScreen(0.95, 5000);
}
if (this.gi.menuAlliance.check(this._img)) {
console.log('自動收取獎勵:血盟');
this.gi.menuAlliance.tap();
this.waitForChangeScreen(0.9, 5000);
if (!this._loop) {
return;
}
this.gi.signAlliance.tap();
this.safeSleep(3000);
if (!this._loop) {
return;
}
this.gi.menuOnBtn.tap();
this.waitForChangeScreen(0.95, 5000);
}
}
// HP MP EXP
}, {
key: 'getHpPercent',
value: function getHpPercent() {
return this.getBarPercent(this.gi.hpBarRect, 70, 14, true);
}
}, {
key: 'getMpPercent',
value: function getMpPercent() {
return this.getBarPercent(this.gi.mpBarRect, 70, 70);
}
}, {
key: 'getExpPercent',
value: function getExpPercent() {
return this.getBarPercent(this.gi.expBarRect, 70, 70);
}
}, {
key: 'getBarPercent',
value: function getBarPercent(barRect, b1, b2) {
var poison = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var bar = cropImage(this._img, barRect.tx, barRect.ty, barRect.tw, barRect.th);
var y1 = barRect.th / 3;
var y2 = barRect.th / 3 * 2;
var fc = Utils.mergeColor(getImageColor(bar, 0, y1), getImageColor(bar, 0, y2));
var bright1 = 0;
var bright2 = 0;
for (var x = 0; x < barRect.tw; x += 1) {
var c = Utils.mergeColor(getImageColor(bar, x, y1), getImageColor(bar, x, y2));
var d = Utils.minMaxDiff(c);
if (d > b1) {
bright1++;
}
if (d > b2) {
bright2++;
}
}
releaseImage(bar);
if (fc.g > fc.r) {
if (poison) {
this.gi.isPoison = true;
}
return (bright2 / barRect.tw * 100).toFixed(0);
} else {
if (poison) {
this.gi.isPoison = false;
}
return (bright1 / barRect.tw * 100).toFixed(0);
}
}
// MAP
}, {
key: 'goMap',
value: function goMap(disX, disY) {
var max = 20000;
if (Math.abs(disX) < 30 && Math.abs(disY) < 30) {
return;
}
var timeL = 3000;var timeR = 3000;var timeT = 3000;var timeB = 3000;
if (disX >= 0 && disX > 30) {
timeR += Math.min(1600 * Math.abs(disX) / 10, max);
} else if (disX < 0 && disX < -30) {
timeL += Math.min(1600 * Math.abs(disX) / 10, max);
}
if (disY >= 0 && disY > 30) {
timeB += Math.min(1600 * Math.abs(disY) / 10, max);
} else if (disY < 0 && disY < -30) {
timeT += Math.min(1600 * Math.abs(disY) / 10, max);
}
var times = Math.ceil((timeL + timeR + timeT + timeB) / 24000);
console.log('左', timeL, '右', timeR, '上', timeT, '下', timeB, times);
var tl = Math.ceil(timeL / times);
var tr = Math.ceil(timeR / times);
var tt = Math.ceil(timeT / times);
var tb = Math.ceil(timeB / times);
this.gi.mapController.tapDown();
for (var t = 0; t < times && this._loop; t++) {
if (timeL > 100) {
console.log('往左移動', tl);
this.gi.mapControllerL.moveTo();
this.gi.mapControllerL.moveTo();
this.safeSleep(tl);
timeL -= tl;
}
if (timeT > 100) {
console.log('往上移動', tt);
this.gi.mapControllerT.moveTo();
this.gi.mapControllerT.moveTo();
this.safeSleep(tt);
timeT -= tt;
}
if (timeR > 100) {
console.log('往右移動', tr);
this.gi.mapControllerR.moveTo();
this.gi.mapControllerR.moveTo();
this.safeSleep(tr);
timeR -= tr;
}
if (timeB > 100) {
console.log('往下移動', tb);
this.gi.mapControllerB.moveTo();
this.gi.mapControllerB.moveTo();
this.safeSleep(tb);
timeB -= tb;
}
}
this.gi.mapController.tapUp();
}
}, {
key: 'recordCurrentLocation',
value: function recordCurrentLocation() {
var p = new Point(768, 360);
var rect1 = new Rect(p.x - 120, p.y - 90, p.x - 30, p.y - 30); // left top
var rect2 = new Rect(p.x + 30, p.y - 90, p.x + 120, p.y - 30); // right top
var rect3 = new Rect(p.x - 120, p.y + 30, p.x - 30, p.y + 90); // left bottom
var rect4 = new Rect(p.x + 30, p.y + 30, p.x + 120, p.y + 90); // right bottom
var img1 = cropImage(this._img, rect1.tx, rect1.ty, rect1.tw, rect1.th);
var img2 = cropImage(this._img, rect2.tx, rect2.ty, rect2.tw, rect2.th);
var img3 = cropImage(this._img, rect3.tx, rect3.ty, rect3.tw, rect3.th);
var img4 = cropImage(this._img, rect4.tx, rect4.ty, rect4.tw, rect4.th);
saveImage(img1, this.localPath + '/mapRecord1.png');
saveImage(img2, this.localPath + '/mapRecord2.png');
saveImage(img3, this.localPath + '/mapRecord3.png');
saveImage(img4, this.localPath + '/mapRecord4.png');
releaseImage(img1);releaseImage(img2);releaseImage(img3);releaseImage(img4);
}
}, {
key: 'getDiffRecordLocation',
value: function getDiffRecordLocation() {
var result = undefined;
for (var i = 0; i < 3; i++) {
result = this.findDiffRecordLocation();
if (result !== undefined) {
break;
}
sleep(1000);
this.refreshScreen();
}
if (result === undefined) {
console.log('無法找到紀錄點');
return { x: 0, y: 0 };
}
return result;
}
}, {
key: 'findDiffRecordLocation',
value: function findDiffRecordLocation() {
var p = new Point(768, 360);
var images = [openImage(this.localPath + '/mapRecord1.png'), openImage(this.localPath + '/mapRecord2.png'), openImage(this.localPath + '/mapRecord3.png'), openImage(this.localPath + '/mapRecord4.png')];
var findXYs = [];
for (var i = 0; i < images.length; i++) {
if (images[i] === 0) {
console.log('無法記錄地圖位置');
return;
}
var xy = findImage(this._img, images[i]);
switch (i) {
case 0:
xy.x = p.x - xy.x / gRatioTarget - 120;
xy.y = p.y - xy.y / gRatioTarget - 90;
break;
case 1:
xy.x = p.x - xy.x / gRatioTarget + 30;
xy.y = p.y - xy.y / gRatioTarget - 90;
break;
case 2:
xy.x = p.x - xy.x / gRatioTarget - 120;
xy.y = p.y - xy.y / gRatioTarget + 30;
break;
case 3:
xy.x = p.x - xy.x / gRatioTarget + 30;
xy.y = p.y - xy.y / gRatioTarget + 30;
break;
}
findXYs.push(xy);
releaseImage(images[i]);
}
var finalXY = undefined;
for (var _i = 0; _i < findXYs.length; _i++) {
var count = 0;
for (var j = 0; j < findXYs.length; j++) {
if (Math.abs(findXYs[_i].x - findXYs[j].x) < 30 && Math.abs(findXYs[_i].y - findXYs[j].y) < 30) {
count++;
}
}
if (count > 1) {
finalXY = findXYs[_i];
}
}
if (finalXY !== undefined) {
// console.log(JSON.stringify(findXYs));
console.log('\u4F4D\u7F6E\u76F8\u5DEE x\uFF1A' + finalXY.x + '\uFF0Cy\uFF1A' + finalXY.y);
}
return finalXY;
}
}, {
key: 'slideMapSelector',
value: function slideMapSelector(nth) {
var itemHeight = 112 * gRatioDevice; // dev 1920 * 1080 => device item height
var sDCX = gGameOffsetX + (this.gi.mapSelector.x1 + this.gi.mapSelector.x2) / 2 * gRatioDevice;
var sDCY = gGameOffsetY + this.gi.mapSelector.y1 * gRatioDevice;
var itemsY = [sDCY + itemHeight * 0.5, sDCY + itemHeight * 1.5, sDCY + itemHeight * 2.5, sDCY + itemHeight * 3.5, sDCY + itemHeight * 4.5];
// move to top
var move2Top = function move2Top() {
for (var i = 0; i < 3; i++) {
tapDown(sDCX, itemsY[0], 10);
tapUp(sDCX, itemsY[4], 10);
sleep(1000);
}
};
var move4down = function move4down() {
tapDown(sDCX, itemsY[4], 20);
moveTo(sDCX, itemsY[4], 20);
moveTo(sDCX, itemsY[3], 20);
moveTo(sDCX, itemsY[2], 20);
moveTo(sDCX, itemsY[1], 20);
sleep(150);
moveTo(sDCX, itemsY[0], 20);
sleep(1500);
tapUp(sDCX, itemsY[0], 20);
};
move2Top();
sleep(500);
for (var i = 0; i < Math.floor((nth - 1) / 4) && this._loop; i++) {
move4down();
}
tap(sDCX, itemsY[(nth - 1) % 4], 20);
sleep(500);
this.refreshScreen();
this.gi.mapMoveBtn.tap();
// this.waitForChangeScreen(0.92, 5000);
// this.safeSleep(3000); if (!this._loop) { return; }
// this.refreshScreen();
// const floorXY1 = findImage(this._img, this.images.floor1);
// if (floorXY1.score > 0.8) {
// const dXY = Utils.targetToDevice(floorXY1);
// tap(dXY.x + 5, dXY.y + 5, 50);
// sleep(1000);
// this.gi.mapFloorBtn.tap();
// sleep(1000);
// return;
// }
// const floorXY2 = findImage(this._img, this.images.floor2);
// if (floorXY2.score > 0.8) {
// const dXY = Utils.targetToDevice(floorXY2);
// tap(dXY.x + 5, dXY.y + 5, 50);
// sleep(1000);
// this.gi.mapFloorBtn.tap();
// sleep(1000);
// return;
// }
}
}, {
key: 'getImageNumber',
value: function getImageNumber(img, numbers) {
var maxLength = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 8;
if (numbers.length != 10) {
console.log('圖片數量應為 10');
return 0;
}
var results = [];
for (var i = 0; i < 10; i++) {
var nImg = numbers[i];
if (nImg == 0) {
console.log('\u5716\u7247 ' + i + ' \u4E0D\u5B58\u5728');
return 0;
}
var rs = findImages(img, nImg, 0.95, maxLength, true);
for (var k in rs) {
rs[k].number = i;
results.push(rs[k]);
}
}
results.sort(function (a, b) {
return b.score - a.score;
});
results = results.slice(0, Math.min(maxLength, results.length));
results.sort(function (a, b) {
return a.x - b.x;
});
var numberSize = getImageSize(numbers[0]);
var nw = numberSize.width;
var imgSize = getImageSize(img);
var iw = imgSize.width;
var px = 0;
var numberStr = '';
for (var _i2 in results) {
var r = results[_i2];
if (r.x > p) {
numberStr += r.number.toString();
p = r.x - 2;
}
}
console.log('\u5716\u7247\u5927\u5C0F\u70BA ' + numberStr);
return numberStr;
}
}]);
return LineageM;
}();
var DefaultConfig = {
conditions: [
// {type: 'hp', op: -1, value: 80, btn: 0, interval: 1000}, // if hp < 60% use 3th button, like 瞬移
// {type: 'mp', op: 1, value: 50, btn: 1, interval: 1000}, // if hp < 30% use 8th button, like 回卷
// {type: 'mp', op: -1, value: 80, btn: 2, interval: 2000}, // if hp < 75% use 4th button, like 高治
// {type: 'mp', op: -1, value: 70, btn: 4, interval: 2000}, // if mp < 70% use 5th button, like 魂體
// {type: 'mp', op: 1, value: 50, btn: 1, interval: 8000}, // if mp > 80% use th button, like 三重矢, 光箭, 火球等
],
inHomeUseBtn: false, // if in safe region use 3th button, like 瞬移.
beAttackedRandTeleport: true,
dangerousGoHome: true, // if hp < 25%, go home, use button 8th
autoAttack: false,
autoReceiveReward: false,
autoUseAntidote: false, // take an antidote for the poison, use six button
goBackInterval: 0, // whether to go back to origin location, check location every n min
autoBuyFirstSet: false, // 1 * 100, -1 => max
mapSelect: 0, // move to nth map in safe region
grabMonster: false,
autoTeleport: true
};
var lm = undefined;
function testSpecialScreen() {
// for special screen
if (gDeviceWidth / gDeviceHeight > 1.78) {
var _blackX = 0;
var _img = getScreenshot();
for (var x = 0; x < gDeviceWidth; x++) {
var color = getImageColor(_img, x, gDeviceHeight - 1);
if (color.r === 0 && color.g === 0 && color.b === 0) {
_blackX++;
} else {
break;
}
}
releaseImage(_img);
_blackX++;
if (Math.abs(_blackX - gGameOffsetX) >= 2) {
gGameOffsetX = _blackX;
console.log("修正特殊螢幕位置", _blackX);
sleep(1000);
}
}
}
function start(config) {
console.log('📢 啟動腳本 📢');
testSpecialScreen();
console.log('螢幕位移', gGameOffsetX, gGameWidth);
sleep(2000);
if (typeof config === 'string') {
config = JSON.parse(config);
}
if (lm !== undefined) {
console.log('📢 腳本已啟動 📢');
return;
}
lm = new LineageM(config);
lm.start();
lm.stop();
lm = undefined;
console.log('📢 腳本已停止 📢');
}
function stop() {
if (lm == undefined) {
return;
}
lm._loop = false;
lm = undefined;
console.log('📢 停止腳本中 📢');
}
// start(DefaultConfig);
// lm = new LineageM(DefaultConfig);
// lm._loop = true;
// lm.checkAndBuyItems();
// console.log(lm.isSafeRegionState());
// lm.goToMapPage();
// lm.slideMapSelector(5);
// lm.buyItems();
// lm.checkAndAutoGetReward();
// for (var i= 0; i < 1; i++) {
// lm.refreshScreen();
// const a = lm.gi.attackBtn.check(lm._img);
// const b = lm.gi.killNumber.check(lm._img);
// // lm.gi.killNumber.print(lm._img);
// // console.log(b)
// const c = lm.gi.autoPlayBtn.check(lm._img);
// lm.gi.autoPlayBtn.print(lm._img);
// console.log('attack Off', a, 'has kn', b, 'autoOff', c);
// }
// lm.findStore();
// for (let i = 0; i < 5; i++) {
// const hp = lm.getHpPercent();
// // const mp = lm.getMpPercent();
// // const exp = lm.getExpPercent();
// lm.refreshScreen();
// console.log(hp);
// }
// lm.checkAndBuyItems(1);
// lm.goToMapPage();
// const hp = lm.getHpPercent();
// const mp = lm.getMpPercent();
// const exp = lm.getExpPercent();
// console.log(hp, mp, exp);
// lm.goToMapPage();
// lm._loop = true;
// lm.recordCurrentLocation();
// var xy = lm.getDiffRecordLocation();
// lm.gi.menuOnBtn.tap();
// sleep(1000);
// lm.goMap(-xy.x, -xy.y);
// lm.cropAndSave('safeRegionType.png', lm.gi.regionTypeRect);
// lm.updateGlobalState();
// lm.stop();
| r2-studio/robotmon-scripts | scripts/com.r2studio.LineageM/index.js | JavaScript | apache-2.0 | 51,799 |
/*
* Copyright 2016 Alireza Eskandarpour Shoferi
*
* 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.github.meness.easyintro;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.AnimRes;
import android.support.annotation.CallSuper;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RawRes;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import io.github.meness.easyintro.enums.IndicatorContainer;
import io.github.meness.easyintro.enums.PageIndicator;
import io.github.meness.easyintro.enums.SlideTransformer;
import io.github.meness.easyintro.enums.ToggleIndicator;
import io.github.meness.easyintro.interfaces.IConfigMultiple;
import io.github.meness.easyintro.interfaces.IConfigOnActivity;
import io.github.meness.easyintro.listeners.EasyIntroInteractionsListener;
public abstract class EasyIntro extends AppCompatActivity implements EasyIntroInteractionsListener, IConfigMultiple, IConfigOnActivity {
public static final String TAG = EasyIntro.class.getSimpleName();
private EasyIntroCarouselFragment carouselFragment;
@Override
public void onPreviousSlide() {
// empty
}
@Override
public void onNextSlide() {
// empty
}
@Override
public void onDonePressed() {
// empty
}
@Override
public void onSkipPressed() {
// empty
}
protected final EasyIntroCarouselFragment getCarouselFragment() {
return carouselFragment;
}
/**
* Only Activity has this special callback method
* Fragment doesn't have any onBackPressed callback
* <p/>
* Logic:
* Each time when the back button is pressed, this Activity will propagate the call to the
* container Fragment and that Fragment will propagate the call to its each tab Fragment
* those Fragments will propagate this method call to their child Fragments and
* eventually all the propagated calls will get back to this initial method
* <p/>
* If the container Fragment or any of its Tab Fragments and/or Tab child Fragments couldn't
* handle the onBackPressed propagated call then this Activity will handle the callback itself
*/
@Override
@CallSuper
public void onBackPressed() {
if (!carouselFragment.onBackPressed()) {
// container Fragment or its associates couldn't handle the back pressed task
// delegating the task to super class
super.onBackPressed();
} // else: carousel handled the back pressed task
// do not call super
}
@Override
@CallSuper
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easyintro_main);
initCarousel(savedInstanceState);
}
private void initCarousel(Bundle savedInstanceState) {
if (savedInstanceState == null) {
// withholding the previously created fragment from being created again
// On orientation change, it will prevent fragment recreation
// its necessary to reserve the fragment stack inside each tab
// Creating the ViewPager container fragment once
carouselFragment = (EasyIntroCarouselFragment) EasyIntroCarouselFragment.instantiate(getApplicationContext(), EasyIntroCarouselFragment.class.getName());
carouselFragment.setInteractionsListener(this);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, carouselFragment)
.commit();
} else {
// restoring the previously created fragment
// and getting the reference
carouselFragment = (EasyIntroCarouselFragment) getSupportFragmentManager().getFragments().get(0);
}
}
@Override
@CallSuper
public void onCarouselViewCreated(View view, @Nullable Bundle savedInstanceState) {
initIntro();
}
protected abstract void initIntro();
@Override
public void withTranslucentStatusBar(boolean b) {
carouselFragment.withTranslucentStatusBar(b);
}
@Override
public void withStatusBarColor(@ColorInt int statusBarColor) {
carouselFragment.withStatusBarColor(statusBarColor);
}
@Override
public void withOffScreenPageLimit(int limit) {
carouselFragment.withOffScreenPageLimit(limit);
}
@Override
public void withTransparentStatusBar(boolean b) {
carouselFragment.withTransparentStatusBar(b);
}
@Override
public void withTransparentNavigationBar(boolean b) {
carouselFragment.withTransparentNavigationBar(b);
}
@Override
public void withFullscreen(boolean b) {
carouselFragment.withFullscreen(b);
}
@Override
public void withTranslucentNavigationBar(boolean b) {
carouselFragment.withTranslucentNavigationBar(b);
}
@Override
public void withSlideTransformer(SlideTransformer transformer) {
carouselFragment.withSlideTransformer(transformer);
}
@Override
public void withToggleIndicator(ToggleIndicator indicators) {
carouselFragment.withToggleIndicator(indicators);
}
@Override
public void withVibrateOnSlide(int intensity) {
carouselFragment.withVibrateOnSlide(intensity);
}
@Override
public void withVibrateOnSlide() {
carouselFragment.withVibrateOnSlide();
}
@Override
public void withRtlSupport() {
carouselFragment.withRtlSupport();
}
@Override
public void withPageMargin(int marginPixels) {
carouselFragment.withPageMargin(marginPixels);
}
@Override
public void setPageMarginDrawable(Drawable d) {
carouselFragment.setPageMarginDrawable(d);
}
@Override
public void setPageMarginDrawable(@DrawableRes int resId) {
carouselFragment.setPageMarginDrawable(resId);
}
@Override
public void withToggleIndicatorSoundEffects(boolean b) {
carouselFragment.withToggleIndicatorSoundEffects(b);
}
@Override
public void withSlideSound(@RawRes int sound) {
carouselFragment.withSlideSound(sound);
}
@Override
public void withOverScrollMode(int mode) {
carouselFragment.withOverScrollMode(mode);
}
@Override
public void withPageIndicator(PageIndicator pageIndicator) {
carouselFragment.withPageIndicator(pageIndicator);
}
@Override
public void withIndicatorContainer(IndicatorContainer container) {
carouselFragment.withIndicatorContainer(container);
}
@Override
public void withIndicatorContainer(@LayoutRes int resId) {
carouselFragment.withIndicatorContainer(resId);
}
@Override
public void withRightIndicatorDisabled(boolean b) {
carouselFragment.withRightIndicatorDisabled(b);
}
@Override
public void withIndicatorContainerGravity(int gravity) {
carouselFragment.withIndicatorContainerGravity(gravity);
}
@Override
public void withSlide(Fragment slide) {
carouselFragment.withSlide(slide);
}
@Override
public void withLeftIndicatorDisabled(boolean b) {
carouselFragment.withLeftIndicatorDisabled(b);
}
@Override
public void withPageIndicator(@LayoutRes int resId) {
carouselFragment.withPageIndicator(resId);
}
@Override
public void withOverlaySlideAnimation(@AnimRes int enter, @AnimRes int exit, @AnimRes int popEnter, @AnimRes int popExit) {
carouselFragment.withOverlaySlideAnimation(enter, exit, popEnter, popExit);
}
@Override
public void withSlideBackPressSupport(boolean b) {
carouselFragment.withSlideBackPressSupport(b);
}
@Override
public void withPageIndicatorVisibility(boolean b) {
carouselFragment.withPageIndicatorVisibility(b);
}
@Override
public void withRightIndicatorDisabled(boolean b, @NonNull Class slide) {
carouselFragment.withRightIndicatorDisabled(b, slide);
}
@Override
public void withLeftIndicatorDisabled(boolean b, @NonNull Class slide) {
carouselFragment.withLeftIndicatorDisabled(b, slide);
}
@Override
public void withBothIndicatorsDisabled(boolean b, Class slide) {
carouselFragment.withBothIndicatorsDisabled(b, slide);
}
@Override
public void withNextSlide(boolean smoothScroll) {
carouselFragment.withNextSlide(smoothScroll);
}
@Override
public void withPreviousSlide(boolean smoothScroll) {
carouselFragment.withPreviousSlide(smoothScroll);
}
@Override
public void withSlideTo(int page, boolean smoothScroll) {
carouselFragment.withSlideTo(page, smoothScroll);
}
@Override
public Fragment getCurrentSlide() {
return carouselFragment.getCurrentSlide();
}
@Override
public void withSlideTo(Class slideClass, boolean smoothScroll) {
carouselFragment.withSlideTo(slideClass, smoothScroll);
}
}
| meNESS/EasyIntro | library/src/main/java/io/github/meness/easyintro/EasyIntro.java | Java | apache-2.0 | 9,883 |
/*
* 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.ignite.internal.portable.streams;
import org.apache.ignite.internal.util.GridUnsafe;
import org.apache.ignite.internal.util.typedef.internal.U;
import sun.misc.Unsafe;
import static org.apache.ignite.IgniteSystemProperties.IGNITE_MARSHAL_BUFFERS_RECHECK;
/**
* Memory allocator chunk.
*/
public class PortableMemoryAllocatorChunk {
/** Unsafe instance. */
protected static final Unsafe UNSAFE = GridUnsafe.unsafe();
/** Array offset: byte. */
protected static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class);
/** Buffer size re-check frequency. */
private static final Long CHECK_FREQ = Long.getLong(IGNITE_MARSHAL_BUFFERS_RECHECK, 10000);
/** Data array */
private byte[] data;
/** Max message size detected between checks. */
private int maxMsgSize;
/** Last time array size is checked. */
private long lastCheck = U.currentTimeMillis();
/** Whether the holder is acquired or not. */
private boolean acquired;
/**
* Allocate.
*
* @param size Desired size.
* @return Data.
*/
public byte[] allocate(int size) {
if (acquired)
return new byte[size];
acquired = true;
if (data == null || size > data.length)
data = new byte[size];
return data;
}
/**
* Reallocate.
*
* @param data Old data.
* @param size Size.
* @return New data.
*/
public byte[] reallocate(byte[] data, int size) {
byte[] newData = new byte[size];
if (this.data == data)
this.data = newData;
UNSAFE.copyMemory(data, BYTE_ARR_OFF, newData, BYTE_ARR_OFF, data.length);
return newData;
}
/**
* Shrinks array size if needed.
*/
public void release(byte[] data, int maxMsgSize) {
if (this.data != data)
return;
if (maxMsgSize > this.maxMsgSize)
this.maxMsgSize = maxMsgSize;
this.acquired = false;
long now = U.currentTimeMillis();
if (now - this.lastCheck >= CHECK_FREQ) {
int halfSize = data.length >> 1;
if (this.maxMsgSize < halfSize)
this.data = new byte[halfSize];
this.lastCheck = now;
}
}
/**
* @return {@code True} if acquired.
*/
public boolean isAcquired() {
return acquired;
}
}
| apacheignite/ignite | modules/core/src/main/java/org/apache/ignite/internal/portable/streams/PortableMemoryAllocatorChunk.java | Java | apache-2.0 | 3,228 |