hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
e5e4970b675b9ee3144367caaeb93bf3716f7eed | 712 | // Decompiled by Jad v1.5.8e2. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://kpdus.tripod.com/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi space
// Source File Name: CheckParser.java
package com.pa.sdk.parser;
import com.alibaba.fastjson.JSONObject;
import com.pa.sdk.core.BaseAPIParser;
import com.pa.sdk.entity.ExistEntity;
public class CheckParser extends BaseAPIParser
{
public ExistEntity exist;
public CheckParser(JSONObject data)
{
super(data);
if (success)
exist = parse(this.data);
}
public static ExistEntity parse(JSONObject data)
{
ExistEntity exist = new ExistEntity();
exist.setExist(!data.getBooleanValue("notExist"));
return exist;
}
}
| 22.967742 | 63 | 0.75 |
6d2148bdb7a4c25af3c76e59dc5acf4d5bc81bc7 | 862 | package net.scadsdnd.adviser.myadviser;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// Default onCrete method.
// Move here anything should happen just after app started.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// This function is called whe user clicks 'let's start'
public void getSections(View vw){
// This will create new intent from our activity class
Intent intSec = new Intent(this, SectionsActivity.class);
// And this will actually fire up our new activity
startActivity(intSec);
}
}
| 28.733333 | 67 | 0.716937 |
45f605482fd3a7e667557bd056227f460164d61c | 189 | package org.andengine.ui;
import org.andengine.b.c.b;
import org.andengine.c.b.e;
public interface a {
b a();
void a(e eVar, d dVar);
void a(b bVar);
void a(c cVar);
}
| 12.6 | 27 | 0.613757 |
c20bb652fa1114b1f8d5d2dd0ee4c897fe9fe955 | 4,664 | /* -------------------------------------------------------------------------- *
* OpenSim: PluginsDB.java *
* -------------------------------------------------------------------------- *
* OpenSim is a toolkit for musculoskeletal modeling and simulation, *
* developed as an open source project by a worldwide community. Development *
* and support is coordinated from Stanford University, with funding from the *
* U.S. NIH and DARPA. See http://opensim.stanford.edu and the README file *
* for more information including specific grant numbers. *
* *
* Copyright (c) 2005-2017 Stanford University and the Authors *
* Author(s): Ayman Habib *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* PluginsDB.java
*
* Created on Jan 19, 2009, 9:55 AM
*
*/
package org.opensim.view.pub;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import org.opensim.logger.OpenSimLogger;
import org.opensim.modeling.Model;
/**
*
* @author Ayman
*
* This class contains a representation of PluginsDB for serialization on entry/exit.
* If we want to serialize to an XML file this class should implement Externalizable instead and follow Beans convention.
*/
public class PluginsDB implements Externalizable {
private ArrayList<String> fileNames=new ArrayList<String>(5);
private static final long serialVersionUID = 1L;
private static PluginsDB instance;
/** Creates a new instance of PluginsDB
* This constructor will be invoked from the deserialization code
*/
public PluginsDB() {
System.out.println("PluginsDB constructor called");
instance = this;
}
public static synchronized PluginsDB getInstance() {
if (instance == null) {
new PluginsDB();
}
return instance;
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeLong(serialVersionUID);
out.writeInt(getFileNames().size());
for (int i=0; i<getFileNames().size(); i++) {
out.writeUTF(getFileNames().get(i));
}
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
long ver = in.readLong();
int sz = in.readInt();
for (int i=0; i<sz; i++) {
String sharedLibraryName = in.readUTF();
try{
System.load(sharedLibraryName);
getFileNames().add(sharedLibraryName);
}
catch(UnsatisfiedLinkError e){
System.out.println("Error trying to load library "+sharedLibraryName+" ignored.");
}
};
}
public ArrayList<String> getFileNames() {
return fileNames;
}
public void setFileNames(ArrayList<String> fileNames) {
this.fileNames = fileNames;
}
public void addLibrary(String fileName) {
fileNames.add(fileName);
}
public void loadPlugins() {
for (int i=0; i<fileNames.size(); i++) {
String sharedLibraryName = fileNames.get(i);
try{
System.load(sharedLibraryName);
OpenSimLogger.logMessage("Successfully loaded library "+sharedLibraryName+".\n", OpenSimLogger.INFO);
}
catch(UnsatisfiedLinkError e){
OpenSimLogger.logMessage("Error trying to load library "+sharedLibraryName+". Ignored, removed from persistent list.", OpenSimLogger.ERROR);
fileNames.remove(i);
i--;
}
};
}
}
| 39.863248 | 156 | 0.555746 |
7988651a6ac5d20842e8f9e68b7c52df6c000db9 | 280 | package net.adrianlehmann.swt_revision.patterns.variation_patterns.factory_method;
/**
* Created by adrianlehmann on 09.07.17.
*/
public class NormalStudent extends Student{
@Override
public Smartphone makeSmartPhone() {
return new GenericSmartphone();
}
}
| 23.333333 | 82 | 0.739286 |
dc8b1a6b79a78df38bb0c426ed448f13006b29b1 | 377 | package com.huellapositiva.domain.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.FORBIDDEN)
public class TimeForRecoveringPasswordExpiredException extends RuntimeException {
public TimeForRecoveringPasswordExpiredException(String message) {
super(message);
}
}
| 31.416667 | 81 | 0.827586 |
5ee1124bba92515d2f02de967aa41d09925fbf73 | 2,292 | /*
* Copyright 2016 PantherCode
*
* 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.panthercode.arctic.core.processing;
/**
* Enumeration of possible processing states. It's used indicate the inner state of an object.
*/
public enum ProcessState {
/**
* State after the object is created.
*/
NEW("New"),
/**
* The process was aborted. A smoother form of stopped.
*/
CANCELLED("Cancelled"),
/**
* The run finished unsuccessfully.
*/
FAILED("Failed"),
/**
* The object is preparing.
*/
INITIALIZING("Initializing"),
/**
* The object is ready to execute.
*/
READY("Ready"),
/**
* The object is executing its functionality.
*/
RUNNING("Running"),
/**
* The object is sorted.
*/
SCHEDULING("Scheduling"),
/**
* The execution was aborted.
*/
STOPPED("Stopped"),
/**
* The run finished successful.
*/
SUCCEEDED("Succeeded"),
/**
* The object's execution is interrupted for short time by some reason.
*/
WAITING("Waiting");
/**
* string value of state
*/
private final String value;
/**
* Constructor
*
* @param value value of state
*/
ProcessState(final String value) {
this.value = value;
}
/**
* Returns a string representing the process state.
*
* @return Returns a string representing the process state.
*/
public String value() {
return this.value;
}
/**
* Returns a string representing the process state.
*
* @return Returns a string representing the process state.
*/
@Override
public String toString() {
return this.value;
}
}
| 21.828571 | 94 | 0.607766 |
90029faec118a1481fbe64919b811e5a87883685 | 5,440 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hive
operator|.
name|jdbc
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|locks
operator|.
name|ReentrantLock
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|security
operator|.
name|auth
operator|.
name|Subject
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hive
operator|.
name|service
operator|.
name|auth
operator|.
name|HttpAuthUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|http
operator|.
name|HttpException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|http
operator|.
name|HttpRequest
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|http
operator|.
name|client
operator|.
name|CookieStore
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|http
operator|.
name|protocol
operator|.
name|HttpContext
import|;
end_import
begin_comment
comment|/** * Authentication interceptor which adds Base64 encoded payload, * containing the username and kerberos service ticket, * to the outgoing http request header. */
end_comment
begin_class
specifier|public
class|class
name|HttpKerberosRequestInterceptor
extends|extends
name|HttpRequestInterceptorBase
block|{
name|String
name|principal
decl_stmt|;
name|String
name|host
decl_stmt|;
name|String
name|serverHttpUrl
decl_stmt|;
name|Subject
name|loggedInSubject
decl_stmt|;
comment|// A fair reentrant lock
specifier|private
specifier|static
name|ReentrantLock
name|kerberosLock
init|=
operator|new
name|ReentrantLock
argument_list|(
literal|true
argument_list|)
decl_stmt|;
specifier|public
name|HttpKerberosRequestInterceptor
parameter_list|(
name|String
name|principal
parameter_list|,
name|String
name|host
parameter_list|,
name|String
name|serverHttpUrl
parameter_list|,
name|Subject
name|loggedInSubject
parameter_list|,
name|CookieStore
name|cs
parameter_list|,
name|String
name|cn
parameter_list|,
name|boolean
name|isSSL
parameter_list|,
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|additionalHeaders
parameter_list|,
name|Map
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|customCookies
parameter_list|)
block|{
name|super
argument_list|(
name|cs
argument_list|,
name|cn
argument_list|,
name|isSSL
argument_list|,
name|additionalHeaders
argument_list|,
name|customCookies
argument_list|)
expr_stmt|;
name|this
operator|.
name|principal
operator|=
name|principal
expr_stmt|;
name|this
operator|.
name|host
operator|=
name|host
expr_stmt|;
name|this
operator|.
name|serverHttpUrl
operator|=
name|serverHttpUrl
expr_stmt|;
name|this
operator|.
name|loggedInSubject
operator|=
name|loggedInSubject
expr_stmt|;
block|}
annotation|@
name|Override
specifier|protected
name|void
name|addHttpAuthHeader
parameter_list|(
name|HttpRequest
name|httpRequest
parameter_list|,
name|HttpContext
name|httpContext
parameter_list|)
throws|throws
name|Exception
block|{
try|try
block|{
comment|// Generate the service ticket for sending to the server.
comment|// Locking ensures the tokens are unique in case of concurrent requests
name|kerberosLock
operator|.
name|lock
argument_list|()
expr_stmt|;
name|String
name|kerberosAuthHeader
init|=
name|HttpAuthUtils
operator|.
name|getKerberosServiceTicket
argument_list|(
name|principal
argument_list|,
name|host
argument_list|,
name|serverHttpUrl
argument_list|,
name|loggedInSubject
argument_list|)
decl_stmt|;
comment|// Set the session key token (Base64 encoded) in the headers
name|httpRequest
operator|.
name|addHeader
argument_list|(
name|HttpAuthUtils
operator|.
name|AUTHORIZATION
operator|+
literal|": "
operator|+
name|HttpAuthUtils
operator|.
name|NEGOTIATE
operator|+
literal|" "
argument_list|,
name|kerberosAuthHeader
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|HttpException
argument_list|(
name|e
operator|.
name|getMessage
argument_list|()
argument_list|,
name|e
argument_list|)
throw|;
block|}
finally|finally
block|{
name|kerberosLock
operator|.
name|unlock
argument_list|()
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
| 16.484848 | 813 | 0.806434 |
37aad899d96606b1ea5ea1289331b16aa0fed1d4 | 443 | package com.github.hexsmith.spring.cloud.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class SpringCloudBootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudBootApplication.class, args);
}
}
| 29.533333 | 72 | 0.846501 |
85473b634d1982ca0509e786e1f69a67671fe35c | 2,826 | package com.springboot.yangmeng.admin.core.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonView;
import com.springboot.yangmeng.admin.core.util.ValidateConfig;
import org.beetl.sql.core.annotatoin.AutoID;
import org.beetl.sql.core.annotatoin.SeqID;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
/**
* 描述: 字典
* @author : xiandafu
*/
public class CoreDict extends BaseEntity {
@NotNull(message = "ID不能为空", groups = ValidateConfig.UPDATE.class)
@SeqID(name = ORACLE_CORE_SEQ_NAME)
@AutoID
private Long id;
private String value; // 数据值
//删除标识
@JsonIgnore
protected Integer delFlag = 0;
//创建时间
protected Date createTime;
@NotBlank(message = "字典类型不能为空", groups = ValidateConfig.ADD.class)
@JsonView(TypeListView.class)
private String type; //类型
@JsonView(TypeListView.class)
@NotBlank(message = "字典类型描述不能为空")
private String typeName; //类型描述
@NotBlank(message = "字典值不能为空", groups = ValidateConfig.ADD.class)
@NotBlank(message = "字典值名称不能为空")
private String name; // 标签名
private Integer sort; // 排序
private Long parent; //父Id
private String remark; //备注
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Long getParent() {
return parent;
}
public void setParent(Long parent) {
this.parent = parent;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Integer getDelFlag() {
return delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public interface TypeListView{
}
@Override
public String toString() {
return "CoreDict [value=" + value + ", type=" + type + ", name=" + name + "]";
}
}
| 19.625 | 86 | 0.630573 |
6f5e70ac850db5a397cfbe5a17bc21764a9ac249 | 3,463 | package de.uni_stuttgart.informatik.sopra.sopraapp.requests;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import de.uni_stuttgart.informatik.sopra.sopraapp.R;
public class OidAdapter extends ArrayAdapter<OidElement> {
private static final String TAG = "OidAdapter";
private RequestDbHelper requestDbHelper;
private int requestId;
private String requestName;
private Context context;
OidAdapter(Context context, RequestDbHelper dbHelper, int requestId, String requestName) {
super(context, 0);
this.context = context;
requestDbHelper = dbHelper;
this.requestName = requestName;
this.requestId = requestId;
addAll(requestDbHelper.getOIDsFrom(requestName));
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View oidView = convertView;
if (oidView == null) {
oidView = LayoutInflater.from(context).inflate(R.layout.recycler_edit_layout, parent, false);
}
final OidElement element = getItem(position);
EditText oidField = oidView.findViewById(R.id.oid_field);
Log.d(TAG, "getView: requestName: " +requestName);
String oid = requestDbHelper.getOIDsFrom(requestName).get(position).getOidString();
oidField.setText(oid);
EditText descText = oidView.findViewById(R.id.description_field);
String des = requestDbHelper.getOIDsFrom(requestName).get(position).getDescription();
descText.setText(des);
ImageButton deleteImBtn = oidView.findViewById(R.id.delete_btn);
deleteImBtn.setOnClickListener(v -> {
SQLiteDatabase readableDatabase = requestDbHelper.getReadableDatabase();
Cursor cursor = readableDatabase.rawQuery("select * from " + RequestsContract.OID_TABLE_NAME + " where " +
RequestsContract.COLUMN_OID_REQ + " = " + requestId + " order by " + RequestsContract.COLUMN_OID_ID, null);
cursor.moveToPosition(position);
int idToDel = cursor.getInt(cursor.getColumnIndex(RequestsContract.COLUMN_OID_ID));
readableDatabase.delete(RequestsContract.OID_TABLE_NAME, RequestsContract.COLUMN_OID_ID + " = " + idToDel, null);
super.remove(element);
cursor.close();
});
descText.setEnabled(false);
oidField.setEnabled(false);
return oidView;
}
@Override
public void notifyDataSetChanged() {
setNotifyOnChange(false);
SQLiteDatabase titleGetter = requestDbHelper.getReadableDatabase();
Cursor cursor = titleGetter.rawQuery("select * from " + RequestsContract.REQ_TABLE_NAME + " where " + RequestsContract.COLUMN_REQ_ID + " = " + requestId, null);
cursor.moveToFirst();
requestName = cursor.getString(cursor.getColumnIndex(RequestsContract.COLUMN_REQ_NAME));
clear();
Log.d(TAG, "notifyDataSetChanged: oids from " + requestDbHelper.getOIDsFrom(requestName).size());
addAll(requestDbHelper.getOIDsFrom(requestName));
Log.d(TAG, "notifyDataSetChanged: elementsList " + getCount());
super.notifyDataSetChanged();
}
}
| 41.22619 | 168 | 0.701992 |
89d21adc20272d30efe97c42f3809e04605a383d | 13,533 | package MinimumSpanningTree;
import java.io.*;
import java.util.*;
public class Main implements Runnable
{
private String fileName;
private String algorithm;
private File file;
private LinkedList verticesInfo;
private LinkedList edgesInfo;
private LinkedList graphsInfo;
private LinkedList graphs;
public Main(String fileName,String algorithm)
{
this.fileName = fileName;
this.algorithm = algorithm;
verticesInfo = new LinkedList();
edgesInfo = new LinkedList();
graphsInfo = new LinkedList();
graphs = new LinkedList();
}
public void run()
{
validate();
loadFile();
buildGraphsInfo();
buildGraphs();
printAll();
algorithm();
showResult();
}
private void validate()
{
String directory = System.getProperty("user.dir") + "/";
file = new File(directory + fileName);
if(!file.exists())
{
System.out.print("\n\tO ficheiro \"" + file.toString() + "\" nao foi encontrado\n");
System.exit(1);
}
algorithm = algorithm.toLowerCase();
if(!algorithm.equals("p") && !algorithm.equals("k"))
{
System.out.print("\n\tAlgoritmo invalido\n");
System.exit(1);
}
}
private void loadFile()
{
int line = 0;
try
{
BufferedReader bufReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String str;
str = "";
while(!str.equals("#"))
{
str = bufReader.readLine();
line++;
if(str == null)
{
System.out.print("\n\tO ficheiro nao tem o formato correcto ( Linha " + line + " )\n");
System.exit(1);
}
}
str = bufReader.readLine();
line++;
if(str == null)
{
System.out.print("\n\tO ficheiro nao tem o formato correcto ( Linha " + line + " )\n");
System.exit(1);
}
while(!str.equals("#"))
{
StringTokenizer strTok = new StringTokenizer(str);
if(strTok.countTokens() != 3)
{
System.out.print("\n\tO ficheiro nao tem o formato correcto ( Linha " + line + " )\n");
System.exit(1);
}
String s1 = strTok.nextToken();
String s2 = strTok.nextToken();
if(!checkString(s1))
{
System.out.print("\n\tO ficheiro nao tem o formato correcto ( Linha " + line + " )\n");
System.exit(1);
}
if(!checkString(s2))
{
System.out.print("\n\tO ficheiro nao tem o formato correcto ( Linha " + line + " )\n");
System.exit(1);
}
boolean f1 = true;
boolean f2 = true;
for(ListIterator listItr = verticesInfo.listIterator() ; listItr.hasNext() ; )
{
VertexInfo vInfo = (VertexInfo) listItr.next();
if(vInfo.name.equals(s1)) f1 = false;
if(vInfo.name.equals(s2)) f2 = false;
}
if(f1) verticesInfo.addLast(new VertexInfo(s1));
if(f2 && !s2.equals(s1)) verticesInfo.addLast(new VertexInfo(s2));
int weight = 0;
try
{
weight = Integer.parseInt(strTok.nextToken());
}
catch(NumberFormatException nfe)
{
System.out.print("\n\tO ficheiro nao tem o formato correcto ( Linha " + line + " )\n");
System.exit(1);
}
edgesInfo.addLast(new EdgeInfo(s1,s2,weight));
str = bufReader.readLine();
line++;
if(str == null)
{
System.out.print("\n\tO ficheiro nao tem o formato correcto ( Linha " + line + " )\n");
System.exit(1);
}
}
bufReader.close();
}
catch(Exception e)
{
System.out.print("\n" + e.toString() + "\n");
System.exit(1);
}
}
private void buildGraphsInfo()
{
GraphInfo gInfo;
for(ListIterator listItr = edgesInfo.listIterator() ; listItr.hasNext() ; )
{
EdgeInfo eInfo = (EdgeInfo) listItr.next();
int index1 = indexOf(eInfo.v1Name);
int index2 = indexOf(eInfo.v2Name);
if(index1 == index2)
{
if(index1 == -1)
{
gInfo = new GraphInfo();
gInfo.verticesInfo.addLast(new VertexInfo(eInfo.v1Name));
if(!eInfo.v2Name.equals(eInfo.v1Name)) gInfo.verticesInfo.addLast(new VertexInfo(eInfo.v2Name));
gInfo.edgesInfo.addLast(eInfo);
graphsInfo.addLast(gInfo);
}
else
{
gInfo = (GraphInfo) graphsInfo.get(index1);
gInfo.edgesInfo.addLast(eInfo);
}
}
else
{
if(index1 == -1)
{
gInfo = (GraphInfo) graphsInfo.get(index2);
gInfo.verticesInfo.addLast(new VertexInfo(eInfo.v1Name));
gInfo.edgesInfo.addLast(eInfo);
}
else if(index2 == -1)
{
gInfo = (GraphInfo) graphsInfo.get(index1);
gInfo.verticesInfo.addLast(new VertexInfo(eInfo.v2Name));
gInfo.edgesInfo.addLast(eInfo);
}
else
{
gInfo = (GraphInfo) graphsInfo.get(index1);
GraphInfo gInfoAux = (GraphInfo) graphsInfo.get(index2);
gInfo.verticesInfo.addAll(gInfoAux.verticesInfo);
gInfo.edgesInfo.addAll(gInfoAux.edgesInfo);
gInfo.edgesInfo.addLast(eInfo);
graphsInfo.remove(gInfoAux);
}
}
}
verticesInfo.clear();
edgesInfo.clear();
System.gc();
}
private void buildGraphs()
{
for(ListIterator listItr = graphsInfo.listIterator() ; listItr.hasNext() ; )
{
GraphInfo gInfo = (GraphInfo) listItr.next();
Graph graph = new Graph();
for(ListIterator listItr1 = gInfo.verticesInfo.listIterator() ; listItr1.hasNext() ; )
{
try
{
graph.addVertex( ((VertexInfo) listItr1.next()).name );
}
catch(AlreadyAddedException e1)
{
System.out.print("\n\tDeclaracao duplicada de um vertice\n");
System.exit(1);
}
}
for(ListIterator listItr2 = gInfo.edgesInfo.listIterator() ; listItr2.hasNext() ; )
{
EdgeInfo eInfo = (EdgeInfo) listItr2.next();
try
{
graph.addEdge(eInfo.v1Name,eInfo.v2Name,eInfo.weight);
}
catch(EqualVerticesException e2)
{
System.out.print("\n\tDeclarao de uma ligacao de um vertice para si proprio ( " + eInfo.v1Name + " <-> " + eInfo.v2Name + " )\n");
System.exit(1);
}
catch(NoSuchVertexException e3)
{
System.out.print("\n\tDeclaracao de uma ligacao usando um vertice nao existente ( " + eInfo.v1Name + " <-> " + eInfo.v2Name + " )\n");
System.exit(1);
}
catch(NegativeWeightException e4)
{
System.out.print("\n\tDeclaracao de uma ligacao usando um peso negativo ( " + eInfo.v1Name + " <-> " + eInfo.v2Name + " )\n");
System.exit(1);
}
catch(AlreadyConnectedException e5)
{
System.out.print("\n\tDeclaracao duplicada de uma ligacao ( " + eInfo.v1Name + " <-> " + eInfo.v2Name + " )\n");
System.exit(1);
}
}
graphs.addLast(graph);
}
graphsInfo.clear();
System.gc();
}
private void printAll()
{
int i = 1;
for(ListIterator listItr = graphs.listIterator() ; listItr.hasNext() ; )
{
Graph graph = (Graph) listItr.next();
System.out.print("\n\tGrafo " + i + "\n\n");
System.out.print(graph.toString());
i++;
}
}
private void algorithm()
{
int i = 1;
ListIterator listItr;
Graph graph;
if(algorithm.equals("p"))
for(listItr = graphs.listIterator() ; listItr.hasNext() ; )
{
System.out.print("\n\tA executar o Algoritmo de Prim no grafo " + i + "...");
graph = (Graph) listItr.next();
graph.prim();
i++;
}
else if(algorithm.equals("k"))
for(listItr = graphs.listIterator() ; listItr.hasNext() ; )
{
System.out.print("\n\tA executar o Algoritmo de Kruskal no grafo " + i + "...");
graph = (Graph) listItr.next();
graph.kruskal();
i++;
}
System.out.print("\n");
}
private void showResult()
{
int i = 1;
for(ListIterator listItr = graphs.listIterator() ; listItr.hasNext() ; )
{
Graph graph = (Graph) listItr.next();
System.out.print("\n\tGrafo " + i + " - Arvore de expansao minima\n\n");
System.out.print(graph.getAlgorithmResult());
i++;
}
}
private boolean checkString(String s)
{
boolean b = true;
if(s.length() == 0) b = false;
else for(int i = 0 ; i < s.length() ; i++)
if(!Character.isLetter(s.charAt(i)) && !Character.isDigit(s.charAt(i)))
{
b = false;
break;
}
return b;
}
private int indexOf(String vertexName)
{
int index = -1;
int i = 0;
boolean flag = false;
for(ListIterator listItr1 = graphsInfo.listIterator() ; listItr1.hasNext() ; )
{
GraphInfo gInfo = (GraphInfo) listItr1.next();
for(ListIterator listItr2 = gInfo.verticesInfo.listIterator() ; listItr2.hasNext() ; )
{
VertexInfo vInfo = (VertexInfo) listItr2.next();
if(vInfo.name.equals(vertexName))
{
index = i;
flag = true;
break;
}
}
if(flag) break;
i++;
}
return index;
}
private class VertexInfo
{
String name;
public VertexInfo(String name)
{
this.name = name;
}
}
private class EdgeInfo
{
String v1Name;
String v2Name;
int weight;
public EdgeInfo(String v1Name,String v2Name,int weight)
{
this.v1Name = v1Name;
this.v2Name = v2Name;
this.weight = weight;
}
}
private class GraphInfo
{
LinkedList verticesInfo;
LinkedList edgesInfo;
public GraphInfo()
{
verticesInfo = new LinkedList();
edgesInfo = new LinkedList();
}
}
public static void main(String args[])
{
if(args.length != 2)
{
System.out.print("\n\tUso: Main [ Ficheiro de entrada ] [ Algoritmo ]\n");
System.out.print("\n\t[ Algoritmo ]\n");
System.out.print("\n\tP - Algoritmo de Prim");
System.out.print("\n\tK - Algoritmo de Kruskal\n");
System.exit(1);
}
new Thread(new Main(args[0],args[1])).start();
}
} | 29.874172 | 154 | 0.427326 |
a5823c48fdca53fd034f9189547c0e4480b04ae0 | 361 | package uk.co.sentinelweb.tvmod.exoplayer.upstream;
import com.google.android.exoplayer2.upstream.DataSource;
/**
* TODO pass in usrname and password config?
*/
public class SmbDataSourceFactory implements DataSource.Factory {
@Override
public DataSource createDataSource() {
return new SmbDataSource(null/*listener - not needed*/);
}
} | 25.785714 | 65 | 0.745152 |
e326c883526f2544ac1b207f64febb3f65b4fa2c | 988 | package io.jenkins.blueocean.service.embedded.rest;
import com.google.common.collect.ImmutableMap;
import hudson.Extension;
import hudson.model.User;
import hudson.util.AdaptedIterator;
import io.jenkins.blueocean.rest.model.BlueUser;
import io.jenkins.blueocean.rest.model.BlueUserContainer;
import java.util.Iterator;
/**
*
* @author Vivek Pandey
* @author Kohsuke Kawaguchi
*/
@Extension
public class UserContainerImpl extends BlueUserContainer {
@Override
public BlueUser get(String name) {
User user = User.get(name, false, ImmutableMap.of());
if (user==null) return null;
return new UserImpl(user);
}
/**
* Iterates all the users in the system
*/
@Override
public Iterator<BlueUser> iterator() {
return new AdaptedIterator<User, BlueUser>(User.getAll()) {
@Override
protected BlueUser adapt(User item) {
return new UserImpl(item);
}
};
}
}
| 25.333333 | 67 | 0.66498 |
241ec5ce2bbfd24a91e2720ef762110fff33c00a | 335 | package OctopusConsortium.Core;
public class ExternalServiceException extends Exception {
/**
*
*/
private static final long serialVersionUID = 569442375626316093L;
public ExternalServiceException(String message){
super(message);
}
public ExternalServiceException(String string, Exception e) {
super(string, e);
}
}
| 18.611111 | 66 | 0.761194 |
289d274f07df7959e7a52d689151e691f3056bf1 | 10,205 | package sososlik.countryonjoin;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Iterator;
import com.maxmind.db.CHMCache;
import com.maxmind.geoip2.DatabaseReader;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
public class Plugin extends net.md_5.bungee.api.plugin.Plugin
{
public static final String GEOIP_DB_FILENAME = "GeoLite2-Country.mmdb";
public static final String README_FILENAME = "README.txt";
public static final String CONFIG_FILENAME = "config.yml";
public static final String MESSAGES_FILENAME_PATTERN = "messages\\..\\.yml";
public static final String MESSAGES_BASEDIR = "messages";
public static final String MESSAGES_FILENAME_FORMAT = "messages.%s.yml";
public static final String COUNTRYNAMES_FILENAME_PATTERN = "countrynames\\..\\.yml";
public static final String COUNTRYNAMES_BASEDIR = "countrynames";
public static final String COUNTRYNAMES_FILENAME_FORMAT = "countrynames.%s.yml";
public static final String PERMISSIONS_BASE = "countryonjoin";
public static final String UNKNOWN_COUNTRY_KEY = "unknown";
public static final String COMMANDS_BASE = "countryonjoin";
private static Plugin instance;
private DatabaseReader geoipdbreader;
private Config config;
public Plugin()
{
instance = this;
}
@Override
public void onEnable()
{
File dataDir = this.getDataFolder();
if (!dataDir.exists())
{
try
{
dataDir.mkdir();
}
catch(Exception e)
{
this.getLogger().severe("Error creating the plugin data directory \"" + dataDir.getAbsolutePath() + "\".");
e.printStackTrace();
return;
}
}
File configFile = new File(dataDir, CONFIG_FILENAME);
if(!configFile.exists())
{
try(InputStream rs = this.getResourceAsStream(CONFIG_FILENAME))
{
Files.copy(rs, configFile.toPath());
} catch (Exception e)
{
this.getLogger().severe("Error extracting the file \"" + CONFIG_FILENAME +"\" to \"" + configFile.getAbsolutePath() + "\".");
e.printStackTrace();
return;
}
}
File messagesBaseDir = new File(dataDir, MESSAGES_BASEDIR);
if(!messagesBaseDir.exists())
{
try
{
messagesBaseDir.mkdir();
}
catch (Exception e)
{
this.getLogger().severe("Error creating " + messagesBaseDir.getAbsolutePath() + " directory.");
e.printStackTrace();
return;
}
}
try(FileSystem fs = FileSystems.newFileSystem(Plugin.class.getResource("/" + MESSAGES_BASEDIR).toURI(), Collections.<String, Object>emptyMap()))
{
Iterator<Path> it = Files.walk(fs.getPath("/" + MESSAGES_BASEDIR), 1).iterator();
while(it.hasNext())
{
Path p = it.next();
if(p.toString().equals("/" + MESSAGES_BASEDIR))
{
continue; //The first entry appears to be always the directory which we are enumerating...
}
File f = new File(messagesBaseDir, p.getFileName().toString());
if(!f.exists())
{
try (InputStream rs = this.getResourceAsStream(MESSAGES_BASEDIR + "/" + f.getName()))
{
Files.copy(rs, f.toPath());
}
catch (Exception e)
{
this.getLogger().severe("Error extracting the file \"" + MESSAGES_BASEDIR + "/" + f.getName() + "\" to \"" + f.getAbsolutePath() + "\".");
throw e;
}
}
}
}
catch (Exception e)
{
this.getLogger().severe("Error extracting the directory \"" + MESSAGES_BASEDIR + "\" to \"" + messagesBaseDir.getAbsolutePath() + "\".");
e.printStackTrace();
return;
}
File countrynamesBaseDir = new File(dataDir, COUNTRYNAMES_BASEDIR);
if(!countrynamesBaseDir.exists())
{
try
{
countrynamesBaseDir.mkdir();
}
catch (Exception e)
{
this.getLogger().severe("Error creating " + countrynamesBaseDir.getAbsolutePath() + " directory.");
e.printStackTrace();
return;
}
}
try(FileSystem fs = FileSystems.newFileSystem(Plugin.class.getResource("/" + COUNTRYNAMES_BASEDIR).toURI(), Collections.<String, Object>emptyMap()))
{
Iterator<Path> it = Files.walk(fs.getPath("/" + COUNTRYNAMES_BASEDIR), 1).iterator();
while(it.hasNext())
{
Path p = it.next();
if(p.toString().equals("/" + COUNTRYNAMES_BASEDIR))
{
continue; //The first entry appears to be always the directory which we are enumerating...
}
File f = new File(countrynamesBaseDir, p.getFileName().toString());
if(!f.exists())
{
try (InputStream rs = this.getResourceAsStream(COUNTRYNAMES_BASEDIR + "/" + f.getName()))
{
Files.copy(rs, f.toPath());
}
catch (Exception e)
{
this.getLogger().severe("Error extracting the file \"" + COUNTRYNAMES_BASEDIR + "/" + f.getName() + "\" to \"" + f.getAbsolutePath() + "\".");
throw e;
}
}
}
}
catch (Exception e)
{
this.getLogger().severe("Error extracting the directory \"" + COUNTRYNAMES_BASEDIR + "\" to \"" + countrynamesBaseDir.getAbsolutePath() + "\".");
e.printStackTrace();
return;
}
File geoipdbFile = new File(dataDir, GEOIP_DB_FILENAME);
if(!geoipdbFile.exists())
{
try(InputStream rs = this.getResourceAsStream(GEOIP_DB_FILENAME))
{
Files.copy(rs, geoipdbFile.toPath());
}
catch (Exception e)
{
this.getLogger().severe("Error extracting the file \"" + GEOIP_DB_FILENAME + "\" to \"" + geoipdbFile.getAbsolutePath() + "\".");
e.printStackTrace();
return;
}
}
File readmeFile = new File(dataDir, README_FILENAME);
if(!readmeFile.exists())
{
try(InputStream rs = this.getResourceAsStream(README_FILENAME))
{
Files.copy(rs, readmeFile.toPath());
}
catch (Exception e)
{
this.getLogger().severe("Error extracting the file \"" + README_FILENAME + "\" to \"" + readmeFile.getAbsolutePath() + "\".");
e.printStackTrace();
return;
//the README file is critical because legal reasons (maxmind's license requires to mention their website in the product)
}
}
this.reload(); //the first time it means 'load' and if fail should not disable the plugin
this.getProxy().getPluginManager().registerListener(this, new Listener());
this.getProxy().getPluginManager().registerCommand(this, new BaseCommand());
}
public void reload()
{
//means 'load' on first time call
//NOTE: don't disable the plugin here, user can edit the config/message files and use 'reload' command for resolve the problem
File dataDir = this.getDataFolder();
File configFile = new File(dataDir, CONFIG_FILENAME);
if(this.config == null)
{
this.config = new Config();
}
try {
Configuration config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
this.config.setBroadcastOnUnknownCountry(config.getBoolean("broadcastOnUnknownCountry"));
this.config.setBroadcastAltJoinMsgOnUnknownCountry(config.getBoolean("broadcastAltJoinMsgOnUnknownCountry"));
this.config.setMessagesCulture(config.getString("messages-culture"));
this.config.setCountrynamesCulture(config.getString("countrynames-culture"));
this.config.setDebug(config.getBoolean("debug"));
} catch (Exception e) {
this.getLogger().severe("Error loading the " + configFile.getName() + " file.");
e.printStackTrace();
}
File messagesBaseDir = new File(dataDir, MESSAGES_BASEDIR);
File messagesFile = new File(messagesBaseDir, String.format(MESSAGES_FILENAME_FORMAT, this.config.getMessagesCulture()));
try (InputStreamReader sr = new InputStreamReader(new FileInputStream(messagesFile), "UTF8"))
{
Configuration messages = ConfigurationProvider.getProvider(YamlConfiguration.class).load(sr);
this.config.setJoinWithCountryMessage(messages.getString("joinWithCountry"));
this.config.setJoinWithoutCountryMessage(messages.getString("joinWithoutCountry"));
} catch (Exception e)
{
this.getLogger().severe("Error loading the " + messagesFile.getName() + " file.");
e.printStackTrace();
}
File countrynamesBaseDir = new File(dataDir, COUNTRYNAMES_BASEDIR);
File countrynamesFile = new File(countrynamesBaseDir, String.format(COUNTRYNAMES_FILENAME_FORMAT, this.config.getCountrynamesCulture()));
try(InputStreamReader sr = new InputStreamReader(new FileInputStream(countrynamesFile), "UTF8"))
{
Configuration countrynames = ConfigurationProvider.getProvider(YamlConfiguration.class).load(sr);
this.config.getCountryNames().clear(); //need that because a reloaded file maybe not contains all the keys that previous
for(String key : countrynames.getKeys())
{
this.config.getCountryNames().put(key, countrynames.getString(key));
}
} catch (Exception e)
{
this.getLogger().severe("Error loading the " + countrynamesFile.getName() + " file.");
e.printStackTrace();
}
File geoipdbFile = new File(dataDir, GEOIP_DB_FILENAME);
if(this.geoipdbreader != null)
{
try {
this.geoipdbreader.close();
}
catch (IOException e)
{
this.getLogger().severe("Error closing the " + geoipdbFile.getName() + " file.");
e.printStackTrace();
}
}
try
{
this.geoipdbreader = new DatabaseReader.Builder(geoipdbFile).withCache(new CHMCache()).build();
}
catch (IOException e)
{
this.getLogger().severe("Error loading the " + geoipdbFile.getName() + " file.");
e.printStackTrace();
}
}
public static Plugin getInstance()
{
return instance;
}
public DatabaseReader getGeoIPDBReader()
{
return this.geoipdbreader;
}
public Config getConfig()
{
return this.config;
}
}
| 29.324713 | 154 | 0.663694 |
8310748abd906aa4b9471d6818a25e5f409dec54 | 8,376 | /*
* Copyright (C) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.beam.examples.complete.game;
import com.google.api.services.bigquery.model.TableFieldSchema;
import com.google.api.services.bigquery.model.TableReference;
import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.TableSchema;
import java.util.ArrayList;
import java.util.List;
import org.apache.beam.examples.complete.game.solutions.Exercise3.ReadGameEvents;
import org.apache.beam.examples.complete.game.utils.ChangeMe;
import org.apache.beam.examples.complete.game.utils.GameEvent;
import org.apache.beam.examples.complete.game.utils.Options;
import org.apache.beam.runners.dataflow.DataflowRunner;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.StreamingOptions;
import org.apache.beam.sdk.transforms.Combine;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.transforms.Mean;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.IntervalWindow;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TypeDescriptors;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Sixth in a series of coding exercises in a gaming domain.
*
* <p>This exercise introduces session windows.
*
* <p>See README.md for details.
*/
public class Exercise6 {
private static final Logger LOG = LoggerFactory.getLogger(Exercise6.class);
/**
* Calculate and output an element's session duration.
*/
private static class UserSessionInfoFn extends DoFn<KV<String, Integer>, Integer> {
@ProcessElement
public void processElement(ProcessContext c, BoundedWindow window) {
IntervalWindow w = (IntervalWindow) window;
int duration = new Duration(w.start(), w.end()).toPeriod().toStandardMinutes().getMinutes();
c.output(duration);
}
}
/**
* Options supported by {@link Exercise6}.
*/
interface Exercise6Options extends Options, StreamingOptions {
@Description("Numeric value of gap between user sessions, in minutes")
@Default.Integer(1)
Integer getSessionGap();
void setSessionGap(Integer value);
@Description(
"Numeric value of fixed window for finding mean of user session duration, " + "in minutes")
@Default.Integer(5)
Integer getUserActivityWindowDuration();
void setUserActivityWindowDuration(Integer value);
}
public static void main(String[] args) throws Exception {
Exercise6Options options =
PipelineOptionsFactory.fromArgs(args).withValidation().as(Exercise6Options.class);
// Enforce that this pipeline is always run in streaming mode.
options.setStreaming(true);
options.setRunner(DataflowRunner.class);
Pipeline pipeline = Pipeline.create(options);
TableReference sessionsTable = new TableReference();
sessionsTable.setDatasetId(options.getOutputDataset());
sessionsTable.setProjectId(options.as(GcpOptions.class).getProject());
sessionsTable.setTableId(options.getOutputTableName());
PCollection<GameEvent> rawEvents = pipeline.apply(new ReadGameEvents(options));
// Extract username/score pairs from the event stream
PCollection<KV<String, Integer>> userEvents =
rawEvents.apply(
"ExtractUserScore",
MapElements
.into(TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers()))
.via((GameEvent gInfo) -> KV.<String, Integer>of(gInfo.getUser(),
gInfo.getScore())));
// [START EXERCISE 6]:
// Detect user sessions-- that is, a burst of activity separated by a gap from further
// activity. Find and record the mean session lengths.
// This information could help the game designers track the changing user engagement
// as their set of games changes.
userEvents
// Window the user events into sessions with gap options.getSessionGap() minutes. Make sure
// to use an outputTimeFn that sets the output timestamp to the end of the window. This will
// allow us to compute means on sessions based on their end times, rather than their start
// times.
// JavaDoc:
// - https://beam.apache.org/documentation/sdks/javadoc/2.0.0/org/apache/beam/sdk/transforms/windowing/Sessions.html
// - https://beam.apache.org/documentation/sdks/javadoc/2.0.0/org/apache/beam/sdk/transforms/windowing/Window.html
// Note: Pay attention to the withTimestampCombiner method on Window.
.apply("WindowIntoSessions",
/* TODO: YOUR CODE GOES HERE */
new ChangeMe<PCollection<KV<String, Integer>>, KV<String, Integer>>())
// For this use, we care only about the existence of the session, not any particular
// information aggregated over it, so the following is an efficient way to do that.
.apply(Combine.perKey(x -> 0))
// Get the duration per session.
.apply("UserSessionActivity", ParDo.of(new UserSessionInfoFn()))
// Note that the output of the previous transform is a PCollection of session durations
// (PCollection<Integer>) where the timestamp of elements is the end of the window.
//
// Re-window to process groups of session sums according to when the sessions complete.
// In streaming we don't just ask "what is the mean value" we must ask "what is the mean
// value for some window of time". To compute periodic means of session durations, we
// re-window the session durations.
.apply("WindowToExtractSessionMean",
/* TODO: YOUR CODE GOES HERE */
new ChangeMe<PCollection<Integer>, Integer>())
// Find the mean session duration in each window.
.apply(Mean.<Integer>globally().withoutDefaults())
// Write this info to a BigQuery table.
.apply("FormatSessions", ParDo.of(new FormatSessionWindowFn()))
.apply(
BigQueryIO.writeTableRows().to(sessionsTable)
.withSchema(FormatSessionWindowFn.getSchema())
.withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(WriteDisposition.WRITE_APPEND));
// [END EXERCISE 6]:
PipelineResult result = pipeline.run();
result.waitUntilFinish();
}
/**
* Format a KV of session and associated properties to a BigQuery TableRow.
*/
static class FormatSessionWindowFn extends DoFn<Double, TableRow> {
@ProcessElement
public void processElement(ProcessContext c, BoundedWindow window) {
IntervalWindow w = (IntervalWindow) window;
TableRow row =
new TableRow()
.set("window_start", w.start().getMillis() / 1000)
.set("mean_duration", c.element());
c.output(row);
}
static TableSchema getSchema() {
List<TableFieldSchema> fields = new ArrayList<>();
fields.add(new TableFieldSchema().setName("window_start").setType("TIMESTAMP"));
fields.add(new TableFieldSchema().setName("mean_duration").setType("FLOAT"));
return new TableSchema().setFields(fields);
}
}
}
| 43.853403 | 126 | 0.718601 |
867c10b8fc2d5f89d1080bc08dc6654782a88197 | 4,221 | package touristagency.persistence.repository.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import touristagency.model.Employee;
import touristagency.persistence.repository.EmployeeRepository;
import touristagency.persistence.repository.RepositoryException;
import java.util.ArrayList;
import java.util.List;
public class EmployeeDBRepositoryHibernate implements EmployeeRepository {
private SessionFactory sessionFactory;
public EmployeeDBRepositoryHibernate(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public Employee findByUsername(String username) {
System.out.println("In hibernate repo...");
try(Session session = sessionFactory.openSession()) {
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Query<Employee> query = session.createQuery("from Employee where username = :username");
query.setParameter("username", username);
List<Employee> employees = query.list();
transaction.commit();
return employees.get(0);
} catch (RepositoryException ex) {
if(transaction != null)
transaction.rollback();
}
}
return null;
}
@Override
public Employee findOne(Integer id) {
try(Session session = sessionFactory.openSession()) {
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Query<Employee> query = session.createQuery("from Employee where id = :id");
query.setParameter("id", id);
List<Employee> employees = query.list();
transaction.commit();
return employees.get(0);
} catch (RepositoryException ex) {
if(transaction != null)
transaction.rollback();
}
}
return null;
}
@Override
public Iterable<Employee> findAll() {
List<Employee> all = new ArrayList<>();
try(Session session = sessionFactory.openSession()) {
Transaction transaction = null;
try {
transaction = session.beginTransaction();
all = session.createQuery("from Employee", Employee.class).list();
transaction.commit();
} catch (RepositoryException ex) {
if(transaction != null)
transaction.rollback();
}
}
return all;
}
@Override
public void add(Employee employee) {
try(Session session = sessionFactory.openSession()) {
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(employee);
transaction.commit();
} catch (RepositoryException ex) {
if(transaction != null)
transaction.rollback();
}
}
}
@Override
public void delete(Employee employee) {
try(Session session = sessionFactory.openSession()) {
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.delete(employee);
transaction.commit();
} catch (RepositoryException ex) {
if(transaction != null) {
transaction.rollback();
}
}
}
}
@Override
public void update(Employee employee, Integer id) {
try(Session session = sessionFactory.openSession()) {
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.update(employee);
transaction.commit();
} catch (RepositoryException ex) {
if(transaction != null) {
transaction.rollback();
}
}
}
}
}
| 33.768 | 104 | 0.564558 |
fb3308899dd9e213f98bdebf2984f427215b73f8 | 23,969 |
package com.vibes.push.cordova.plugin;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.Map;
import java.util.Collection;
import java.lang.reflect.InvocationTargetException;
import android.app.Application;
import android.content.Context;
import android.content.Context;
import android.util.Log;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.Context;
import android.content.Intent;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.vibes.vibes.Vibes;
import com.vibes.vibes.VibesConfig;
import com.vibes.vibes.VibesListener;
import com.vibes.vibes.Credential;
import com.vibes.vibes.Person;
import com.vibes.vibes.InboxMessage;
import com.google.gson.Gson;
import com.vibes.push.cordova.plugin.FMS;
/**
* Entry point into the cordova plugin.
*/
public class VibesPlugin extends CordovaPlugin {
private static final String TAG = "c.v.pcp.VibesPlugin";
public static final String REGISTERED = "REGISTERED";
public static final String PUSH_REGISTERED = "PUSH_REGISTERED";
public static final String DEVICE_ID = "VibesPlugin.DEVICE_ID";
public static final String VIBES_APPID_KEY = "vibes_app_id";
public static final String VIBES_APIURL_KEY = "vibes_api_url";
private String[] actions = {
"registerDevice", "unregisterDevice", "registerPush", "unregisterPush", "associatePerson", "getVibesDeviceInfo",
"getPerson", "onNotificationOpened", "fetchInboxMessages", "expireInboxMessage", "markInboxMessageAsRead",
"fetchInboxMessage", "onInboxMessageOpen"
};
private static CallbackContext notificationCallbackContext;
private static ArrayList<Bundle> notificationStack = null;
/**
* Gets the application context from cordova's main activity.
*
* @return the application context
*/
private Context getApplicationContext() {
return this.cordova.getActivity().getApplicationContext();
}
@Override
public void pluginInitialize() {
Log.d(TAG, "Initialing the Vibes Push SDK and registering your device");
Bundle extras = this.cordova.getActivity().getIntent().getExtras();
this.initializeSDK();
this.registerDeviceAtStartup();
if (extras != null && extras.size() > 1) {
if (VibesPlugin.notificationStack == null) {
VibesPlugin.notificationStack = new ArrayList<Bundle>();
}
if (extras.containsKey(Vibes.VIBES_REMOTE_MESSAGE_DATA)) {
notificationStack.add(extras);
}
}
}
public boolean execute(String action, JSONArray args, final CallbackContext callback) throws JSONException {
Log.i(TAG, String.format("Plugin called with the action [%s] and arguments [%s]", action, args));
Context context = getApplicationContext();
//check if method invoked is one of the supported methods.
List<String> list = Arrays.asList(actions);
if (!list.contains(action)) {
callback.error("\"" + action + "\" is not a recognized action.");
return false;
}
if (action.equals("registerDevice")) {
VibesListener<Credential> listener = getRegisterDeviceListener(callback);
this.registerDevice(listener);
} else if (action.equals("unregisterDevice")) {
this.unregisterDevice(callback);
} else if (action.equals("registerPush")) {
SharedPrefsManager prefsManager = new SharedPrefsManager(context);
String pushToken = prefsManager.getStringData(FMS.TOKEN_KEY);
if (pushToken == null) {
FirebaseInstanceId.getInstance().getInstanceId()
.addOnSuccessListener(
new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String instanceToken = instanceIdResult.getToken();
if (instanceToken == null) {
callback.error("No push token available for registration yet");
} else {
SharedPrefsManager prefsManager = new SharedPrefsManager(context);
prefsManager.saveData(FMS.TOKEN_KEY, instanceToken);
Log.d(TAG, "Push token obtianed from FirebaseInstanceId --> " + instanceToken);
VibesListener<Void> listener = getRegisterPushListener(callback);
registerPush(instanceToken, listener);
}
}
}
)
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.d(TAG, "Failed to fetch token from FirebaseInstanceId: "+ e.getLocalizedMessage());
callback.error("No push token available for registration yet");
}
}
);
} else {
VibesListener<Void> listener = getRegisterPushListener(callback);
registerPush(pushToken, listener);
}
} else if (action.equals("unregisterPush")) {
this.unregisterPush(callback);
} else if (action.equals("getVibesDeviceInfo")) {
this.getVibesDeviceInfo(callback);
} else if (action.equals("getPerson")) {
VibesListener<Person> listener = new VibesListener<Person>() {
public void onSuccess(Person person) {
String jsonString = null;
try {
JSONObject json = new JSONObject();
json.put("person_key", person.getPersonKey());
json.put("mdn", person.getMdn());
json.put("external_person_id", person.getExternalPersonId());
jsonString = json.toString();
} catch (JSONException ex) {
Log.e(TAG, "Error serializing person to json");
}
callback.success(jsonString);
}
public void onFailure(String errorText) {
callback.error(errorText);
}
};
this.getPerson(listener);
} else if (action.equals("associatePerson")) {
String externalPersonId = args.getString(0);
Log.d(TAG, "Associating Person --> " + externalPersonId);
VibesListener<Void> listener = new VibesListener<Void>() {
public void onSuccess(Void value) {
callback.success();
}
public void onFailure(String errorText) {
callback.error(errorText);
}
};
this.associatePerson(externalPersonId, listener);
} else if (action.equals("onNotificationOpened")) {
this.onNotificationOpened(callback);
} else if (action.equals("fetchInboxMessages")) {
VibesListener<Collection<InboxMessage>> listener = new VibesListener<Collection<InboxMessage>>() {
public void onSuccess(Collection<InboxMessage> inboxMessages) {
Gson gson = new Gson();
String jsonString = gson.toJson(inboxMessages);
callback.success(jsonString);
}
public void onFailure(String errorText) {
callback.error(errorText);
}
};
this.fetchInboxMessages(listener);
} else if (action.equals("expireInboxMessage")) {
if (args.length() < 1) {
callback.error("No arguments supplied");
return true;
}
String messageId = args.getString(0);
Date date = new Date();
if (args.length() > 1) {
Date datePassed = PluginDateFormatter.fromISOString(args.getString(1));
if (datePassed != null) {
date = datePassed;
Log.d(TAG, "Expiry date supplied is a valid ISO Date format. Will be used in call");
} else {
Log.e(TAG, "Date supplied cannot be converted to ISO Date format. Using default date");
}
}
VibesListener<InboxMessage> listener = new VibesListener<InboxMessage>() {
public void onSuccess(InboxMessage value) {
Gson gson = new Gson();
String jsonString = gson.toJson(value);
callback.success(jsonString);
}
public void onFailure(String errorText) {
callback.error(errorText);
}
};
this.expireInboxMessage(messageId, date, listener);
} else if (action.equals("markInboxMessageAsRead")) {
String messageId = args.getString(0);
VibesListener<InboxMessage> listener = new VibesListener<InboxMessage>() {
public void onSuccess(InboxMessage value) {
Gson gson = new Gson();
String jsonString = gson.toJson(value);
callback.success(jsonString);
}
public void onFailure(String errorText) {
callback.error(errorText);
}
};
this.markInboxMessageAsRead(messageId, listener);
} else if (action.equals("fetchInboxMessage")) {
if (args.length() < 1) {
callback.error("No message id supplied");
return true;
}
String messageId = args.getString(0);
VibesListener<InboxMessage> listener = new VibesListener<InboxMessage>() {
public void onSuccess(InboxMessage value) {
Gson gson = new Gson();
String jsonString = gson.toJson(value);
callback.success(jsonString);
}
public void onFailure(String errorText) {
callback.error(errorText);
}
};
this.fetchInboxMessage(messageId, listener);
} else if (action.equals("onInboxMessageOpen")) {
if (args.length() < 1) {
callback.error("No message object supplied");
return true;
}
String inboxJsonString = args.getString(0);
try {
Gson gson = new Gson();
InboxMessage message = gson.fromJson(inboxJsonString, InboxMessage.class);
Log.d(TAG, "Conversion of json payload for inbox message to InboxMessage object successful");
Vibes.getInstance().onInboxMessageOpen(message);
callback.success();
} catch (Exception e) {
Log.e(TAG, "Failure converting payload to Inbox message "+e.getMessage());
callback.error(e.getMessage());
}
}
return true;
}
/**
* Uses the values passed from preferences into the vibes_app_id and vibes_api_url to initialize the SDK.
* Crashes the app with appropriate message if those 2 values are not supplied.
*/
private void initializeSDK() {
String appId = null;
String apiUrl = null;
try {
ApplicationInfo ai = getApplicationContext().getPackageManager()
.getApplicationInfo(getApplicationContext().getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
appId = bundle.getString(VIBES_APPID_KEY);
apiUrl = bundle.getString(VIBES_APIURL_KEY);
Log.d(TAG, "Vibes parameters are : appId=[" + appId + "], appUrl=[" + apiUrl + "]");
} catch (PackageManager.NameNotFoundException ex) {
}
if (appId == null || appId.isEmpty()) {
throw new IllegalStateException("No appId provided in manifest under meta-data name [" + VIBES_APPID_KEY + "]");
}
if (apiUrl == null || apiUrl.isEmpty()) {
throw new IllegalStateException("No url provided in manifest under meta-data name [" + VIBES_APIURL_KEY + "]");
}
VibesConfig config = new VibesConfig.Builder().setApiUrl(apiUrl).setAppId(appId).build();
Vibes.initialize(getApplicationContext(), config);
}
private void registerDeviceAtStartup() {
VibesListener<Credential> listener = getRegisterDeviceListener(null);
this.registerDevice(listener);
}
private VibesListener<Credential> getRegisterDeviceListener(final CallbackContext callback) {
return new VibesListener<Credential>() {
public void onSuccess(Credential credential) {
SharedPrefsManager prefsManager = new SharedPrefsManager(VibesPlugin.this.getApplicationContext());
prefsManager.saveBoolean(VibesPlugin.REGISTERED, true);
String deviceId = credential.getDeviceID();
prefsManager.saveData(VibesPlugin.DEVICE_ID, deviceId);
Log.d(TAG, "Device id obtained is --> " + deviceId);
String pushToken = prefsManager.getStringData(FMS.TOKEN_KEY);
if (pushToken == null) {
Log.d(TAG, "Token not yet available. Skipping registerPush");
} else {
Log.d(TAG, "Token found after registering device. Attempting to register push token");
registerPush(pushToken);
}
String jsonString = null;
try {
JSONObject json = new JSONObject();
json.put("device_id", credential.getDeviceID());
jsonString = json.toString();
if (callback != null) {
callback.success(jsonString);
}
} catch (JSONException ex) {
Log.e(TAG, "Error serializing credential to json");
if (callback != null) {
callback.error("Error serializing credential to json");
}
}
}
public void onFailure(String errorText) {
Log.e(TAG, "Failure registering device with Vibes Push SDK: " + errorText);
if (callback != null) {
callback.error(errorText);
}
}
};
}
private VibesListener<Void> getRegisterPushListener(final CallbackContext callback) {
return new VibesListener<Void>() {
public void onSuccess(Void credential) {
SharedPrefsManager prefsManager = new SharedPrefsManager(VibesPlugin.this.getApplicationContext());
prefsManager.saveBoolean(VibesPlugin.PUSH_REGISTERED, true);
Log.d(TAG, "Push token registration successful");
callback.success();
}
public void onFailure(String errorText) {
SharedPrefsManager prefsManager = new SharedPrefsManager(VibesPlugin.this.getApplicationContext());
prefsManager.saveBoolean(VibesPlugin.PUSH_REGISTERED, false);
Log.d(TAG, "Failure registering token with Vibes Push SDK: " + errorText);
callback.error(errorText);
}
};
}
private void registerDevice(VibesListener<Credential> listener) {
Vibes.getInstance().registerDevice(listener);
}
private void unregisterDevice(final CallbackContext callback) {
VibesListener<Void> listener = new VibesListener<Void>() {
public void onSuccess(Void credential) {
Log.d(TAG, "Unregister device successful");
SharedPrefsManager prefsManager = new SharedPrefsManager(getApplicationContext());
prefsManager.updateData(VibesPlugin.DEVICE_ID, null);
prefsManager.updateBoolean(VibesPlugin.REGISTERED, false);
callback.success();
}
public void onFailure(String errorText) {
Log.d(TAG, "Unregister device failed");
callback.error(errorText);
}
};
Vibes.getInstance().unregisterDevice(listener);
}
/**
* Registers a push token with the Vibes SDK, where the caller is not interested in success or failure callback.
*
* @param pushToken the callback to be notified of either success or failure.
*/
public static void registerPush(String pushToken) {
VibesListener<Void> listener = new VibesListener<Void>() {
public void onSuccess(Void credential) {
Log.d(TAG, "Push token registration successful");
}
public void onFailure(String errorText) {
Log.d(TAG, "Failure registering token with Vibes Push SDK: " + errorText);
}
};
registerPush(pushToken, listener);
}
/**
* Registers a push token with the Vibes SDK, with the supplied listener to handle success/failure callbacks.
*
* @param pushToken token to register with Vibes SDK
* @param listener the callback to be notified of either success or failure.
*/
public static void registerPush(String pushToken, VibesListener<Void> listener) {
Vibes.getInstance().registerPush(pushToken, listener);
}
private void unregisterPush(final CallbackContext callback) {
VibesListener<Void> listener = new VibesListener<Void>() {
public void onSuccess(Void credential) {
Log.d(TAG, "Unregister push successful");
callback.success();
}
public void onFailure(String errorText) {
Log.d(TAG, "Unregister push failed");
callback.error(errorText);
}
};
Vibes.getInstance().unregisterPush(listener);
}
private void getVibesDeviceInfo(final CallbackContext callback) {
SharedPrefsManager prefsManager = new SharedPrefsManager(getApplicationContext());
String pushToken = prefsManager.getStringData(FMS.TOKEN_KEY);
String deviceId = prefsManager.getStringData(VibesPlugin.DEVICE_ID);
Boolean pushRegistered = prefsManager.getBooleanData(VibesPlugin.PUSH_REGISTERED);
String jsonString = null;
try {
JSONObject json = new JSONObject();
json.put("device_id", deviceId);
if(pushRegistered){
json.put("push_token", pushToken);
}
jsonString = json.toString();
callback.success(jsonString);
} catch (JSONException ex) {
Log.e(TAG, "Error serializing device info to json");
callback.error("Error serializing device info to json");
}
}
private void getPerson(VibesListener<Person> listener) {
Vibes.getInstance().getPerson(listener);
}
private void associatePerson(String externalPersonId, VibesListener<Void> listener) {
Vibes.getInstance().associatePerson(externalPersonId, listener);
}
/**
* Callback that notifies the app when a push notification is received with the payload in the notification.
* On first attempt, the callback is stored in static variable and all previously received notification stored
* in the stack prior to registering for this callback are sent.
* <p>
* Subsequently, each new notification is immediately sent to the app.
*/
private void onNotificationOpened(final CallbackContext callbackContext) {
VibesPlugin.notificationCallbackContext = callbackContext;
if (VibesPlugin.notificationStack != null) {
for (Bundle bundle : VibesPlugin.notificationStack) {
VibesPlugin.notifyCallback(bundle, this.cordova.getActivity().getApplicationContext());
}
VibesPlugin.notificationStack.clear();
}
}
/**
* Performs the actual sending of notification payload through the static notificationCallbackContext
*/
public static void notifyCallback(Bundle bundle, Context context) {
Log.d(TAG, "notifyCallback invoked. Attempting to read and send notification payload");
if (!VibesPlugin.hasNotificationsCallback()) {
String packageName = context.getPackageName();
if (VibesPlugin.notificationStack == null) {
VibesPlugin.notificationStack = new ArrayList<Bundle>();
}
notificationStack.add(bundle);
return;
}
VibesPlugin.notifyCallback((Map<String, String>) bundle.get(Vibes.VIBES_REMOTE_MESSAGE_DATA));
}
public static void notifyCallback(Map<String, String> data) {
final CallbackContext callbackContext = VibesPlugin.notificationCallbackContext;
if (callbackContext != null && data != null) {
String jsonString = null;
JSONObject json = new JSONObject();
try {
for (Map.Entry<String, String> entry : data.entrySet()) {
if (entry.getKey().equals("client_app_data")) {
json.put(entry.getKey(), new JSONObject(entry.getValue()));
} else if (entry.getKey().equals("client_custom_data")) {
json.put(entry.getKey(), new JSONObject(entry.getValue()));
} else {
json.put(entry.getKey(), entry.getValue());
}
}
jsonString = json.toString();
PluginResult pluginresult = new PluginResult(PluginResult.Status.OK, jsonString);
pluginresult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginresult);
} catch (Exception e) {
Log.e(TAG, "Failure converting push message payload to json");
}
}
}
private static boolean hasNotificationsCallback() {
return VibesPlugin.notificationCallbackContext != null;
}
private void fetchInboxMessages(VibesListener<Collection<InboxMessage>> listener) {
Vibes.getInstance().fetchInboxMessages(listener);
}
private void expireInboxMessage(String messageId, Date date, VibesListener<InboxMessage> listener) {
Vibes.getInstance().expireInboxMessage(messageId, date, listener);
}
private void markInboxMessageAsRead(String messageId, VibesListener<InboxMessage> listener) {
Vibes.getInstance().markInboxMessageAsRead(messageId, listener);
}
private void fetchInboxMessage(String messageId, VibesListener<InboxMessage> listener) {
Vibes.getInstance().fetchInboxMessage(messageId, listener);
}
}
| 44.141805 | 124 | 0.596562 |
ba7ae6f200b1a53beea8c2613eae9e32264a4034 | 635 | /** The aim of this program is to get the smallest number in a sorted integer array.
* Due to this, the first number found in the array will be the smallest.
*/
public class SmallestElementSortedArray {
/**
* @param arr is the array defined
* @return the first element on the array
*/
public static int findSmallestElement(int arr[]){
return arr[0];
}
public static void main(String args[]) {
int array[] = {5, 32, 491, 1001, 45612};
int smallest = findSmallestElement(array);
System.out.println ("This is the smallest number in the array: " + smallest);
}
}
| 28.863636 | 85 | 0.640945 |
1a179fb456bce85f8e7002a87ab74c03e6575c4b | 759 | package i.collection;
import java.util.AbstractMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CreateMapBefore9A {
public static void main(String[] args) {
Map<String, String> map = Stream.of(new String[][] {{"x", "1"}, {"y", "2"}}).collect(Collectors.toMap(data->data[0], data->data[1]));
System.out.println(map.getClass());
System.out.println(map);
Map<String, Integer> map2 = Stream.of(new AbstractMap.SimpleEntry<String, Integer>("idea", 1), new AbstractMap.SimpleEntry<String, Integer>("stuff", 2)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(map2.getClass());
System.out.println(map2);
}
}
| 36.142857 | 227 | 0.677207 |
76c75f9ca6524ec14a6908ffbc35151e95e0fa21 | 11,014 | /* Copyright 2002-2021 CS GROUP
* Licensed to CS GROUP (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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.orekit.frames;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.hipparchus.Field;
import org.hipparchus.CalculusFieldElement;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.FieldAbsoluteDate;
import org.orekit.utils.AngularDerivativesFilter;
import org.orekit.utils.CartesianDerivativesFilter;
import org.orekit.utils.GenericTimeStampedCache;
/** Transform provider using thread-safe interpolation on transforms sample.
* <p>
* The interpolation is a polynomial Hermite interpolation, which
* can either use or ignore the derivatives provided by the raw
* provider. This means that simple raw providers that do not compute
* derivatives can be used, the derivatives will be added appropriately
* by the interpolation process.
* </p>
* @see GenericTimeStampedCache
* @see ShiftingTransformProvider
* @author Luc Maisonobe
*/
public class InterpolatingTransformProvider implements TransformProvider {
/** Serializable UID. */
private static final long serialVersionUID = 20140723L;
/** Provider for raw (non-interpolated) transforms. */
private final TransformProvider rawProvider;
/** Filter for Cartesian derivatives to use in interpolation. */
private final CartesianDerivativesFilter cFilter;
/** Filter for angular derivatives to use in interpolation. */
private final AngularDerivativesFilter aFilter;
/** Grid points time step. */
private final double step;
/** Cache for sample points. */
private final transient GenericTimeStampedCache<Transform> cache;
/** Field caches for sample points. */
// we use Object as the value of fieldCaches because despite numerous attempts,
// we could not find a way to use GenericTimeStampedCache<FieldTransform<? extends CalculusFieldElement<?>>
// without the compiler complaining
private final transient Map<Field<? extends CalculusFieldElement<?>>, Object> fieldCaches;
/** Simple constructor.
* @param rawProvider provider for raw (non-interpolated) transforms
* @param cFilter filter for derivatives from the sample to use in interpolation
* @param aFilter filter for derivatives from the sample to use in interpolation
* @param gridPoints number of interpolation grid points
* @param step grid points time step
* @param maxSlots maximum number of independent cached time slots
* in the {@link GenericTimeStampedCache time-stamped cache}
* @param maxSpan maximum duration span in seconds of one slot
* in the {@link GenericTimeStampedCache time-stamped cache}
* @param newSlotInterval time interval above which a new slot is created
* in the {@link GenericTimeStampedCache time-stamped cache}
* @since 9.1
*/
public InterpolatingTransformProvider(final TransformProvider rawProvider,
final CartesianDerivativesFilter cFilter,
final AngularDerivativesFilter aFilter,
final int gridPoints, final double step,
final int maxSlots, final double maxSpan, final double newSlotInterval) {
this.rawProvider = rawProvider;
this.cFilter = cFilter;
this.aFilter = aFilter;
this.step = step;
this.cache = new GenericTimeStampedCache<Transform>(gridPoints, maxSlots, maxSpan, newSlotInterval,
new TransformGenerator(gridPoints,
rawProvider,
step));
this.fieldCaches = new HashMap<>();
}
/** Get the underlying provider for raw (non-interpolated) transforms.
* @return provider for raw (non-interpolated) transforms
*/
public TransformProvider getRawProvider() {
return rawProvider;
}
/** Get the number of interpolation grid points.
* @return number of interpolation grid points
*/
public int getGridPoints() {
return cache.getNeighborsSize();
}
/** Get the grid points time step.
* @return grid points time step
*/
public double getStep() {
return step;
}
/** {@inheritDoc} */
@Override
public Transform getTransform(final AbsoluteDate date) {
// retrieve a sample from the thread-safe cache
final List<Transform> sample = cache.getNeighbors(date).collect(Collectors.toList());
// interpolate to specified date
return Transform.interpolate(date, cFilter, aFilter, sample);
}
/** {@inheritDoc} */
@Override
public <T extends CalculusFieldElement<T>> FieldTransform<T> getTransform(final FieldAbsoluteDate<T> date) {
@SuppressWarnings("unchecked")
GenericTimeStampedCache<FieldTransform<T>> fieldCache =
(GenericTimeStampedCache<FieldTransform<T>>) fieldCaches.get(date.getField());
if (fieldCache == null) {
fieldCache =
new GenericTimeStampedCache<FieldTransform<T>>(cache.getNeighborsSize(),
cache.getMaxSlots(),
cache.getMaxSpan(),
cache.getNewSlotQuantumGap(),
new FieldTransformGenerator<>(date.getField(),
cache.getNeighborsSize(),
rawProvider,
step));
fieldCaches.put(date.getField(), fieldCache);
}
// retrieve a sample from the thread-safe cache
final Stream<FieldTransform<T>> sample = fieldCache.getNeighbors(date.toAbsoluteDate());
// interpolate to specified date
return FieldTransform.interpolate(date, cFilter, aFilter, sample);
}
/** Replace the instance with a data transfer object for serialization.
* <p>
* This intermediate class serializes only the data needed for generation,
* but does <em>not</em> serializes the cache itself (in fact the cache is
* not serializable).
* </p>
* @return data transfer object that will be serialized
*/
private Object writeReplace() {
return new DTO(rawProvider, cFilter.getMaxOrder(), aFilter.getMaxOrder(),
cache.getNeighborsSize(), step,
cache.getMaxSlots(), cache.getMaxSpan(), cache.getNewSlotQuantumGap());
}
/** Internal class used only for serialization. */
private static class DTO implements Serializable {
/** Serializable UID. */
private static final long serialVersionUID = 20170823L;
/** Provider for raw (non-interpolated) transforms. */
private final TransformProvider rawProvider;
/** Cartesian derivatives to use in interpolation. */
private final int cDerivatives;
/** Angular derivatives to use in interpolation. */
private final int aDerivatives;
/** Number of grid points. */
private final int gridPoints;
/** Grid points time step. */
private final double step;
/** Maximum number of independent cached time slots. */
private final int maxSlots;
/** Maximum duration span in seconds of one slot. */
private final double maxSpan;
/** Time interval above which a new slot is created. */
private final double newSlotInterval;
/** Simple constructor.
* @param rawProvider provider for raw (non-interpolated) transforms
* @param cDerivatives derivation order for Cartesian coordinates
* @param aDerivatives derivation order for angular coordinates
* @param gridPoints number of interpolation grid points
* @param step grid points time step
* @param maxSlots maximum number of independent cached time slots
* in the {@link GenericTimeStampedCache time-stamped cache}
* @param maxSpan maximum duration span in seconds of one slot
* in the {@link GenericTimeStampedCache time-stamped cache}
* @param newSlotInterval time interval above which a new slot is created
* in the {@link GenericTimeStampedCache time-stamped cache}
*/
private DTO(final TransformProvider rawProvider, final int cDerivatives, final int aDerivatives,
final int gridPoints, final double step,
final int maxSlots, final double maxSpan, final double newSlotInterval) {
this.rawProvider = rawProvider;
this.cDerivatives = cDerivatives;
this.aDerivatives = aDerivatives;
this.gridPoints = gridPoints;
this.step = step;
this.maxSlots = maxSlots;
this.maxSpan = maxSpan;
this.newSlotInterval = newSlotInterval;
}
/** Replace the deserialized data transfer object with a {@link InterpolatingTransformProvider}.
* @return replacement {@link InterpolatingTransformProvider}
*/
private Object readResolve() {
// build a new provider, with an empty cache
return new InterpolatingTransformProvider(rawProvider,
CartesianDerivativesFilter.getFilter(cDerivatives),
AngularDerivativesFilter.getFilter(aDerivatives),
gridPoints, step,
maxSlots, maxSpan, newSlotInterval);
}
}
}
| 44.955102 | 118 | 0.62357 |
7fa62095c1cc35e62676b7865778dbcd90045d3e | 5,889 | /*
* Copyright 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* 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.processors.query.h2.opt;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.binary.BinaryObjectImpl;
import org.apache.ignite.internal.processors.cache.CacheObject;
import org.apache.ignite.internal.processors.cache.CacheObjectValueContext;
import org.apache.ignite.internal.processors.query.h2.H2Utils;
import org.h2.message.DbException;
import org.h2.util.Bits;
import org.h2.util.JdbcUtils;
import org.h2.util.Utils;
import org.h2.value.CompareMode;
import org.h2.value.TypeInfo;
import org.h2.value.Value;
import org.h2.value.ValueJavaObject;
/**
* H2 Value over {@link CacheObject}. Replacement for {@link ValueJavaObject}.
*/
public class GridH2ValueCacheObject extends Value {
/** */
private CacheObject obj;
/** Object value context. */
private CacheObjectValueContext valCtx;
/**
* Constructor.
*
* @param obj Object.
* @param valCtx Object value context.
*/
public GridH2ValueCacheObject(CacheObject obj, CacheObjectValueContext valCtx) {
assert obj != null;
if (obj instanceof BinaryObjectImpl) {
((BinaryObjectImpl)obj).detachAllowed(true);
obj = ((BinaryObjectImpl)obj).detach();
}
this.obj = obj;
this.valCtx = valCtx;
}
/**
* @return Cache object.
*/
public CacheObject getCacheObject() {
return obj;
}
/**
* @return Value context.
*/
public CacheObjectValueContext valueContext() {
return valCtx;
}
/** {@inheritDoc} */
@Override public String getSQL() {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public StringBuilder getSQL(StringBuilder sb) {
throw new UnsupportedOperationException();
}
/** {@inheritDoc} */
@Override public TypeInfo getType() {
return TypeInfo.TYPE_JAVA_OBJECT;
}
/** {@inheritDoc} */
@Override public int getValueType() {
return Value.JAVA_OBJECT;
}
/** {@inheritDoc} */
@Override public String getString() {
return getObject().toString();
}
/** {@inheritDoc} */
@Override public byte[] getBytes() {
return Utils.cloneByteArray(getBytesNoCopy());
}
/** {@inheritDoc} */
@Override public byte[] getBytesNoCopy() {
if (obj.cacheObjectType() == CacheObject.TYPE_REGULAR) {
// Result must be the same as `marshaller.marshall(obj.value(coctx, false));`
try {
return obj.valueBytes(valCtx);
}
catch (IgniteCheckedException e) {
throw DbException.convert(e);
}
}
// For user-provided and array types.
return JdbcUtils.serialize(obj, H2Utils.getHandler(valCtx.kernalContext()));
}
/** {@inheritDoc} */
@Override public Object getObject() {
return getObject(false);
}
/**
* @param cpy Copy flag.
* @return Value.
*/
public Object getObject(boolean cpy) {
return obj.isPlatformType() ? obj.value(valCtx, cpy) : obj;
}
/** {@inheritDoc} */
@Override public void set(PreparedStatement prep, int parameterIndex) throws SQLException {
prep.setObject(parameterIndex, getObject(), Types.JAVA_OBJECT);
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public int compareTypeSafe(Value v, CompareMode mode) {
Object o1 = getObject();
Object o2 = v.getObject();
boolean o1Comparable = o1 instanceof Comparable;
boolean o2Comparable = o2 instanceof Comparable;
if (o1Comparable && o2Comparable &&
Utils.haveCommonComparableSuperclass(o1.getClass(), o2.getClass())) {
Comparable<Object> c1 = (Comparable<Object>)o1;
return c1.compareTo(o2);
}
// Group by types.
if (o1.getClass() != o2.getClass()) {
if (o1Comparable != o2Comparable)
return o1Comparable ? -1 : 1;
return o1.getClass().getName().compareTo(o2.getClass().getName());
}
// Compare hash codes.
int h1 = hashCode();
int h2 = v.hashCode();
if (h1 == h2) {
if (o1.equals(o2))
return 0;
return Bits.compareNotNullSigned(getBytesNoCopy(), v.getBytesNoCopy());
}
return h1 > h2 ? 1 : -1;
}
/** {@inheritDoc} */
@Override public int hashCode() {
return getObject().hashCode();
}
/** {@inheritDoc} */
@Override public boolean equals(Object other) {
if (!(other instanceof Value))
return false;
Value otherVal = (Value)other;
return otherVal.getType().getValueType() == Value.JAVA_OBJECT
&& getObject().equals(otherVal.getObject());
}
/** {@inheritDoc} */
@Override public Value convertPrecision(long precision, boolean force) {
return this;
}
/** {@inheritDoc} */
@Override public int getMemory() {
return 0;
}
}
| 28.587379 | 102 | 0.627441 |
7384a437fac7174f2f107691195ef1a92c9b9c3b | 363 | package com.daylight.devleague.exceptions.user.login;
import com.daylight.devleague.exceptions.BusinessException;
public class NotLoggedUserException extends BusinessException {
private static final long serialVersionUID = -2103196187968478192L;
public NotLoggedUserException() {
super("not_logged_user", "There was not logged user");
}
}
| 25.928571 | 69 | 0.779614 |
3860fa5442b36b62a872a4a4d3d6ec2b9eb71970 | 862 | package scmemory;
import org.junit.jupiter.api.Test;
import org.ostis.scmemory.model.element.link.LinkType;
import org.ostis.scmemory.websocketmemory.memory.element.ScLinkBinaryImpl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Michael
* @since 0.6.2
*/
public class ScLInkBinaryImplTest {
@Test
void getContentFromEmptyLink() throws IOException {
String expected = new ByteArrayOutputStream().toString();
String content = null;
ScLinkBinaryImpl link = new ScLinkBinaryImpl(
LinkType.LINK,
33L);
link.setContent(content);
String actual = link.getContent()
.toString();
assertEquals(
actual,
expected);
}
}
| 26.121212 | 74 | 0.650812 |
f2a6f415f50267c31ce17b9fca13f33a9cf2475f | 1,525 | package com.ceosilvajr.app.onlineshoppingcart.manager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import com.ceosilvajr.app.onlineshoppingcart.R;
import com.ceosilvajr.app.onlineshoppingcart.objects.User;
import com.google.gson.Gson;
/**
* Created by ceosilvajr on 8/3/15.
*/
public class UserManager {
private static final String USER = "user";
public static User get(Context context) {
Gson gson = new Gson();
Resources res = context.getResources();
SharedPreferences myPrefs = context.getSharedPreferences(
res.getString(R.string.package_name), 0);
String json = myPrefs.getString(USER, "");
return gson.fromJson(json, User.class);
}
public static void save(User user, Context context) {
Gson gson = new Gson();
Resources res = context.getResources();
SharedPreferences myPrefs = context.getSharedPreferences(
res.getString(R.string.package_name), 0);
SharedPreferences.Editor e = myPrefs.edit();
String json = gson.toJson(user);
e.putString(USER, json);
e.apply();
}
public static void delete(Context context) {
Resources res = context.getResources();
SharedPreferences myPrefs = context.getSharedPreferences(
res.getString(R.string.package_name), 0);
SharedPreferences.Editor e = myPrefs.edit();
e.remove(USER);
e.apply();
}
}
| 30.5 | 65 | 0.666885 |
3c3a6d359e8f94915f9990220e28eec7ba69e007 | 2,030 | package com.uzm.common.reflections.acessors;
import java.lang.reflect.Method;
/**
* Essa classe representa um {@link Method} com métodos seguros de acesso.
*
* @author Maxteer
*/
public class MethodAccessor {
private Method handle;
public MethodAccessor(Method method) {
this(method, false);
}
public MethodAccessor(Method method, boolean forceAccess) {
this.handle = method;
if (forceAccess) {
method.setAccessible(true);
}
}
/**
* Método utilizado para invocar um {@link Method}
*
* @param target A instância para utilizar o método.
* @param args Os parâmetros para invocar o método.
* @return Resultado do método.
*/
public Object invoke(Object target, Object... args) {
try {
return handle.invoke(target, args);
} catch (ReflectiveOperationException ex) {
throw new RuntimeException("Cannot invoke method.", ex);
}
}
/**
* Método utilizado para verificar se a classe do Objeto possui o {@link Method}.
*
* @param target O alvo para verificar.
* @return TRUE caso possua o método na classe, FALSE caso não.
*/
public boolean hasMethod(Object target) {
return target != null && this.handle.getDeclaringClass().equals(target.getClass());
}
/**
* @return O {@link Method} representado nesse Accessor.
*/
public Method getHandle() {
return handle;
}
@Override
public String toString() {
return "MethodAccessor[class=" + this.handle.getDeclaringClass().getName() + ", name=" + this.handle.getName() + ", params=" + this.handle.getParameterTypes().toString() + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj instanceof MethodAccessor) {
MethodAccessor other = (MethodAccessor) obj;
if (other.handle.equals(handle)) {
return true;
}
}
return false;
}
@Override
public int hashCode() {
return this.handle.hashCode();
}
} | 23.882353 | 180 | 0.646305 |
73df8986692c3567a605cf3541d8a0dd2a36b7dc | 1,139 | package io.entraos.idun.rec.floor;
import io.entraos.idun.commands.IdunGetCommand;
import io.entraos.rec.domain.Floor;
import io.entraos.rec.mappers.FloorJsonMapper;
import java.net.URI;
import java.net.http.HttpResponse;
public class GetFloorCommand extends IdunGetCommand {
private final String accessToken;
private final String floorUuid;
public GetFloorCommand(URI baseURI, String accessToken, String floorUuid) {
super(baseURI,"Sensors");
this.accessToken = accessToken;
this.floorUuid = floorUuid;
}
@Override
protected URI buildUri() {
String fullUrl = getBaseUri().toString() + "json/storey/" + floorUuid;
URI fullUri = URI.create(fullUrl);
return fullUri;
}
@Override
protected String buildAuthorization() {
return "Bearer " + accessToken;
}
public Floor getFloor() {
String json = null;
HttpResponse<String> response = run();
json = response.body();
Floor floor = null;
if (json != null) {
floor = FloorJsonMapper.fromJson(json);
}
return floor;
}
}
| 26.488372 | 79 | 0.651449 |
bc8617e6764151d11e256b0854fa1e01a219c6a1 | 182 | package com.ztiany.loadmore.adapter;
public interface LoadMoreView {
void onLoading();
void onFail();
void onCompleted(boolean hasMore);
void onClickLoad();
}
| 12.133333 | 38 | 0.686813 |
ca5f2bd6c8fa3ea6613fd9e79b68af80719b5d23 | 2,182 | package br.com.zupacademy.proposta.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.validation.Valid;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import com.sun.istack.NotNull;
import br.com.zupacademy.proposta.enums.TipoCarteiraDigital;
@Entity
public class CarteiraDigital {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Email
@NotBlank
@Column(nullable = false)
private String email;
@NotNull
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private TipoCarteiraDigital tipoCarteiraDigital;
@NotNull
@Valid
@ManyToOne(optional = false)
@JoinColumn(name = "cartao_id", nullable = false)
private Cartao cartao;
@Deprecated
public CarteiraDigital() {
}
public CarteiraDigital(@Email @NotBlank String email, @NotNull TipoCarteiraDigital tipoCarteiraDigital,
@NotNull @Valid Cartao cartao) {
this.email = email;
this.tipoCarteiraDigital = tipoCarteiraDigital;
this.cartao = cartao;
}
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
public TipoCarteiraDigital getTipoCarteiraDigital() {
return tipoCarteiraDigital;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((tipoCarteiraDigital == null) ? 0 : tipoCarteiraDigital.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarteiraDigital other = (CarteiraDigital) obj;
if (tipoCarteiraDigital != other.tipoCarteiraDigital)
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
return true;
}
}
| 22.968421 | 104 | 0.74198 |
fafd536d2f65b6ce73f77c87ed7089d05ea26d31 | 2,172 | /* ###
* IP: GHIDRA
*
* 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 ghidra.util.search.memory;
import java.util.Objects;
import ghidra.program.model.address.Address;
import ghidra.util.SystemUtilities;
/**
* A class that represents a memory search hit at an address.
*/
public class MemSearchResult implements Comparable<MemSearchResult> {
private Address address;
private int length;
public MemSearchResult(Address address, int length) {
this.address = Objects.requireNonNull(address);
if (length <= 0) {
throw new IllegalArgumentException("Length must be greater than 0");
}
this.length = length;
}
public Address getAddress() {
return address;
}
public int getLength() {
return length;
}
@Override
public int compareTo(MemSearchResult o) {
return address.compareTo(o.address);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MemSearchResult other = (MemSearchResult) obj;
return SystemUtilities.isEqual(address, other.address);
}
@Override
public String toString() {
return address.toString();
}
/**
* Returns true if the given address equals the address of this search result
* @param a the other address
* @return true if the given address equals the address of this search result
*/
public boolean addressEquals(Address a) {
return address.equals(a);
}
}
| 23.868132 | 80 | 0.706722 |
29590442b85cef64c0f043cd974fbf6416f72683 | 1,651 | package tech.wetech.admin.modules.system.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.wetech.admin.modules.base.service.impl.BaseService;
import tech.wetech.admin.modules.system.mapper.RoleMapper;
import tech.wetech.admin.modules.system.po.Role;
import tech.wetech.admin.modules.system.service.ResourceService;
import tech.wetech.admin.modules.system.service.RoleService;
import tk.mybatis.mapper.weekend.Weekend;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class RoleServiceImpl extends BaseService<Role> implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Autowired
private ResourceService resourceService;
@Override
public Set<String> queryRoles(Long... roleIds) {
Set<String> roles = new HashSet<>();
for (Long roleId : roleIds) {
Role role = roleMapper.selectByPrimaryKey(roleId);
if (role != null) {
roles.add(role.getRole());
}
}
return roles;
}
@Override
public Set<String> queryPermissions(Long[] roleIds) {
Weekend<Role> weekend = Weekend.of(Role.class);
weekend.weekendCriteria().andIn(Role::getId, Arrays.asList(roleIds));
return resourceService.queryPermissions(
roleMapper.selectByExample(weekend).stream().flatMap(r ->
Arrays.asList(r.getResourceIds().split(",")).stream()
).map(Long::valueOf).collect(Collectors.toSet())
);
}
}
| 33.693878 | 79 | 0.692308 |
c4e9b7ef2a17a4dd018e93289cdc8861d31e3047 | 362 | package de.maibornwolff.ste.testVille.inputFileParsing.common;
import java.util.concurrent.atomic.AtomicInteger;
public class IDGenerator {
private AtomicInteger keyCentral;
public IDGenerator() {
this.keyCentral = new AtomicInteger(1);
}
public int generateNextUniqueKey() {
return this.keyCentral.getAndIncrement();
}
} | 22.625 | 62 | 0.726519 |
fb7560778db40edd04ec0b986ed75009bac90c2d | 9,370 | package com.hedera.services.bdd.spec.transactions.schedule;
/*-
*
* Hedera Services Test Clients
*
* Copyright (C) 2018 - 2021 Hedera Hashgraph, 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 com.google.common.base.MoreObjects;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.hedera.services.bdd.spec.HapiApiSpec;
import com.hedera.services.bdd.spec.HapiSpecSetup;
import com.hedera.services.bdd.spec.fees.FeeCalculator;
import com.hedera.services.bdd.spec.transactions.HapiTxnOp;
import com.hedera.services.bdd.spec.transactions.TxnUtils;
import com.hedera.services.bdd.suites.schedule.ScheduleUtils;
import com.hederahashgraph.api.proto.java.HederaFunctionality;
import com.hederahashgraph.api.proto.java.Key;
import com.hederahashgraph.api.proto.java.KeyList;
import com.hederahashgraph.api.proto.java.SchedulableTransactionBody;
import com.hederahashgraph.api.proto.java.ScheduleCreateTransactionBody;
import com.hederahashgraph.api.proto.java.Transaction;
import com.hederahashgraph.api.proto.java.TransactionBody;
import com.hederahashgraph.api.proto.java.TransactionResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import static com.hedera.services.bdd.spec.HapiPropertySource.asScheduleString;
import static com.hedera.services.bdd.spec.transactions.TxnFactory.bannerWith;
import static com.hedera.services.bdd.spec.transactions.TxnUtils.suFrom;
import static com.hederahashgraph.api.proto.java.HederaFunctionality.ScheduleCreate;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.SUCCESS;
public class HapiScheduleCreate<T extends HapiTxnOp<T>> extends HapiTxnOp<HapiScheduleCreate<T>> {
private static final Logger log = LogManager.getLogger(HapiScheduleCreate.class);
private static final int defaultScheduleTxnExpiry = HapiSpecSetup.getDefaultNodeProps()
.getInteger("ledger.schedule.txExpiryTimeSecs");
private boolean advertiseCreation = false;
private boolean recordScheduledTxn = false;
private boolean skipRegistryUpdate = false;
private boolean scheduleNoFunction = false;
private boolean saveExpectedScheduledTxnId = false;
private boolean useSentinelKeyListForAdminKey = false;
private ByteString bytesSigned = ByteString.EMPTY;
private List<String> initialSigners = Collections.emptyList();
private Optional<String> adminKey = Optional.empty();
private Optional<String> payerAccountID = Optional.empty();
private Optional<String> entityMemo = Optional.empty();
private Optional<BiConsumer<String, byte[]>> successCb = Optional.empty();
private AtomicReference<SchedulableTransactionBody> scheduledTxn = new AtomicReference<>();
private final String scheduleEntity;
private final HapiTxnOp<T> scheduled;
public HapiScheduleCreate(String scheduled, HapiTxnOp<T> txn) {
this.scheduleEntity = scheduled;
this.scheduled = txn
.withLegacyProtoStructure()
.sansTxnId()
.sansNodeAccount()
.signedBy();
}
public HapiScheduleCreate<T> advertisingCreation() {
advertiseCreation = true;
return this;
}
public HapiScheduleCreate<T> savingExpectedScheduledTxnId() {
saveExpectedScheduledTxnId = true;
return this;
}
public HapiScheduleCreate<T> recordingScheduledTxn() {
recordScheduledTxn = true;
return this;
}
public HapiScheduleCreate<T> rememberingNothing() {
skipRegistryUpdate = true;
return this;
}
public HapiScheduleCreate<T> functionless() {
scheduleNoFunction = true;
return this;
}
public HapiScheduleCreate<T> adminKey(String s) {
adminKey = Optional.of(s);
return this;
}
public HapiScheduleCreate<T> usingSentinelKeyListForAdminKey() {
useSentinelKeyListForAdminKey = true;
return this;
}
public HapiScheduleCreate<T> exposingSuccessTo(BiConsumer<String, byte[]> cb) {
successCb = Optional.of(cb);
return this;
}
public HapiScheduleCreate<T> designatingPayer(String s) {
payerAccountID = Optional.of(s);
return this;
}
public HapiScheduleCreate<T> alsoSigningWith(String... s) {
initialSigners = List.of(s);
return this;
}
public HapiScheduleCreate<T> withEntityMemo(String entityMemo) {
this.entityMemo = Optional.of(entityMemo);
return this;
}
@Override
protected HapiScheduleCreate<T> self() {
return this;
}
@Override
public HederaFunctionality type() {
return ScheduleCreate;
}
@Override
protected Consumer<TransactionBody.Builder> opBodyDef(HapiApiSpec spec) throws Throwable {
var subOp = scheduled.signedTxnFor(spec);
ScheduleCreateTransactionBody opBody = spec
.txns()
.<ScheduleCreateTransactionBody, ScheduleCreateTransactionBody.Builder>body(
ScheduleCreateTransactionBody.class, b -> {
if (scheduleNoFunction) {
b.setScheduledTransactionBody(SchedulableTransactionBody.getDefaultInstance());
} else {
try {
var deserializedTxn = TransactionBody.parseFrom(subOp.getBodyBytes());
scheduledTxn.set(ScheduleUtils.fromOrdinary(deserializedTxn));
b.setScheduledTransactionBody(scheduledTxn.get());
} catch (InvalidProtocolBufferException fatal) {
throw new IllegalStateException("Couldn't deserialize serialized TransactionBody!");
}
}
if (useSentinelKeyListForAdminKey) {
b.setAdminKey(Key.newBuilder().setKeyList(KeyList.getDefaultInstance()));
} else {
adminKey.ifPresent(k -> b.setAdminKey(spec.registry().getKey(k)));
}
entityMemo.ifPresent(b::setMemo);
payerAccountID.ifPresent(a -> {
var payer = TxnUtils.asId(a, spec);
b.setPayerAccountID(payer);
});
}
);
return b -> b.setScheduleCreate(opBody);
}
@Override
protected Function<Transaction, TransactionResponse> callToUse(HapiApiSpec spec) {
return spec.clients().getScheduleSvcStub(targetNodeFor(spec), useTls)::createSchedule;
}
@Override
protected long feeFor(HapiApiSpec spec, Transaction txn, int numPayerKeys) throws Throwable {
FeeCalculator.ActivityMetrics metricsCalc = (_txn, svo) ->
scheduleOpsUsage.scheduleCreateUsage(_txn, suFrom(svo), defaultScheduleTxnExpiry);
return spec.fees().forActivityBasedOp(HederaFunctionality.ScheduleCreate, metricsCalc, txn, numPayerKeys);
}
@Override
protected MoreObjects.ToStringHelper toStringHelper() {
MoreObjects.ToStringHelper helper = super.toStringHelper()
.add("entity", scheduleEntity);
helper.add("id", createdSchedule().orElse("<N/A>"));
return helper;
}
@Override
protected void updateStateOf(HapiApiSpec spec) throws Throwable {
if (actualStatus != SUCCESS) {
return;
}
if (verboseLoggingOn) {
log.info("Created schedule '{}' as {}", scheduleEntity, createdSchedule().get());
}
successCb.ifPresent(cb -> cb.accept(
asScheduleString(lastReceipt.getScheduleID()),
bytesSigned.toByteArray()));
if (skipRegistryUpdate) {
return;
}
var registry = spec.registry();
registry.saveScheduleId(scheduleEntity, lastReceipt.getScheduleID());
registry.saveExpiry(scheduleEntity, (long) defaultScheduleTxnExpiry);
adminKey.ifPresent(k -> registry.saveAdminKey(scheduleEntity, spec.registry().getKey(k)));
if (saveExpectedScheduledTxnId) {
if (verboseLoggingOn) {
log.info("Returned receipt for scheduled txn is {}", lastReceipt.getScheduledTransactionID());
}
registry.saveTxnId(correspondingScheduledTxnId(scheduleEntity), lastReceipt.getScheduledTransactionID());
}
if (recordScheduledTxn) {
if (verboseLoggingOn) {
log.info("Created scheduled txn {}", scheduledTxn.get());
}
registry.saveScheduledTxn(scheduleEntity, scheduledTxn.get());
}
if (advertiseCreation) {
String banner = "\n\n" + bannerWith(
String.format(
"Created schedule '%s' with id '0.0.%d'.",
scheduleEntity,
lastReceipt.getScheduleID().getScheduleNum()));
log.info(banner);
}
}
public static String correspondingScheduledTxnId(String entity) {
return entity + "ScheduledTxnId";
}
@Override
protected List<Function<HapiApiSpec, Key>> defaultSigners() {
List<Function<HapiApiSpec, Key>> signers =
new ArrayList<>(List.of(spec -> spec.registry().getKey(effectivePayer(spec))));
adminKey.ifPresent(k -> signers.add(spec -> spec.registry().getKey(k)));
for (String added : initialSigners) {
signers.add(spec -> spec.registry().getKey(added));
}
return signers;
}
private Optional<String> createdSchedule() {
return Optional
.ofNullable(lastReceipt)
.map(receipt -> asScheduleString(receipt.getScheduleID()));
}
}
| 34.448529 | 108 | 0.756137 |
2ef3970299dc3c36e7f9de767bded8d996297fdc | 4,155 | /*
* Copyright 2012 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.
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
public class GenerateEGL {
private static void copy(String filename, PrintStream out) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
String s;
while ((s = br.readLine()) != null) {
out.println(s);
}
}
private static void emit(EGLCodeEmitter emitter,
BufferedReader specReader,
PrintStream glStream,
PrintStream cStream) throws Exception {
String s = null;
while ((s = specReader.readLine()) != null) {
if (s.trim().startsWith("//")) {
continue;
}
CFunc cfunc = CFunc.parseCFunc(s);
String fname = cfunc.getName();
String stubRoot = "stubs/egl/" + fname;
String javaPath = stubRoot + ".java";
File f = new File(javaPath);
if (f.exists()) {
System.out.println("Special-casing function " + fname);
copy(javaPath, glStream);
copy(stubRoot + ".cpp", cStream);
// Register native function names
// This should be improved to require fewer discrete files
String filename = stubRoot + ".nativeReg";
BufferedReader br =
new BufferedReader(new FileReader(filename));
String nfunc;
while ((nfunc = br.readLine()) != null) {
emitter.addNativeRegistration(nfunc);
}
} else {
emitter.emitCode(cfunc, s);
}
}
}
public static void main(String[] args) throws Exception {
int aidx = 0;
while ((aidx < args.length) && (args[aidx].charAt(0) == '-')) {
switch (args[aidx].charAt(1)) {
default:
System.err.println("Unknown flag: " + args[aidx]);
System.exit(1);
}
aidx++;
}
BufferedReader checksReader =
new BufferedReader(new FileReader("specs/egl/checks.spec"));
ParameterChecker checker = new ParameterChecker(checksReader);
for(String suffix: new String[] {"EGL14", "EGLExt"}) {
BufferedReader specReader = new BufferedReader(new FileReader(
"specs/egl/" + suffix + ".spec"));
String egljFilename = "android/opengl/" + suffix + ".java";
String eglcFilename = "android_opengl_" + suffix + ".cpp";
PrintStream egljStream =
new PrintStream(new FileOutputStream("out/" + egljFilename));
PrintStream eglcStream =
new PrintStream(new FileOutputStream("out/" + eglcFilename));
copy("stubs/egl/" + suffix + "Header.java-if", egljStream);
copy("stubs/egl/" + suffix + "cHeader.cpp", eglcStream);
EGLCodeEmitter emitter = new EGLCodeEmitter(
"android/opengl/" + suffix,
checker, egljStream, eglcStream);
emit(emitter, specReader, egljStream, eglcStream);
emitter.emitNativeRegistration(
"register_android_opengl_jni_" + suffix);
egljStream.println("}");
egljStream.close();
eglcStream.close();
}
}
}
| 37.772727 | 83 | 0.567268 |
3e010e904c5ad747338dd6cd72aab5b5b5c84983 | 820 | package org.omg.hw.HW_vpnManager;
/**
* Generated from IDL definition of alias "IPCrossConnectionList_T"
* @author JacORB IDL compiler
*/
public final class IPCrossConnectionList_THolder
implements org.omg.CORBA.portable.Streamable
{
public org.omg.hw.HW_vpnManager.IPCrossConnection_T[] value;
public IPCrossConnectionList_THolder ()
{
}
public IPCrossConnectionList_THolder (final org.omg.hw.HW_vpnManager.IPCrossConnection_T[] initial)
{
value = initial;
}
public org.omg.CORBA.TypeCode _type ()
{
return IPCrossConnectionList_THelper.type ();
}
public void _read (final org.omg.CORBA.portable.InputStream in)
{
value = IPCrossConnectionList_THelper.read (in);
}
public void _write (final org.omg.CORBA.portable.OutputStream out)
{
IPCrossConnectionList_THelper.write (out,value);
}
}
| 24.848485 | 100 | 0.773171 |
844b6af3d15126d867d74b61ab77d8f55ac7f980 | 8,320 | package org.wikidata.wdtk.client;
/*
* #%L
* Wikidata Toolkit Command-line Tool
* %%
* Copyright (C) 2014 Wikidata Toolkit Developers
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.wikidata.wdtk.datamodel.helpers.Datamodel;
import org.wikidata.wdtk.datamodel.interfaces.DatatypeIdValue;
import org.wikidata.wdtk.datamodel.interfaces.EntityDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemDocument;
import org.wikidata.wdtk.datamodel.interfaces.ItemIdValue;
import org.wikidata.wdtk.datamodel.interfaces.MonolingualTextValue;
import org.wikidata.wdtk.datamodel.interfaces.PropertyDocument;
import org.wikidata.wdtk.datamodel.interfaces.SiteLink;
import org.wikidata.wdtk.datamodel.interfaces.StatementGroup;
import org.wikidata.wdtk.datamodel.json.jackson.JacksonTermedStatementDocument;
import org.wikidata.wdtk.testing.MockDirectoryManager;
import org.wikidata.wdtk.util.CompressionType;
import org.wikidata.wdtk.util.DirectoryManagerFactory;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
public class JsonSerializationActionTest {
@Test
public void testDefaults() {
String[] args = new String[] { "-a", "json" };
DumpProcessingOutputAction action = DumpProcessingOutputActionTest
.getActionFromArgs(args);
assertTrue(action instanceof JsonSerializationAction);
assertFalse(action.needsSites());
assertTrue(action.isReady());
assertEquals(action.getActionName(), "JsonSerializationAction");
}
@Test
public void testJsonOutput() throws IOException {
String[] args = new String[] { "-a", "json", "-o",
"/path/to/output.json" };
DirectoryManagerFactory
.setDirectoryManagerClass(MockDirectoryManager.class);
ClientConfiguration config = new ClientConfiguration(args);
JsonSerializationAction jsa = (JsonSerializationAction) config
.getActions().get(0);
ItemIdValue subject1 = Datamodel.makeWikidataItemIdValue("Q42");
ItemIdValue subject2 = Datamodel.makeWikidataItemIdValue("Q43");
MonolingualTextValue mtv1 = Datamodel.makeMonolingualTextValue("Test1",
"en");
MonolingualTextValue mtv2 = Datamodel.makeMonolingualTextValue("Test2",
"fr");
ItemDocument id1 = Datamodel.makeItemDocument(subject1,
Arrays.asList(mtv1, mtv2), Arrays.asList(mtv1),
Collections.<MonolingualTextValue> emptyList(),
Collections.<StatementGroup> emptyList(),
Collections.<String, SiteLink> emptyMap());
ItemDocument id2 = Datamodel.makeItemDocument(subject2,
Collections.<MonolingualTextValue> emptyList(),
Arrays.asList(mtv2),
Collections.<MonolingualTextValue> emptyList(),
Collections.<StatementGroup> emptyList(),
Collections.<String, SiteLink> emptyMap());
PropertyDocument pd1 = Datamodel
.makePropertyDocument(
Datamodel.makeWikidataPropertyIdValue("P31"),
Arrays.asList(mtv1),
Collections.<MonolingualTextValue> emptyList(),
Arrays.asList(mtv1),
Datamodel
.makeDatatypeIdValue(DatatypeIdValue.DT_MONOLINGUAL_TEXT));
jsa.open();
jsa.processItemDocument(id1);
jsa.processPropertyDocument(pd1);
jsa.processItemDocument(id2);
jsa.close();
MockDirectoryManager mdm = new MockDirectoryManager(
Paths.get("/path/to/"), false);
ObjectMapper mapper = new ObjectMapper();
ObjectReader documentReader = mapper
.reader(JacksonTermedStatementDocument.class);
MappingIterator<JacksonTermedStatementDocument> documentIterator = documentReader
.readValues(mdm.getInputStreamForFile("output.json",
CompressionType.NONE));
List<EntityDocument> results = new ArrayList<>();
while (documentIterator.hasNextValue()) {
JacksonTermedStatementDocument document = documentIterator
.nextValue();
document.setSiteIri(Datamodel.SITE_WIKIDATA);
results.add(document);
}
documentIterator.close();
assertEquals(3, results.size());
assertEquals(id1, results.get(0));
assertEquals(pd1, results.get(1));
assertEquals(id2, results.get(2));
}
@Test
public void testJsonGzipOutput() throws IOException {
String[] args = new String[] { "-a", "json", "-o",
"/path/to/output.json", "-z", "gz" };
DirectoryManagerFactory
.setDirectoryManagerClass(MockDirectoryManager.class);
ClientConfiguration config = new ClientConfiguration(args);
JsonSerializationAction jsa = (JsonSerializationAction) config
.getActions().get(0);
ItemIdValue subject1 = Datamodel.makeWikidataItemIdValue("Q42");
MonolingualTextValue mtv1 = Datamodel.makeMonolingualTextValue("Test1",
"en");
MonolingualTextValue mtv2 = Datamodel.makeMonolingualTextValue("Test2",
"fr");
ItemDocument id1 = Datamodel.makeItemDocument(subject1,
Arrays.asList(mtv1, mtv2), Arrays.asList(mtv1),
Collections.<MonolingualTextValue> emptyList(),
Collections.<StatementGroup> emptyList(),
Collections.<String, SiteLink> emptyMap());
jsa.open();
jsa.processItemDocument(id1);
jsa.close();
MockDirectoryManager mdm = new MockDirectoryManager(
Paths.get("/path/to/"), false);
ObjectMapper mapper = new ObjectMapper();
ObjectReader documentReader = mapper
.reader(JacksonTermedStatementDocument.class);
MappingIterator<JacksonTermedStatementDocument> documentIterator = documentReader
.readValues(mdm.getInputStreamForFile("output.json.gz",
CompressionType.GZIP));
List<EntityDocument> results = new ArrayList<>();
while (documentIterator.hasNextValue()) {
JacksonTermedStatementDocument document = documentIterator
.nextValue();
document.setSiteIri(Datamodel.SITE_WIKIDATA);
results.add(document);
}
documentIterator.close();
assertEquals(1, results.size());
assertEquals(id1, results.get(0));
}
@Test
public void testJsonBz2Output() throws IOException {
String[] args = new String[] { "-a", "json", "-o", "output.json", "-z",
"bz2" };
DirectoryManagerFactory
.setDirectoryManagerClass(MockDirectoryManager.class);
ClientConfiguration config = new ClientConfiguration(args);
JsonSerializationAction jsa = (JsonSerializationAction) config
.getActions().get(0);
ItemIdValue subject1 = Datamodel.makeWikidataItemIdValue("Q42");
MonolingualTextValue mtv1 = Datamodel.makeMonolingualTextValue("Test1",
"en");
MonolingualTextValue mtv2 = Datamodel.makeMonolingualTextValue("Test2",
"fr");
ItemDocument id1 = Datamodel.makeItemDocument(subject1,
Arrays.asList(mtv1, mtv2), Arrays.asList(mtv1),
Collections.<MonolingualTextValue> emptyList(),
Collections.<StatementGroup> emptyList(),
Collections.<String, SiteLink> emptyMap());
jsa.open();
jsa.processItemDocument(id1);
jsa.close();
MockDirectoryManager mdm = new MockDirectoryManager(Paths.get("."),
false);
ObjectMapper mapper = new ObjectMapper();
ObjectReader documentReader = mapper
.reader(JacksonTermedStatementDocument.class);
MappingIterator<JacksonTermedStatementDocument> documentIterator = documentReader
.readValues(mdm.getInputStreamForFile("output.json.bz2",
CompressionType.BZ2));
List<EntityDocument> results = new ArrayList<>();
while (documentIterator.hasNextValue()) {
JacksonTermedStatementDocument document = documentIterator
.nextValue();
document.setSiteIri(Datamodel.SITE_WIKIDATA);
results.add(document);
}
documentIterator.close();
assertEquals(1, results.size());
assertEquals(id1, results.get(0));
}
}
| 34.380165 | 83 | 0.757692 |
2a8fe378bf505160ed20b6c97da7c14c29e14e75 | 983 | package com.example.myapp.main.util;
import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
/**
* So far as JavaEE7, @WebFilter does not allow to exclude specific pages.
*
* @author Luca Vercelli
*
*/
@Stateless
public class WebFilterHelper {
/**
* Return true if the given url is to be excluded by WebFilter. This is
* because @WebFilter annotation does not allow excluding specific paths.
*
* @param url
* @param excludeUrls
* @param request
* @return
*/
public boolean excludeUrl(String[] excludeUrls, HttpServletRequest request) {
String uri = request.getRequestURI();
String contextPath = request.getContextPath();
uri = uri.replaceAll("/+", "/"); // convert /myapp///ui -> /myapp/ui
for (String excludeUrl : excludeUrls) {
excludeUrl = excludeUrl.trim();
if (!excludeUrl.equals("") && uri.startsWith(contextPath + excludeUrl)) {
return true;
}
}
return false;
}
}
| 25.205128 | 79 | 0.666328 |
95f4e3821deb163596d5a79759969ac59af697bb | 10,804 | package P2P;
import java.util.concurrent.ScheduledExecutorService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import Main.Global;
/////////////////////////////////////////////////////////////////////////////////////
// P2P has three types of cmd (P2PJoinReq, P2PJoinRsp, P2PPublicKeyNoti) //
// P2P protocol the type of data is pass from Consensus //
/////////////////////////////////////////////////////////////////////////////////////
public class P2P_TX {
private Global global;
public P2P_TX(Global global) {
this.global = global;
}
public boolean WriteDatas(ChannelHandlerContext ctx, byte[] msg, ScheduledExecutorService tm) {
ByteBuf tx_msg = Unpooled.copiedBuffer(msg);
ChannelFuture cf = ctx.writeAndFlush(tx_msg);
try {
cf.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if(future.isSuccess()) {
global.getCLogger().OutConsole(global.getCLogger().LOG_INFO, "Successfully Write Data");
} else {
global.getCLogger().OutConsole(global.getCLogger().LOG_INFO, "Fail to Write Data");
}
}
});
} catch (Exception e) {
this.global.getCLogger().OutConsole(this.global.getCLogger().LOG_ERROR, "Error in P2P WriteData cause " + e.getCause());
tx_msg = null;
cf = null;
return false;
}
tx_msg = null;
cf = null;
return true;
}
public void P2PJoinReq(ChannelHandlerContext ctx, byte[] dstAddr) {
// P2P Header
byte[] P2PHeader = MakeP2PHeader(dstAddr, this.global.getCP2P().getMyP2PAddr(), (byte)P2P_Type.CMD.ordinal(), (byte)P2P_Cmd.P2P_JOIN_REQ.ordinal());
byte[] Len = new byte[P2P_Header_field.Len.getValue()];
// Join Request Header
byte[] JoiningP2PAddr = new byte[P2P_Cmd_Join_Req_field.JoinP2PAddr.ordinal()];
byte[] NodeRule = new byte[P2P_Cmd_Join_Req_field.NodeRule.ordinal()];
byte[] CRC32 = new byte[P2P_Define.CRC32Len.getValue()];
//
int msgLen = P2P_Header_field.getTotalValue() + Len.length + P2P_Cmd_Join_Req_field.getTotalValue() + CRC32.length;
byte[] before_crc32 = new byte[msgLen - CRC32.length];
byte[] m_Msg = new byte[msgLen];
//
int pos = 0;
String nameofCurrMethod = new Throwable().getStackTrace()[0].getMethodName();
this.global.getCLogger().OutConsole(this.global.getCLogger().LOG_INFO, "Name of current method : " + nameofCurrMethod);
Len = this.global.getCTypeCast().shortToByteArray((short)P2P_Cmd_Join_Req_field.getTotalValue());
//
JoiningP2PAddr = this.global.getCP2P().getMyP2PAddr();
NodeRule = this.global.getCP2P().getMyNodeRule();
//
System.arraycopy(P2PHeader, 0, before_crc32, pos, P2PHeader.length); pos += P2PHeader.length;
System.arraycopy(Len, 0, before_crc32, pos, Len.length); pos += Len.length;
System.arraycopy(JoiningP2PAddr, 0, before_crc32, pos, JoiningP2PAddr.length); pos += JoiningP2PAddr.length;
System.arraycopy(NodeRule, 0, before_crc32, pos, NodeRule.length); pos += NodeRule.length;
//
CRC32 = this.global.getCCRC32().CalcCRC32(before_crc32);
System.arraycopy(before_crc32, 0, m_Msg, 0, msgLen - CRC32.length);
System.arraycopy(CRC32, 0, m_Msg, pos, CRC32.length); pos += CRC32.length;
P2PHeader = null;
Len = null;
JoiningP2PAddr = null;
NodeRule = null;
CRC32 = null;
before_crc32 = null;
nameofCurrMethod = null;
WriteDatas(ctx, m_Msg, null);
m_Msg = null;
}
public void P2PJoinRsp(ChannelHandlerContext ctx, byte[] dstAddr, byte[] JoiningP2PAddr, byte[] NodeRule) {
// P2P Header
byte[] P2PHeader = MakeP2PHeader(dstAddr, this.global.getCP2P().getMyP2PAddr(), (byte)P2P_Type.CMD.ordinal(), (byte)P2P_Cmd.P2P_JOIN_RESP.ordinal());
byte[] Len = new byte[P2P_Header_field.Len.getValue()];
// Joining Response Header
byte[] CRC32 = new byte[P2P_Define.CRC32Len.getValue()];
//
int msgLen = P2P_Header_field.getTotalValue() + Len.length + P2P_Cmd_Join_Rsp_field.getTotalValue() + CRC32.length;
byte[] before_crc32 = new byte[msgLen - CRC32.length];
byte[] m_Msg = new byte[msgLen];
//
int pos = 0;
String nameofCurrMethod = new Throwable().getStackTrace()[0].getMethodName();
this.global.getCLogger().OutConsole(this.global.getCLogger().LOG_INFO, "Name of current method : " + nameofCurrMethod);
Len = this.global.getCTypeCast().shortToByteArray((short)P2P_Cmd_Join_Rsp_field.getTotalValue());
//
System.arraycopy(P2PHeader, 0, before_crc32, pos, P2PHeader.length); pos += P2PHeader.length;
System.arraycopy(Len, 0, before_crc32, pos, Len.length); pos += Len.length;
System.arraycopy(JoiningP2PAddr, 0, before_crc32, pos, JoiningP2PAddr.length); pos += JoiningP2PAddr.length;
System.arraycopy(NodeRule, 0, before_crc32, pos, NodeRule.length); pos += NodeRule.length;
//
CRC32 = this.global.getCCRC32().CalcCRC32(before_crc32);
System.arraycopy(before_crc32, 0, m_Msg, 0, msgLen - CRC32.length);
System.arraycopy(CRC32, 0, m_Msg, pos, CRC32.length); pos += CRC32.length;
P2PHeader = null;
Len = null;
CRC32 = null;
before_crc32 = null;
nameofCurrMethod = null;
WriteDatas(ctx, m_Msg, null);
m_Msg = null;
}
public void P2PPubkeyNoti(ChannelHandlerContext ctx, byte[] dstAddr) {
// P2P Header
byte[] P2PHeader = MakeP2PHeader(dstAddr, this.global.getCP2P().getMyP2PAddr(), (byte)P2P_Type.CMD.ordinal(), (byte)P2P_Cmd.P2P_PUBKEY_NOTI.ordinal());
byte[] Len = new byte[P2P_Header_field.Len.getValue()];
// Public Key Notification
byte[] CompPubKey = new byte[P2P_Cmd_Pubkey_Noti_field.CompPubkey.ordinal()];
byte[] CRC32 = new byte[P2P_Define.CRC32Len.getValue()];
//
int msgLen = P2P_Header_field.getTotalValue() + Len.length + P2P_Cmd_Pubkey_Noti_field.getTotalValue() + CRC32.length;
byte[] before_crc32 = new byte[msgLen - CRC32.length];
byte[] m_Msg = new byte[msgLen];
//
int pos = 0;
String nameofCurrMethod = new Throwable().getStackTrace()[0].getMethodName();
this.global.getCLogger().OutConsole(this.global.getCLogger().LOG_INFO, "Name of current method : " + nameofCurrMethod);
Len = this.global.getCTypeCast().shortToByteArray((short)P2P_Cmd_Pubkey_Noti_field.getTotalValue());
//
CompPubKey = this.global.getCKeyUtil().getCMyKey().getPublicKeyStr();
//
System.arraycopy(P2PHeader, 0, before_crc32, pos, P2PHeader.length); pos += P2PHeader.length;
System.arraycopy(Len, 0, before_crc32, pos, Len.length); pos += Len.length;
System.arraycopy(CompPubKey, 0, before_crc32, pos, CompPubKey.length); pos += CompPubKey.length;
//
CRC32 = this.global.getCCRC32().CalcCRC32(before_crc32);
System.arraycopy(before_crc32, 0, m_Msg, 0, msgLen - CRC32.length);
System.arraycopy(CRC32, 0, m_Msg, pos, CRC32.length); pos += CRC32.length;
P2PHeader = null;
Len = null;
CompPubKey = null;
CRC32 = null;
before_crc32 = null;
nameofCurrMethod = null;
WriteDatas(ctx, m_Msg, null);
m_Msg = null;
}
public byte[] MakeP2PHeader(byte[] dstAddr, byte[] srcAddr, byte type, byte cmd) {
// P2P Header
byte[] DstAddr = new byte[P2P_Header_field.DstAddr.getValue()];
byte[] SrcAddr = new byte[P2P_Header_field.SrcAddr.getValue()];
byte[] TimeStamp = new byte[P2P_Header_field.TimeStamp.getValue()];
byte[] Version = new byte[P2P_Header_field.Version.getValue()];
byte[] Type = new byte[P2P_Header_field.Type.getValue()];
byte[] Cmd = new byte[P2P_Header_field.Cmd.getValue()];
byte[] Rsvd = new byte[P2P_Header_field.Rsvd.getValue()];
byte[] SeqNum = new byte[P2P_Header_field.SeqNum.getValue()];
//
byte[] P2PHeader = new byte[P2P_Header_field.getTotalValue()];
int pos = 0;
DstAddr = dstAddr;
//DstAddr = this.global.getCTypeCast().BytesArrayLE2(DstAddr);
SrcAddr = srcAddr;
//SrcAddr = this.global.getCTypeCast().BytesArrayLE2(DstAddr);
TimeStamp = this.global.getCTimeStamp().getCurrentTimeStampBA();
Version[0] = this.global.getCP2P().getMyVersion();
Type[0] = type;
Cmd[0] = cmd;
Rsvd[0] = (byte)0x00;
if (type == P2P_Type.CMD.ordinal())
{
SeqNum = this.global.getCTypeCast().shortToByteArray(this.global.getCP2P().getMyP2PCmdSN());
this.global.getCP2P().incMyP2PCmdSN();
}
else if (type == P2P_Type.DATA.ordinal())
{
SeqNum = this.global.getCTypeCast().shortToByteArray(this.global.getCP2P().getMyP2PDataSN());
this.global.getCP2P().incMyP2PDataSN();
}
else
{
SeqNum = this.global.getCTypeCast().shortToByteArray((short)0x00);
}
System.arraycopy(DstAddr, 0, P2PHeader, pos, DstAddr.length); pos += DstAddr.length;
System.arraycopy(SrcAddr, 0, P2PHeader, pos, SrcAddr.length); pos += SrcAddr.length;
System.arraycopy(TimeStamp, 0, P2PHeader, pos, TimeStamp.length); pos += TimeStamp.length;
System.arraycopy(Version, 0, P2PHeader, pos, Version.length); pos += Version.length;
System.arraycopy(Type, 0, P2PHeader, pos, 1); pos += 1;
System.arraycopy(Cmd, 0, P2PHeader, pos, Type.length); pos += Type.length;
System.arraycopy(Rsvd, 0, P2PHeader, pos, Rsvd.length); pos += Rsvd.length;
System.arraycopy(SeqNum, 0, P2PHeader, pos, SeqNum.length); pos += SeqNum.length;
DstAddr = null;
SrcAddr = null;
TimeStamp = null;
Version = null;
Type = null;
Cmd = null;
Rsvd = null;
SeqNum = null;
return P2PHeader;
}
public boolean PassFromConsensusTX(ChannelHandlerContext ctx, byte[] dstAddr, byte[] Contents) {
byte[] P2PHeader = MakeP2PHeader(dstAddr, this.global.getCP2P().getMyP2PAddr(), (byte)P2P_Type.DATA.ordinal(), (byte)0x00);
byte[] p2PLen = new byte[P2P_Header_field.Len.getValue()];
byte[] CRC32 = new byte[P2P_Define.CRC32Len.getValue()];
this.global.getCLogger().OutConsole(this.global.getCLogger().LOG_DEBUG, "PassFromConsensusTX " + P2PHeader.length + " " + p2PLen.length + " " + Contents.length);
int totalLen = P2PHeader.length + p2PLen.length + Contents.length + CRC32.length;
byte[] before_crc32 = new byte[totalLen - CRC32.length];
byte[] m_Msg = new byte[totalLen];
int pos = 0;
p2PLen = this.global.getCTypeCast().shortToByteArray((short)Contents.length);
System.arraycopy(P2PHeader, 0, before_crc32, pos, P2PHeader.length); pos += P2PHeader.length;
System.arraycopy(p2PLen, 0, before_crc32, pos, p2PLen.length); pos += p2PLen.length;
System.arraycopy(Contents, 0, before_crc32, pos, Contents.length); pos += Contents.length;
// Calculate CRC32
CRC32 = this.global.getCCRC32().CalcCRC32(before_crc32);
System.arraycopy(before_crc32, 0, m_Msg, 0, totalLen - CRC32.length);
System.arraycopy(CRC32, 0, m_Msg, pos, CRC32.length); pos += CRC32.length;
P2PHeader = null;
p2PLen = null;
CRC32 = null;
before_crc32 = null;
return (WriteDatas(ctx, m_Msg, null));
}
}
| 38.312057 | 164 | 0.703721 |
f53c005671208205844ba294b5dc5123a7337349 | 1,497 | package rpc.ndr;
public class BooleanHolder implements Holder {
private Boolean value;
private boolean embedded;
public BooleanHolder() {
setValue(null);
}
public BooleanHolder(boolean value) {
setValue(new Boolean(value));
}
public BooleanHolder(Boolean value) {
setValue(value);
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = (value != null) ? (Boolean) value : Boolean.FALSE;
}
public boolean getBoolean() {
return ((Boolean) getValue()).booleanValue();
}
public void setBoolean(boolean value) {
setValue(new Boolean(value));
}
public int getAlignment() {
return 1;
}
public boolean isEmbedded() {
return embedded;
}
public void setEmbedded(boolean embedded) {
this.embedded = embedded;
}
public void read(NetworkDataRepresentation ndr) {
setValue(new Boolean(ndr.readBoolean()));
}
public void write(NetworkDataRepresentation ndr) {
Boolean value = (Boolean) getValue();
if (value == null) return;
ndr.writeBoolean(value.booleanValue());
}
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException ex) {
throw new IllegalStateException();
}
}
public String toString() {
return String.valueOf(getValue());
}
}
| 20.791667 | 71 | 0.597862 |
668b062ea202cb0cadd3dca58eef631631ea5c6f | 224 | package com.wthfeng.learn.reflect;
/**
* @author wangtonghe
* @date 2017/10/12 15:28
*/
public class SubjectImpl implements Subject {
@Override
public void load() {
System.out.println("实际代理对象");
}
}
| 16 | 45 | 0.642857 |
97504b38d59e6d616aab374b02a3dab7db35ea54 | 1,152 | //© A+ Computer Science - www.apluscompsci.com
//Name -
//Date -
//Class -
//Lab -
import java.awt.Color;
import java.awt.Graphics;
public class Shape
{
//instance variables
private int xPos;
private int yPos;
private int width;
private int height;
private Color color;
public Shape(int x, int y, int wid, int ht, Color col)
{
xPos = x;
yPos = y;
width = wid;
height = ht;
color = col;
}
public void draw(Graphics window)
{
window.setColor(Color.RED);
window.drawString("Neo Wang APCS 2018",10,40);
int[] xPoints = {xPos, xPos, xPos + width};
int[] yPoints = {yPos, yPos+height, yPos + height};
window.setColor(color);
window.drawPolygon(xPoints, yPoints, 3);
// draw whatever you want
// You will need to use Graphics routines like
// window.drawRect(...);
// window.drawOval(...);
// window.drawLine(...);
// window.drawString(...);
// and any others
// The ... indicates that you need to supply the parameters
// ^
}
public String toString()
{
return xPos+" "+yPos+" "+width+" "+height+" "+color;
}
}
| 18.580645 | 63 | 0.595486 |
edd4ef4a41384c263abc64d67eef5be156dbdb65 | 3,940 | package com.gots.intelligentnursing.receiver;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.gots.intelligentnursing.business.EventPoster;
import com.gots.intelligentnursing.business.UserContainer;
import com.gots.intelligentnursing.exception.BluetoothException;
import com.gots.intelligentnursing.business.BluetoothPairer;
import com.gots.intelligentnursing.entity.DataEvent;
import com.gots.intelligentnursing.tools.LogUtil;
import org.greenrobot.eventbus.EventBus;
import static com.gots.intelligentnursing.business.EventPoster.ACTION_BLUETOOTH_RECEIVER_ON_RECEIVE;
/**
* @author zhqy
* @date 2018/4/17
*/
public class BluetoothReceiver extends BroadcastReceiver {
public static final int CODE_FOUND = 0;
public static final int CODE_BOND_SUCCESS = 1;
public static final int CODE_ERROR = 2;
public static final int CODE_START = 3;
public static final int CODE_FINISH = 4;
private static final String TAG = "BluetoothReceiver";
private static final String DEVICE_NAME = "ZhiHu-W1";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
LogUtil.i(TAG, "receive ACTION_FOUND broadcast");
if (device != null && DEVICE_NAME.equals(device.getName())) {
EventBus.getDefault().post(new DataEvent(ACTION_BLUETOOTH_RECEIVER_ON_RECEIVE, CODE_FOUND));
if (device.getBondState() == BluetoothDevice.BOND_NONE) {
try {
BluetoothPairer.createBond(device.getClass(), device);
} catch (BluetoothException e) {
e.printStackTrace();
EventPoster.post(
new DataEvent(ACTION_BLUETOOTH_RECEIVER_ON_RECEIVE, CODE_ERROR, e.getMessage()));
}
} else if(device.getBondState() == BluetoothDevice.BOND_BONDED) {
EventBus.getDefault().post(
new DataEvent(ACTION_BLUETOOTH_RECEIVER_ON_RECEIVE, CODE_BOND_SUCCESS, device));
}
}
} else if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
LogUtil.i(TAG, "receive ACTION_PAIRING_REQUEST broadcast");
if (device != null && DEVICE_NAME.equals(device.getName())) {
try {
BluetoothPairer.setPairingConfirmation(device.getClass(), device, true);
abortBroadcast();
BluetoothPairer.setPin(device.getClass(), device,
UserContainer.getUser().getUserInfo().getDeviceInfo().getBluetoothPassword());
EventBus.getDefault().post(
new DataEvent(ACTION_BLUETOOTH_RECEIVER_ON_RECEIVE, CODE_BOND_SUCCESS, device));
} catch (BluetoothException e) {
e.printStackTrace();
EventBus.getDefault().post(
new DataEvent(ACTION_BLUETOOTH_RECEIVER_ON_RECEIVE, CODE_ERROR, e.getMessage()));
}
}
} else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
LogUtil.i(TAG, "receive ACTION_DISCOVERY_STARTED broadcast");
EventBus.getDefault().post(new DataEvent(ACTION_BLUETOOTH_RECEIVER_ON_RECEIVE, CODE_START));
} else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
LogUtil.i(TAG, "receive ACTION_DISCOVERY_FINISHED broadcast");
EventBus.getDefault().post(new DataEvent(ACTION_BLUETOOTH_RECEIVER_ON_RECEIVE, CODE_FINISH));
}
}
}
| 48.04878 | 113 | 0.660914 |
2ce1602cafdabfaa34f6cd17739e875ea51d5725 | 1,200 | package org.archivemanager.models.repository;
import java.util.ArrayList;
import java.util.List;
import org.archivemanager.models.ContactModel;
import org.archivemanager.models.SystemModel;
import org.archivemanager.services.entity.Entity;
public class Individual {
private long id;
private String title;
private String biography;
private List<DigitalObject> attachments = new ArrayList<DigitalObject>();
public Individual() {}
public Individual(Entity entity) {
this.id = entity.getId();
this.title = entity.getPropertyValueString(SystemModel.NAME);
this.biography = entity.getPropertyValueString(ContactModel.BIOGRAPHY);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBiography() {
return biography;
}
public void setBiography(String biography) {
this.biography = biography;
}
public List<DigitalObject> getAttachments() {
return attachments;
}
public void setAttachments(List<DigitalObject> attachments) {
this.attachments = attachments;
}
}
| 24.489796 | 75 | 0.725 |
07d44d4793d26a633ca914f898aa338dcdcbda2a | 655 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package expressionparser;
import java.util.Scanner;
/**
*
* @author Lomztein
*/
public class OperatorPrecedence {
public static final Scanner INPUT = new Scanner(System.in);
public static void main(String[] args) {
while (true) {
String input = INPUT.nextLine();
ExpressionParser parser = new ExpressionParser();
double result = parser.parse(input);
System.out.println(result);
}
}
}
| 21.833333 | 79 | 0.648855 |
beafa75c2f08ef4cd94f7e40203ca1dfa5249dc1 | 1,824 | package org.taymyr.lagom.elasticsearch;
import org.taymyr.lagom.elasticsearch.document.dsl.Document;
import org.taymyr.lagom.elasticsearch.search.dsl.SearchResult;
import java.util.Objects;
public class TestDocument {
private String user;
private String message;
private Double balance;
public TestDocument() {
}
public TestDocument(String user, String message) {
this.user = user;
this.message = message;
}
public TestDocument(String user, String message, Double balance) {
this.user = user;
this.message = message;
this.balance = balance;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof TestDocument)) return false;
TestDocument that = (TestDocument) o;
return Objects.equals(user, that.user) &&
Objects.equals(message, that.message) &&
Objects.equals(balance, that.balance);
}
@Override
public int hashCode() {
return Objects.hash(user, message, balance);
}
public static class TestDocumentResult extends SearchResult<TestDocument> { }
public static class IndexedTestDocument extends Document<TestDocument> {
public IndexedTestDocument() { }
public IndexedTestDocument(TestDocument document) {
super(document);
}
}
}
| 23.384615 | 81 | 0.632127 |
59e0d55d2625705c67de73fda9f045a092404840 | 1,758 | /*
* 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 com.intel.hibench.common.streaming;
public enum TestCase {
// Do nothing with input events. It's useful to test the native schedule cost
IDENTITY("identity"),
// Repartition input events to ensure data shuffle happening
REPARTITION("repartition"),
// Wordcount is used to test the performance of state operator
WORDCOUNT("wordcount"),
// FixWindow is used to test the performance of window operator
FIXWINDOW("fixwindow"),
// ====== Following TestCase hasn't been finalized ======
PROJECT("project"),
SAMPLE("sample"),
GREP("grep"),
DISTINCTCOUNT("distinctCount"),
STATISTICS("statistics");
// =========================================================
private String name;
TestCase(String name) {
this.name = name;
}
// Convert input name to uppercase and return related value of TestCase type
public static TestCase withValue(String name) {return TestCase.valueOf(name.toUpperCase()); }
}
| 31.392857 | 95 | 0.70876 |
b9f590713c260da75868ef0c95ed0d337d009afd | 1,385 | package com.roche.manage.service;
import java.util.List;
import com.roche.manage.domain.SysGuide;
/**
* 指引管理Service接口
*
* @author qiushuo dong
* @date 2021-09-26
*/
public interface ISysGuideService
{
/**
* 查询指引管理
*
* @param guideId 指引管理主键
* @return 指引管理
*/
public SysGuide selectSysGuideByGuideId(Long guideId);
/**
* 查询指引管理列表
*
* @param sysGuide 指引管理
* @return 指引管理集合
*/
public List<SysGuide> selectSysGuideList(SysGuide sysGuide);
/**
* 新增指引管理
*
* @param sysGuide 指引管理
* @return 结果
*/
public int insertSysGuide(SysGuide sysGuide);
/**
* 新增指引管理
*
* @param guideId 指引管理
* @return 结果
*/
public int insertEditSysGuide(Long guideId ,String url);
/**
* 修改指引管理
*
* @param sysGuide 指引管理
* @return 结果
*/
public int updateSysGuide(SysGuide sysGuide);
/**
* 批量删除指引管理
*
* @param guideIds 需要删除的指引管理主键集合
* @return 结果
*/
public int deleteSysGuideByGuideIds(String guideIds);
/**
* 删除指引管理信息
*
* @param guideId 指引管理主键
* @return 结果
*/
public int deleteSysGuideByGuideId(Long guideId);
/**
* 删除指引中的图片信息
*
* @param guideId 指引管理主键
* @return 结果
*/
public int deleteSysGuideImgByGuideId(String imageUrl,Long guideId);
}
| 17.987013 | 72 | 0.579783 |
8b7ef61787308b962d661898e561f7f26132622d | 4,292 | package br.com.felix.bikeloc.ui;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import br.com.felix.bikeloc.R;
import br.com.felix.bikeloc.auth.Session;
import br.com.felix.bikeloc.model.Place;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
replaceFragment(
R.id.frameLayoutMain,
HomeFragment.newInstance(),
"HOMEFRAGMENT",
"HOME"
);
BottomNavigationView bottomNav = findViewById(R.id.bottomNav);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.map:
replaceFragment(
R.id.frameLayoutMain,
HomeFragment.newInstance(),
"HOMEFRAGMENT",
"HOME"
);
return true;
case R.id.places:
replaceFragment(
R.id.frameLayoutMain,
PlaceFragment.newInstance(),
"PLACEFRAGMENT",
"PLACE"
);
return true;
case R.id.profile:
replaceFragment(
R.id.frameLayoutMain,
ProfileFragment.newInstance(),
"PROFILEFRAGMENT",
"PROFILE"
);
return true;
}
return false;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return(super.onOptionsItemSelected(item));
}
protected void replaceFragment(
@IdRes int containerViewId,
@NonNull Fragment fragment,
@NonNull String fragmentTag,
@Nullable String backStackStateName
) {
getSupportFragmentManager()
.beginTransaction()
.replace(containerViewId, fragment, fragmentTag)
.addToBackStack(backStackStateName)
.commit();
}
} | 34.063492 | 115 | 0.621622 |
e51d0cb1908824dd665a59d38a60406bf46133a8 | 1,114 | package pl.p.lodz.iis.hr.configuration;
import org.pac4j.oauth.client.GitHubClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import pl.p.lodz.iis.hr.appconfig.AppConfig;
@Configuration
@DependsOn({"pac4jConfig", "appConfig"})
class InterceptorRegistryConfig extends WebMvcConfigurerAdapter {
@Autowired private GitHubClient gitHubClient;
@Autowired private AppConfig appConfig;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new InterceptorHasRoleMaster(gitHubClient, appConfig)).addPathPatterns("/m/**");
registry.addInterceptor(new InterceptorHasRolePeer(gitHubClient, appConfig)).addPathPatterns("/p/**");
registry.addInterceptor(new InterceptorUserInfoAppender(gitHubClient, appConfig)).addPathPatterns("/**");
}
}
| 44.56 | 113 | 0.807899 |
b19bbea4461a45d04eafd6334527a02a0123f543 | 1,053 | import java.util.*;
class Problem4
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t,i;
double avg,tot,neg,pos;
do
{
System.out.println("Enter Number of Students");
t = sc.nextInt();
avg = 0;
neg = pos = 0;
if(t==0)
{
break;
}
double inr[] = new double[t];
for(i=0;i<t;i++)
{
inr[i] = sc.nextDouble();
avg += inr[i];
}
avg /= t;
for(i=0;i<t;i++)
{
if(inr[i]<avg)
{
neg += avg-inr[i];
}
else
{
pos += inr[i]-avg;
}
}
tot = pos<neg?pos:neg;
String res = ""+tot;
res = res.substring(0,res.indexOf('.')+3);
System.out.println(res);
}while(t!=0);
}
} | 24.488372 | 59 | 0.333333 |
a2b69823223dee954ac556fd593c5f4fbe0f711d | 12,217 | package com.relevantcodes.extentreports;
import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bson.Document;
import org.bson.types.ObjectId;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.relevantcodes.extentreports.model.Log;
import com.relevantcodes.extentreports.model.Test;
import com.relevantcodes.extentreports.model.TestAttribute;
import com.relevantcodes.extentreports.utils.MongoUtil;
public class ExtentX extends LogSettings implements IReporter {
private Report report;
private String testName;
private ObjectId reportId;
private MongoClient mongoClient;
private MongoDatabase db;
private MongoCollection<Document> projectCollection;
private MongoCollection<Document> reportCollection;
private MongoCollection<Document> testCollection;
private MongoCollection<Document> nodeCollection;
private MongoCollection<Document> logCollection;
private MongoCollection<Document> categoryCollection;
private MongoCollection<Document> authorCollection;
private MongoCollection<Document> categoriesTests;
private MongoCollection<Document> authorsTests;
@Override
public void start(Report report) {
this.report = report;
db = mongoClient.getDatabase("extent");
// collections
projectCollection = db.getCollection("project");
reportCollection = db.getCollection("report");
testCollection = db.getCollection("test");
nodeCollection = db.getCollection("node");
logCollection = db.getCollection("log");
categoryCollection = db.getCollection("category");
authorCollection = db.getCollection("author");
// many-to-many
categoriesTests = db.getCollection("category_tests__test_categories");
authorsTests = db.getCollection("author_tests__test_authors");
}
@Override
public void stop() {
mongoClient.close();
}
@Override
public void flush() {
if (reportId == null)
insertReport();
reportCollection.updateOne(
new Document("_id", reportId),
new Document("$set",
new Document("endTime", new Date(report.getSuiteTimeInfo().getSuiteEndTimestamp()))
.append("status", report.getStatus().toString())));
}
private ObjectId getProjectId() {
String projectName = report.getProjectName();
Document doc = new Document("name", projectName);
FindIterable<Document> iterable = projectCollection.find(doc);
Document project = iterable.first();
ObjectId projectId;
if (project != null) {
projectId = project.getObjectId("_id");
}
else {
projectCollection.insertOne(doc);
projectId = MongoUtil.getId(doc);
}
return projectId;
}
private void insertReport() {
ObjectId projectId = getProjectId();
String id = report.getMongoDBObjectID();
// if extent is started with [replaceExisting = false] and ExtentX is used,
// use the same report ID for the 1st report run and update the database for
// the corresponding report-ID
if (id != null & !id.isEmpty()) {
FindIterable<Document> iterable = reportCollection.find(new Document("_id", new ObjectId(id)));
Document report = iterable.first();
if (report != null) {
reportId = report.getObjectId("_id");
return;
}
}
// if [replaceExisting = true] or the file does not exist, create a new
// report-ID and assign all components to it
Document doc = new Document("project", projectId)
.append("fileName", new File(report.getFilePath()).getName())
.append("startTime", report.getStartedTime());
reportCollection.insertOne(doc);
reportId = MongoUtil.getId(doc);
report.setMongoDBObjectID(reportId.toString());
}
@Override
public void addTest(Test test) {
if (reportId == null)
insertReport();
testName = test.getName();
Document doc = new Document("report", reportId)
.append("name", testName)
.append("status", test.getStatus().toString())
.append("description", test.getDescription())
.append("startTime", test.getStartedTime())
.append("endTime", test.getEndedTime())
.append("childNodesCount", getNodeLength(test, 0))
.append("categorized", test.getCategoryList().size() > 0 ? true : false);
testCollection.insertOne(doc);
ObjectId testId = MongoUtil.getId(doc);
// add logs
addLogs(test, testId);
// add child nodes
addNodes(test, testId, 0);
// add categories
addCategories(test, testId);
// add authors
addAuthors(test, testId);
}
private int getNodeLength(Test test, int length) {
for (Test node : test.getNodeList()) {
length++;
if (node.hasChildNodes) {
length = getNodeLength(node, length);
}
}
return length;
}
private void addLogs(Test test, ObjectId testId) {
Iterator<Log> iter = test.logIterator();
Log log; Document doc;
int ix = 0;
while (iter.hasNext()) {
log = iter.next();
doc = new Document("test", testId)
.append("report", reportId)
.append("testName", test.getName())
.append("logSequence", ix++)
.append("status", log.getLogStatus().toString())
.append("timestamp", log.getTimestamp())
.append("stepName", log.getStepName())
.append("details", log.getDetails());
logCollection.insertOne(doc);
}
}
private void addNodes(Test test, ObjectId testId, int level) {
if (!test.hasChildNodes)
return;
for (Test node : test.getNodeList()) {
addNode(node, testId, ++level);
--level;
if (node.hasChildNodes) {
addNodes(node, testId, ++level);
--level;
}
}
}
private void addNode(Test node, ObjectId testId, int level) {
Document doc = new Document("test", testId)
.append("parentTestName", testName)
.append("report", reportId)
.append("name", node.getName())
.append("level", level)
.append("status", node.getStatus().toString())
.append("description", node.getDescription())
.append("startTime", node.getStartedTime())
.append("endTime", node.getEndedTime())
.append("childNodesCount", node.getNodeList().size());
nodeCollection.insertOne(doc);
ObjectId nodeId = MongoUtil.getId(doc);
addLogs(node, nodeId);
}
private void addCategories(Test test, ObjectId testId) {
Iterator<TestAttribute> categories = test.categoryIterator();
while (categories.hasNext()) {
TestAttribute category = categories.next();
Document doc = new Document("tests", testId)
.append("report", reportId)
.append("name", category.getName())
.append("status", test.getStatus().toString())
.append("testName", test.getName());
categoryCollection.insertOne(doc);
ObjectId categoryId = MongoUtil.getId(doc);
/* create association with category
* tests (many) <-> categories (many)
* tests and categories have a many to many relationship
* - a test can be assigned with one or more categories
* - a category can have one or more tests
*/
doc = new Document("test_categories", testId)
.append("category_tests", categoryId)
.append("category", category.getName())
.append("test", test.getName());
categoriesTests.insertOne(doc);
}
}
private void addAuthors(Test test, ObjectId testId) {
Iterator<TestAttribute> authors = test.authorIterator();
while (authors.hasNext()) {
TestAttribute author = authors.next();
Document doc = new Document("tests", testId)
.append("report", reportId)
.append("name", author.getName())
.append("status", test.getStatus().toString())
.append("testName", test.getName());
authorCollection.insertOne(doc);
ObjectId authorId = MongoUtil.getId(doc);
doc = new Document("test_authors", testId)
.append("author_tests", authorId)
.append("author", author.getName())
.append("test", test.getName());
authorsTests.insertOne(doc);
}
}
@Override
public void setTestRunnerLogs() {
}
public ExtentX() {
mongoClient = new MongoClient("localhost", 27017);
}
public ExtentX(String host) {
mongoClient = new MongoClient(host, 27017);
}
public ExtentX(String host, MongoClientOptions options) {
mongoClient = new MongoClient(host, options);
}
public ExtentX(String host, int port) {
mongoClient = new MongoClient(host, port);
}
public ExtentX(MongoClientURI uri) {
mongoClient = new MongoClient(uri);
}
public ExtentX(ServerAddress addr) {
mongoClient = new MongoClient(addr);
}
public ExtentX(List<ServerAddress> seeds) {
mongoClient = new MongoClient(seeds);
}
public ExtentX(List<ServerAddress> seeds, List<MongoCredential> credentialsList) {
mongoClient = new MongoClient(seeds, credentialsList);
}
public ExtentX(List<ServerAddress> seeds, List<MongoCredential> credentialsList, MongoClientOptions options) {
mongoClient = new MongoClient(seeds, credentialsList, options);
}
public ExtentX(List<ServerAddress> seeds, MongoClientOptions options) {
mongoClient = new MongoClient(seeds, options);
}
public ExtentX(ServerAddress addr, List<MongoCredential> credentialsList) {
mongoClient = new MongoClient(addr, credentialsList);
}
public ExtentX(ServerAddress addr, List<MongoCredential> credentialsList, MongoClientOptions options) {
mongoClient = new MongoClient(addr, credentialsList, options);
}
public ExtentX(ServerAddress addr, MongoClientOptions options) {
mongoClient = new MongoClient(addr, options);
}
static {
// set mongodb reporting for only critical/severe events
Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
mongoLogger.setLevel(Level.SEVERE);
}
}
| 34.905714 | 114 | 0.570516 |
fe2f8762e7dec2385898294c0ac6093707f6db81 | 77 | package com.google.android.gms.location;
public interface GeofencingApi {
}
| 15.4 | 40 | 0.805195 |
487694329a4c95757135ca0b20ddc189dc5512bf | 541 | public static boolean getConnection(String dsn) {
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:" + dsn;
con = DriverManager.getConnection(url);
} catch (ClassNotFoundException e) {
return false;
} catch (SQLException e) {
return false;
}
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
| 28.473684 | 58 | 0.504621 |
6873855c34c09db07fd6853fe1d3bee38beacec1 | 2,421 | package codersit.co.kr.jejugo.activity.partnerstore;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import codersit.co.kr.jejugo.R;
import codersit.co.kr.jejugo.dto.DTOPartnerStore;
/**
* Created by BooHee on 2017-06-11.
*/
public class PartnerStoreAdapter extends BaseAdapter {
Context mContext;
private ArrayList<DTOPartnerStore> dtoStoreList = new ArrayList<>();
private List<DTOPartnerStore> tempList = null;
public PartnerStoreAdapter(Context mContext, ArrayList<DTOPartnerStore> dtoPartnerStore)
{
this.mContext = mContext;
this.dtoStoreList = dtoPartnerStore;
this.tempList = new ArrayList<>();
this.tempList.addAll(dtoStoreList);
}
@Override
public int getCount() {
return dtoStoreList.size();
}
@Override
public Object getItem(int position) {
return dtoStoreList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.partnerstore_item, parent, false);
TextView tv_store_title = (TextView)convertView.findViewById(R.id.store_title);
TextView tv_store_addr = (TextView)convertView.findViewById(R.id.store_addr);
TextView tv_store_tel = (TextView)convertView.findViewById(R.id.store_tel);
tv_store_title.setText(dtoStoreList.get(position).getStoreName());
tv_store_addr.setText(dtoStoreList.get(position).getAddr());
tv_store_tel.setText("("+dtoStoreList.get(position).getTelNo()+")");
return convertView;
}
public void filter(String charText)
{
dtoStoreList.clear();
if(charText.length() == 0)
{
dtoStoreList.addAll(tempList);
}
else
{
for(DTOPartnerStore tp : tempList)
{
if(tp.getStoreName().toLowerCase(Locale.getDefault()).contains(charText))
{
dtoStoreList.add(tp);
}
}
}
notifyDataSetChanged();
}
}
| 27.202247 | 114 | 0.662949 |
5e1332452b47c312df84a05c91c0bb80bbbb7582 | 394 | package com.emicb.desolation.level.tile;
import com.emicb.desolation.graphics.Screen;
import com.emicb.desolation.graphics.Sprite;
public class VoidTile extends Tile {
// Tile constructor
public VoidTile(Sprite sprite) {
super(sprite);
}
public void render(int x, int y, Screen screen) {
screen.renderTile(x << 5, y << 5, this);
}
public boolean solid() {
return true;
}
}
| 18.761905 | 50 | 0.71066 |
c9256260d52403b6d3c127607a048e0565bc2873 | 2,281 | package com.helospark.site.core.web.common.password;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.stream.Stream;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ConstraintValidatorContext.ConstraintViolationBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mock;
import org.mockito.Mockito;
public class ValidPasswordValidatorTest {
@Mock
private ConstraintValidatorContext constraintValidatorContext;
@Mock
private ConstraintViolationBuilder constraintViolationBuilder;
private ValidPasswordValidator underTest;
@BeforeEach
public void setUp() {
initMocks(this);
underTest = new ValidPasswordValidator();
when(constraintValidatorContext.buildConstraintViolationWithTemplate(Mockito.anyString())).thenReturn(constraintViolationBuilder);
}
@ParameterizedTest
@MethodSource("passwordTestDataSource")
public void testWrongPassword() {
boolean result = underTest.isValid("asd", constraintValidatorContext);
assertThat(result, is(false));
}
private static Stream<Arguments> passwordTestDataSource() {
return Stream.of(
Arguments.of("pass"),
Arguments.of("pass1"),
Arguments.of("pass12121pass12121pass12121pass12121pass12121pass12121pass12121pass12121pass12121pass12121"),
Arguments.of(""));
}
@ParameterizedTest
@MethodSource("correctPasswordTestDataSource")
public void testCorrectPasswords(String input) {
boolean result = underTest.isValid(input, constraintValidatorContext);
assertThat(result, is(true));
}
private static Stream<Arguments> correctPasswordTestDataSource() {
return Stream.of(
Arguments.of("password1"),
Arguments.of("SecurePassword!!!?"),
Arguments.of("This is a sentence"),
Arguments.of("Whut????????"));
}
}
| 32.585714 | 138 | 0.724244 |
7533f50a9267c2c4d226a61e01a40cd5260653ea | 1,629 | import org.testng.Assert;
import org.testng.annotations.Test;
import base.BaseTest;
import base.WebLink;
import pages.DynamicControlPage;
public class DynamicContorl_Test extends BaseTest {
DynamicControlPage page = null;
@Test
public void validateChcckBoxGoneAfterRemoving() {
page = new DynamicControlPage(driver);
try {
driver.get(WebLink.dynamicControlPageUrl);
Assert.assertTrue(page.verifyCheckBoxIsRemoved());
}
catch (Exception e) {
Assert.assertTrue(false);
e.getLocalizedMessage();
}
}
@Test
public void validateCheckBoxIsAdded() {
page = new DynamicControlPage(driver);
try {
driver.get(WebLink.dynamicControlPageUrl);
page.verifyCheckBoxIsRemoved();
Assert.assertTrue(page.verifyChckBoxIsAdded());
} catch (Exception e) {
Assert.assertTrue(false);
e.getLocalizedMessage();
}
}
@Test
public void validateTextBoxIsDisabled() {
page = new DynamicControlPage(driver);
try {
driver.get(WebLink.dynamicControlPageUrl);
page.verifyCheckBoxIsRemoved();
Assert.assertTrue(page.verifyTextBoxIsDisabled());
// Assert.assertEquals(page.verifyDropDownOption("Option 1"), true);
} catch (Exception e) {
Assert.assertTrue(false);
e.getLocalizedMessage();
}
}
@Test
public void validateTextBoxEnabled() {
page = new DynamicControlPage(driver);
try {
driver.get(WebLink.dynamicControlPageUrl);
page.enableTextBox();
Assert.assertTrue(page.verifyTextBoxIsEnabled());
// Assert.assertEquals(page.verifyDropDownOption("Option 1"), true);
} catch (Exception e) {
Assert.assertTrue(false);
e.getLocalizedMessage();
}
}
}
| 24.681818 | 71 | 0.735421 |
76259eef9cb43fc3ef74416067c1d9c75a316865 | 16,932 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Vistas;
import Controlador.Conexion;
import Modelo.Usuario;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
/**
*
* @author Daro
*/
public class Login extends javax.swing.JFrame {
/**
* Creates new form Login
*/
//String usuario1 = "dennis", contraseña1 = "dennis";
public Login() {
initComponents();
setLocationRelativeTo(null);// centrado
setResizable(false); // impide maximizar
setTitle("Inicio Sesión");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btnIngresar = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jSeparator2 = new javax.swing.JSeparator();
btnCancelar = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtContrasena = new javax.swing.JPasswordField();
jLabel5 = new javax.swing.JLabel();
jComboBoxRol = new javax.swing.JComboBox<>();
textFieldUsuario = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
btnIngresar.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
btnIngresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/acceder.png"))); // NOI18N
btnIngresar.setText("Ingresar");
btnIngresar.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnIngresar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnIngresarActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel1.setText("Sistema de Gestión de Turnos ");
btnCancelar.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/salir.png"))); // NOI18N
btnCancelar.setText("Salir");
btnCancelar.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelarActionPerformed(evt);
}
});
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Inicio de Sesión", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 15))); // NOI18N
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 15)); // NOI18N
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/usuarioo.png"))); // NOI18N
jLabel2.setText("Usuario:");
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 15)); // NOI18N
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/contraseña.png"))); // NOI18N
jLabel4.setText("Contraseña:");
txtContrasena.setFont(new java.awt.Font("Tahoma", 0, 17)); // NOI18N
txtContrasena.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
txtContrasena.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtContrasenaActionPerformed(evt);
}
});
txtContrasena.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtContrasenaKeyPressed(evt);
}
});
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 15)); // NOI18N
jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/rolEmpleado.png"))); // NOI18N
jLabel5.setText("Rol:");
jComboBoxRol.setFont(new java.awt.Font("Tahoma", 0, 17)); // NOI18N
jComboBoxRol.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Administrador" }));
jComboBoxRol.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
textFieldUsuario.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textFieldUsuarioActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(23, 23, 23)
.addComponent(txtContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel5))
.addGap(49, 49, 49)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jComboBoxRol, 0, 200, Short.MAX_VALUE)
.addComponent(textFieldUsuario))))
.addContainerGap(37, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jComboBoxRol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(textFieldUsuario)))
.addGap(19, 19, 19)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(34, Short.MAX_VALUE))
);
jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/medico.png"))); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 626, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(160, 160, 160)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(195, 195, 195)
.addComponent(btnIngresar, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 626, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6))))))
.addContainerGap(29, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel1)
.addGap(11, 11, 11)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnIngresar)
.addComponent(btnCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(27, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed
// TODO add your handling code here:
Usuario usuario = new Usuario();
String sql = "SELECT * FROM Usuarios WHERE Nombre = ? and Contraseña = ?";
ResultSet rs;
Conexion conexion = new Conexion();
Connection con = conexion.Conectar();
System.out.print(con);
//new PantallaPrincipal().setVisible(true);
//this.dispose();
try {
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, textFieldUsuario.getText());
pst.setString(2, usuario.MD5(txtContrasena.getText()));
rs = pst.executeQuery();
if (rs.next()){
//JOptionPane.showMessageDialog(null, "Acceso Permitido");
new PantallaPrincipal().setVisible(true);
this.dispose();
} else{
JOptionPane.showMessageDialog(null, "Acceso Denegado");}
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnIngresarActionPerformed
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
dispose();
}//GEN-LAST:event_btnCancelarActionPerformed
private void txtContrasenaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtContrasenaKeyPressed
// TODO add your handling code here:
}//GEN-LAST:event_txtContrasenaKeyPressed
private void textFieldUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textFieldUsuarioActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_textFieldUsuarioActionPerformed
private void txtContrasenaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtContrasenaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtContrasenaActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnIngresar;
private javax.swing.JComboBox<String> jComboBoxRol;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JTextField textFieldUsuario;
private javax.swing.JPasswordField txtContrasena;
// End of variables declaration//GEN-END:variables
}
| 50.392857 | 249 | 0.642629 |
814e7c74165cc76067ad0ba0d76e28365366caf5 | 948 | package de.peeeq.eclipsewurstplugin.editor;
import org.eclipse.core.filebuffers.IDocumentSetupParticipant;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentExtension3;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.rules.FastPartitioner;
import de.peeeq.eclipsewurstplugin.WurstPlugin;
import de.peeeq.eclipsewurstplugin.WurstConstants;
public class WurstDocumentSetupParticipant implements IDocumentSetupParticipant {
@Override
public void setup(IDocument document) {
if (document instanceof IDocumentExtension3) {
IDocumentExtension3 extension3= (IDocumentExtension3) document;
IDocumentPartitioner partitioner= new FastPartitioner(WurstPlugin.getDefault().scanners().wurstPartitionScanner(), WurstConstants.PARTITION_TYPES);
extension3.setDocumentPartitioner(WurstConstants.WURST_PARTITIONING, partitioner);
partitioner.connect(document);
}
}
} | 39.5 | 151 | 0.831224 |
6097bd85bf63e2937beab1be03bed74fea2c8a3f | 2,588 | package org.aidework.core.object;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.aidework.core.constant.AtomicType;
/**
* 类型转换器
* 主要用于pojo对象中各个层次的业务对象相互转换
* 简单属性的转换
*
*
* @author Caysen
*
* @date 2018年5月16日
*
*/
public class TypeConvertor {
public static <S,T> T convert(S obj,Class<T> target){
if(obj==null||target==null){
return null;
}
/**
* 存储类型中的属性信息
*/
Field[] targetField=target.getDeclaredFields();
Field[] sourceField=obj.getClass().getDeclaredFields();
List<Field> field=new ArrayList<>();
boolean flag=false;
/**
* 判断两个类中能够有效转换的类属性
*/
for(Field tTemp:targetField){
for(Field sTemp:sourceField){
if(sTemp.getName().equals(tTemp.getName())&&
sTemp.getType().getName().equals(tTemp.getType().getName())){
flag=true;
break;
}
}
if(flag){
field.add(tTemp);
flag=false;
}
}
/**
* 实例化需要返回的对象
*/
T result=null;
try {
result=target.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Class<?> clazz=null;
String methodName;
for(Field temp:field){
/**
* 判断是否为boolean类型
*/
if(temp.getType().getName().equals("boolean")){
methodName="is"+uppercase(temp.getName());
}else{
methodName="get"+uppercase(temp.getName());
}
try {
Method sourceMethod=obj.getClass().getMethod(methodName);
Method resultMethod=null;
if(AtomicType.contain(temp.getType().getName())){
clazz=AtomicType.getAtomicClass(temp.getType().getName());
}else{
try {
clazz=Class.forName(temp.getType().getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
resultMethod = target.getMethod("set"+uppercase(temp.getName()),clazz);
S source=(S)obj;
resultMethod.invoke(result, sourceMethod.invoke(source));
} catch (NoSuchMethodException e) {
System.out.println("Not found the method named "+methodName);
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return result;
}
private static String uppercase(String str){
return str.substring(0,1).toUpperCase()+str.substring(1,str.length());
}
}
| 22.902655 | 75 | 0.656878 |
bd537e1776efc59ba531c9c98c54de15874100e8 | 86 | package com.snet;
public interface BiFactory<P, M, N> {
P create(M obj0, N obj1);
}
| 14.333333 | 37 | 0.674419 |
0f9addcac267e0647e7b3d69be7006f0b4aa77b3 | 2,152 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.management.internal.configuration.functions;
import java.io.IOException;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.distributed.internal.ClusterConfigurationService;
import org.apache.geode.distributed.internal.InternalLocator;
import org.apache.geode.internal.cache.execute.InternalFunction;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.management.internal.configuration.messages.ConfigurationResponse;
public class GetClusterConfigurationFunction implements InternalFunction {
private static final Logger logger = LogService.getLogger();
@Override
public void execute(FunctionContext context) {
ClusterConfigurationService clusterConfigurationService =
InternalLocator.getLocator().getSharedConfiguration();
Set<String> groups = (Set<String>) context.getArguments();
logger.info("Received request for configuration : {}", groups);
try {
ConfigurationResponse response =
clusterConfigurationService.createConfigurationResponse(groups);
context.getResultSender().lastResult(response);
} catch (IOException e) {
logger.error("Unable to retrieve the cluster configuration", e);
context.getResultSender().lastResult(e);
}
}
}
| 41.384615 | 100 | 0.779275 |
56d5c43ca655670a59e2bda1d6257393d7a14556 | 659 | package io.github.tslamic.prem;
final class Constant {
private Constant() {
throw new AssertionError();
}
static final String RESPONSE_CODE = "RESPONSE_CODE";
static final String RESPONSE_DETAILS_LIST = "DETAILS_LIST";
static final String RESPONSE_BUY_INTENT = "BUY_INTENT";
static final String RESPONSE_PURCHASE_DATA = "INAPP_PURCHASE_DATA";
static final String RESPONSE_SIGNATURE = "INAPP_DATA_SIGNATURE";
static final String RESPONSE_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST";
static final String REQUEST_ITEM_ID_LIST = "ITEM_ID_LIST";
static final String BILLING_TYPE = "inapp";
static final int BILLING_RESPONSE_RESULT_OK = 0;
}
| 36.611111 | 70 | 0.783005 |
a05936ecc980f94119ebf242637bc20e9b220866 | 3,386 | package alien4cloud.security.users.rest;
import alien4cloud.security.users.JwtTokenService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;
/**
* A filter that checks if a JWT authentication token is present in the header. If found, it's verified.
*/
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends GenericFilterBean {
private static final String BEARER = "Bearer";
@Autowired
private JwtTokenService jwtTokenService;
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
// Assume we have only one Authorization header value
final Optional<String> token = Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION));
Authentication authentication;
boolean securityContextSet = false;
if(token.isPresent() && token.get().startsWith(BEARER)) {
if (logger.isDebugEnabled()) {
logger.debug("A Authorization header was found, containing a Bearer, JWT auth is required !");
}
String bearerToken = token.get().substring(BEARER.length()+1);
try {
Jws<Claims> claims = jwtTokenService.validateJwtToken(bearerToken);
authentication = jwtTokenService.buildAuthenticationFromClaim(claims);
SecurityContextHolder.getContext().setAuthentication(authentication);
securityContextSet = true;
if (logger.isDebugEnabled()) {
logger.debug("JWT authentication successfull");
}
} catch (ExpiredJwtException exception) {
if (logger.isDebugEnabled()) {
logger.debug("JWT token expired", exception);
}
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "error.jwt.expired");
return;
} catch (JwtException exception) {
if (logger.isDebugEnabled()) {
logger.debug("JWT authentication failed", exception);
}
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "error.jwt.invalid");
return;
}
}
chain.doFilter(servletRequest, servletResponse);
// if (securityContextSet) {
// SecurityContextHolder.getContext().setAuthentication(null);
// }
}
}
| 38.91954 | 146 | 0.695511 |
185f01db9b455036c3ebf3d8abf721a56c82754d | 239 | package de.rnd7.calexport;
public class EventParseRuntimeException extends RuntimeException {
private static final long serialVersionUID = 1073130188967714643L;
public EventParseRuntimeException(final Throwable t) {
super(t);
}
}
| 19.916667 | 67 | 0.807531 |
61436eeaec26f364e79a581f77c83a7160546465 | 11,370 | package com.planet_ink.coffee_mud.Abilities.Archon;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2004-2022 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Archon_Multiwatch extends ArchonSkill
{
@Override
public String ID()
{
return "Archon_Multiwatch";
}
private final static String localizedName = CMLib.lang().L("Multiwatch");
@Override
public String name()
{
return localizedName;
}
@Override
public String displayText()
{
return "";
}
@Override
protected int canAffectCode()
{
return CAN_MOBS;
}
@Override
protected int canTargetCode()
{
return 0;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_INDIFFERENT;
}
private static final String[] triggerStrings = I(new String[] { "MULTIWATCH" });
@Override
public String[] triggerStrings()
{
return triggerStrings;
}
@Override
public int classificationCode()
{
return Ability.ACODE_SKILL | Ability.DOMAIN_ARCHON;
}
@Override
public int usageType()
{
return USAGE_MOVEMENT;
}
public static Hashtable<MOB, int[]> DATA = new Hashtable<MOB, int[]>();
public static Hashtable<String, List<MOB>> IPS = new Hashtable<String, List<MOB>>();
public static final int DATA_GOODSPEECH=0;
public static final int DATA_ANYSPEECH=1;
public static final int DATA_DIRSPEECH=2;
public static final int DATA_GOODSOCIAL=3;
public static final int DATA_ANYSOCIAL=4;
public static final int DATA_DIRSOCIAL=5;
public static final int DATA_TYPEDCOMMAND=6;
public static final int DATA_SYNCHROFOUND=7;
public static final int DATA_ORDER=8;
public static final int DATA_TOTAL=10;
public String lastCommand=null;
public boolean nonIPnonMonsterWithMe(final MOB me)
{
if((me.location()!=null)&&(me.session()!=null))
{
final Room R=me.location();
for(int i=0;i<R.numInhabitants();i++)
{
final MOB M=R.fetchInhabitant(i);
if((M==null)||(M==me))
continue;
if((M.session()!=null)&&(M.session().getAddress().equals(me.session().getAddress())))
return true;
}
}
return false;
}
@Override
public void executeMsg(final Environmental host, final CMMsg msg)
{
super.executeMsg(host,msg);
if((affected instanceof MOB)&&(msg.amISource((MOB)affected)))
{
if(!DATA.containsKey(msg.source()))
DATA.put(msg.source(),new int[DATA_TOTAL]);
final int[] data=DATA.get(msg.source());
if(data==null)
return;
if(msg.tool() instanceof Social)
{
if(nonIPnonMonsterWithMe(msg.source()))
data[DATA_GOODSOCIAL]++;
if((msg.target() instanceof MOB)
&&(!((MOB)msg.target()).isMonster()))
data[DATA_DIRSOCIAL]++;
data[DATA_ANYSOCIAL]++;
}
else
switch(msg.sourceMinor())
{
case CMMsg.TYP_SPEAK:
if((msg.othersMessage()!=null)
&&(msg.sourceMessage()!=null)
&&(msg.othersMinor()==msg.sourceMinor())
&&(msg.source().location()!=null)
&&(msg.source().session()!=null))
{
if(msg.sourceMessage().indexOf("order(s)")>0)
{
if((msg.target() instanceof MOB)
&&(((MOB)msg.target()).session()!=null)
&&(((MOB)msg.target()).session().getAddress().equals(msg.source().session().getAddress())))
data[DATA_ORDER]++;
}
else
{
if(nonIPnonMonsterWithMe(msg.source()))
data[DATA_GOODSPEECH]++;
if((msg.target() instanceof MOB)
&&(!((MOB)msg.target()).isMonster()))
data[DATA_DIRSPEECH]++;
data[DATA_ANYSPEECH]++;
}
}
break;
}
}
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
if(!super.tick(ticking,tickID))
return false;
if((tickID==Tickable.TICKID_MOB)
&&(affected instanceof MOB))
{
final MOB mob=(MOB)affected;
if(!DATA.containsKey(mob))
DATA.put(mob,new int[DATA_TOTAL]);
final int[] data=DATA.get(mob);
if((mob.session()!=null)&&(mob.session().getPreviousCMD()!=null))
{
if((lastCommand!=null)
&&(!CMParms.combine(mob.session().getPreviousCMD(),0).equals(lastCommand)))
{
data[DATA_TYPEDCOMMAND]++;
List<MOB> V=null;
if(mob.session().getAddress()!=null)
V=IPS.get(mob.session().getAddress());
if(V!=null)
for(int v=0;v<V.size();v++)
{
final MOB M=V.get(v);
if(M==mob)
continue;
if(M.session()==null)
continue;
if(!CMLib.flags().isInTheGame(M,true))
continue;
final String hisLastCmd=CMParms.combine(mob.session().getPreviousCMD(),0);
final Archon_Multiwatch A=(Archon_Multiwatch)M.fetchEffect(ID());
if(A!=null)
{
if((A.lastCommand!=null)&&(!A.lastCommand.equals(hisLastCmd)))
data[DATA_SYNCHROFOUND]++;
break;
}
}
}
lastCommand=CMParms.combine(mob.session().getPreviousCMD(),0);
}
}
return true;
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
if(CMParms.combine(commands,0).equalsIgnoreCase("auto"))
{
DATA.clear();
IPS.clear();
final Hashtable<String,List<MOB>> ipes=new Hashtable<String,List<MOB>>();
for(final Session S : CMLib.sessions().localOnlineIterable())
{
if((S.getAddress().length()>0)
&&(S.mob()!=null))
{
List<MOB> V=ipes.get(S.getAddress());
if(V==null)
{
V=new Vector<MOB>();
ipes.put(S.getAddress(),V);
}
if(!V.contains(S.mob()))
V.add(S.mob());
}
}
final StringBuffer rpt=new StringBuffer("");
for(final Enumeration<String> e=ipes.keys();e.hasMoreElements();)
{
final String addr=e.nextElement();
final List<MOB> names=ipes.get(addr);
if(names.size()>1)
{
IPS.put(addr,names);
rpt.append("Watch #"+(IPS.size())+" added: ");
for(int n=0;n<names.size();n++)
{
final MOB MN=names.get(n);
if(MN.fetchEffect(ID())==null)
{
final Ability A=(Ability)copyOf();
MN.addNonUninvokableEffect(A);
A.setSavable(false);
}
rpt.append(MN.Name()+" ");
}
rpt.append("\n\r");
}
}
if(rpt.length()==0)
rpt.append("No users with duplicate IDs found. Try MULTIWATCH ADD name1 name2 ... ");
mob.tell(rpt.toString());
return true;
}
else
if(CMParms.combine(commands,0).equalsIgnoreCase("stop"))
{
boolean foundLegacy=false;
for(final Session S : CMLib.sessions().localOnlineIterable())
{
if((S!=null)&&(S.mob()!=null)&&(S.mob().fetchEffect(ID())!=null))
{
foundLegacy=true;
break;
}
}
if((DATA.size()==0)&&(IPS.size()==0)&&(!foundLegacy))
{
mob.tell(L("Multiwatch is already off."));
return false;
}
for(final Enumeration<List<MOB>> e=IPS.elements();e.hasMoreElements();)
{
final List<MOB> V=e.nextElement();
for(int v=0;v<V.size();v++)
{
final MOB M=V.get(v);
final Ability A=M.fetchEffect(ID());
if(A!=null)
M.delEffect(A);
}
}
for(final Session S : CMLib.sessions().localOnlineIterable())
{
if((S!=null)&&(S.mob()!=null))
{
final MOB M=S.mob();
final Ability A=M.fetchEffect(ID());
if(A!=null)
M.delEffect(A);
}
}
mob.tell(L("Multiplay watcher is now turned off."));
DATA.clear();
IPS.clear();
return true;
}
else
if((commands.size()>1)&&(commands.get(0)).equalsIgnoreCase("add"))
{
final List<MOB> V=new ArrayList<MOB>();
for(int i=1;i<commands.size();i++)
{
final String name=commands.get(i);
final MOB M=CMLib.players().getPlayerAllHosts(name);
if((M.session()!=null)&&(CMLib.flags().isInTheGame(M,true)))
V.add(M);
else
mob.tell(L("'@x1' is not online.",name));
}
if(V.size()>1)
{
for(int n=0;n<V.size();n++)
{
final MOB MN=V.get(n);
if(MN.fetchEffect(ID())==null)
{
final Ability A=(Ability)copyOf();
MN.addNonUninvokableEffect(A);
A.setSavable(false);
}
}
IPS.put("MANUAL"+(IPS.size()+1),V);
mob.tell(L("Manual Watch #@x1 added.",""+IPS.size()));
}
return true;
}
else
if((commands.size()==0)&&(DATA.size()>0)&&(IPS.size()>0))
{
final StringBuffer report=new StringBuffer("");
for(final Enumeration<String> e=IPS.keys();e.hasMoreElements();)
{
final String key=e.nextElement();
int sync=0;
final List<MOB> V=IPS.get(key);
for(int v=0;v<V.size();v++)
{
final MOB M=V.get(v);
final int data[]=DATA.get(M);
if(data!=null)
sync+=data[DATA_SYNCHROFOUND];
}
report.append("^x"+key+"^?^., Syncs: "+sync+"\n\r");
report.append(CMStrings.padRight(L("Name"),25)
+CMStrings.padRight(L("Speech"),15)
+CMStrings.padRight(L("Socials"),15)
+CMStrings.padRight(L("CMD"),10)
+CMStrings.padRight(L("ORDERS"),10)
+"\n\r");
for(int v=0;v<V.size();v++)
{
final MOB M=V.get(v);
int data[]=DATA.get(M);
if(data==null)
data=new int[DATA_TOTAL];
report.append(CMStrings.padRight(M.Name(),25));
report.append(CMStrings.padRight(data[DATA_GOODSPEECH]
+"/"+data[DATA_DIRSPEECH]
+"/"+data[DATA_ANYSPEECH],15));
report.append(CMStrings.padRight(data[DATA_GOODSOCIAL]
+"/"+data[DATA_DIRSOCIAL]
+"/"+data[DATA_ANYSOCIAL],15));
report.append(CMStrings.padRight(data[DATA_TYPEDCOMMAND]+"",10));
report.append(CMStrings.padRight(data[DATA_ORDER]+"",10));
report.append("\n\r");
}
report.append("\n\r");
}
mob.tell(report.toString());
return true;
}
else
{
mob.tell(L("Try MULTIWATCH AUTO, MULTIWATCH STOP, or MULTIWATCH ADD name1 name2.."));
return false;
}
}
}
| 27.731707 | 134 | 0.612665 |
25a7264c53db9b6bf0e28c20406393f13c6cb183 | 8,872 | package game.level;
import game.staticData.Constants;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class TerrainGenerator {
public static class Tuple<X, Y> {
private final X x;
private final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Tuple)) {
return false;
}
Tuple<X, Y> other_ = (Tuple<X, Y>) other;
// this may cause NPE if nulls are valid values for x or y. The logic may be improved to handle nulls properly, if needed.
return other_.x.equals(this.x) && other_.y.equals(this.y);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((x == null) ? 0 : x.hashCode());
result = prime * result + ((y == null) ? 0 : y.hashCode());
return result;
}
}
private static final Random rng = new Random();
private static int randomLevelWidth = Constants.STARTING_LEVEL_WIDTH;
private static int randomLevelHeight = Constants.STARTING_LEVEL_HEIGHT;
private static int randomLevelDumbZCount = Constants.DUMB_ZOMBIE_SPAWN_NUM;
private static int randomLevelSmartZCount = Constants.SMART_ZOMBIE_SPAWN_NUM;
private static int playerStartX;
private static int playerStartY;
private static final Integer[] allObjects = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 4};
private static final Integer[] impassableObj = {3, 5};
private static final Integer[] destructibleObj = {4};
private static final Integer[] passableObj = {0, 1, 2}; //0 - ground ; 1 - Start; 2- Exit
private static Integer[][] grid;
private static Integer[][] gridTraced;
private static Set<Tuple<Integer, Integer>> passableArea = new HashSet<>();
public static int getPlayerStartX() {
return playerStartX;
}
public static void setPlayerStartX(int startX) {
playerStartX = startX;
}
public static int getPlayerStartY() {
return playerStartY;
}
public static void setPlayerStartY(int startY) {
playerStartY = startY;
}
public static int getRandomLevelWidth() {
return randomLevelWidth;
}
private static void setRandomLevelWidth(int randomLevelWidth) {
TerrainGenerator.randomLevelWidth = randomLevelWidth;
}
public static void changeRandomLevelWidth(int amount) {
TerrainGenerator.setRandomLevelWidth(getRandomLevelWidth() + amount);
}
public static int getRandomLevelHeight() {
return randomLevelHeight;
}
private static void setRandomLevelHeight(int randomLevelHeight) {
TerrainGenerator.randomLevelHeight = randomLevelHeight;
}
public static void changeRandomLevelHeight(int amount) {
TerrainGenerator.setRandomLevelHeight(getRandomLevelHeight() + amount);
}
public static int getRandomLevelDumbZCount() {
return randomLevelDumbZCount;
}
private static void setRandomLevelDumbZCount(int randomLevelDumbZCount) {
TerrainGenerator.randomLevelDumbZCount = randomLevelDumbZCount;
}
public static void changeRandomLevelDumbZCount(){
TerrainGenerator.setRandomLevelDumbZCount((int)Math.ceil(getRandomLevelDumbZCount()*Constants.ENEMY_SPAWN_INCREASE_FACTOR));
}
public static int getRandomLevelSmartZCount() {
return randomLevelSmartZCount;
}
private static void setRandomLevelSmartZCount(int randomLevelSmartZCount) {
TerrainGenerator.randomLevelSmartZCount = randomLevelSmartZCount;
}
public static void changeRandomLevelSmartZCount(){
TerrainGenerator.setRandomLevelSmartZCount((int)Math.ceil(getRandomLevelSmartZCount()*Constants.ENEMY_SPAWN_INCREASE_FACTOR));
}
public static String[] generateNewLevel() {
generateGrid();
while (!findConnectedAreas()) {
generateGrid();
}
return generateLevelData();
}
public static Integer[] getPassableObj() {
return passableObj;
}
public static Set<Tuple<Integer, Integer>> getPassableArea() {
return passableArea;
}
private static Integer[][] copyGrid(Integer[][] grid) {
Integer[][] copiedGrid = new Integer[grid.length][grid[0].length];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
copiedGrid[i][j] = grid[i][j];
}
}
return copiedGrid;
}
private static boolean findConnectedAreas() {
int exitRow = 0;
int exitCol = 0;
for (int row = 0; row < gridTraced.length; row++) {
for (int col = 0; col < gridTraced[0].length; col++) {
//Finds the area that is connected to the start cell
if (gridTraced[row][col] == 1) {
setPlayerStartX(col);
setPlayerStartY(row);
tryDirection(row, col - 1, 'L');
tryDirection(row - 1, col, 'U');
tryDirection(row, col + 1, 'R');
tryDirection(row + 1, col, 'D');
}
if (grid[row][col] == 2) {
exitCol = col;
exitRow = row;
}
}
}
return passableArea.contains(new Tuple<>(exitRow, exitCol));
}
private static void tryDirection(int row, int col, char direction) {
if (!inRange(row, col)) {
return;
}
//TODO check if block is destructible
if (Arrays.asList(passableObj).contains(gridTraced[row][col]) ||
Arrays.asList(destructibleObj).contains(gridTraced[row][col])) {
passableArea.add(new Tuple<>(row, col));
//-1 is any number not a passable or impassable object so as not to cause
// stack overflow or to terminate the search prematurely
gridTraced[row][col] = -1;
tryDirection(row, col - 1, 'L'); // left
tryDirection(row - 1, col, 'U'); // up
tryDirection(row, col + 1, 'R'); // right
tryDirection(row + 1, col, 'D'); // down
}
}
private static boolean inRange(int row, int col) {
boolean rowInRange = row >= 0 && row < gridTraced.length;
boolean colInRange = col >= 0 && col < gridTraced[0].length;
return rowInRange && colInRange;
}
private static void printLabyrinth() {
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[0].length; col++) {
System.out.printf("%d ", grid[row][col]);
}
System.out.println();
}
}
private static void printTracedLabyrinth() {
for (int row = 0; row < gridTraced.length; row++) {
for (int col = 0; col < gridTraced[0].length; col++) {
System.out.printf("%d ", gridTraced[row][col]);
}
System.out.println();
}
}
private static void generateGrid() {
grid = new Integer[randomLevelHeight][randomLevelWidth];
for (int row = 1; row < grid.length - 1; row++) {
for (int col = 1; col < grid[0].length - 1; col++) {
grid[row][col] = allObjects[rng.nextInt(allObjects.length)];
}
}
for (int col = 0; col < grid[0].length; col++) {
grid[0][col] = 3;
grid[randomLevelHeight - 1][col] = 3;
}
for (int row = 0; row < grid.length; row++) {
grid[row][0] = 3;
grid[row][randomLevelWidth - 1] = 3;
}
//place entry and exit point
//Col position starts at 3/4ths to the right.
int endPosCol = rng.nextInt(randomLevelWidth / 2 - 2) + 1 + randomLevelWidth / 2;
int endPosRow = rng.nextInt(randomLevelHeight - 2) + 1;
grid[1][1] = 1;
grid[endPosRow][endPosCol] = 2;
passableArea.clear();
gridTraced = copyGrid(grid);
}
private static String[] generateLevelData() {
String[] level = new String[getRandomLevelHeight()];
for (int i = 0; i < getRandomLevelHeight(); i++) {
StringBuilder line = new StringBuilder();
for (Integer num : grid[i]) {
line.append(num.toString() + " ");
}
level[i] = line.toString().trim();
}
return level;
}
}
| 32.144928 | 134 | 0.576533 |
a9887cfd8f15bd56032fc659fc7cdc0549011919 | 1,734 | package fpt;
import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Main {
public static void main(String[] args) {
try {
String outFile;
VCSolver solver = null;
String pathToGraph = args[0];
outFile = args[1];
solver = new AdvancedSolver(pathToGraph);
System.out.println("Calculating vertex cover..");
PartialSolution vertexCover = solver.getVC();
System.out.println("Found VC with size: " + vertexCover.getCurrentVC().size());
writeVCToFile(vertexCover, outFile);
} catch (IOException | IndexOutOfBoundsException e) {
handleError(e);
}
}
private static void writeVCToFile(PartialSolution vertexCover, String outFile) throws IOException {
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outFile), StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
writer.write(Integer.toString(vertexCover.getCurrentVC().size()));
writer.newLine();
for (Integer node : vertexCover.getCurrentVC()) {
writer.write(node.toString());
writer.newLine();
}
writer.flush();
}
}
private static void handleError(Exception e) {
System.out.println("Error, use graph file as first argument and output file as second argument");
System.err.println(e);
System.exit(1);
}
}
| 34.68 | 136 | 0.643022 |
1c3fe5f7b3f72609934f2ba49e46d6763f025708 | 1,160 | package com.odero.bigbeats;
public class Category {
private String categoryName, categoryDescription, numberOfSongs;
private int imageId;
public Category(String categoryName, String categoryDescription, String numberOfSongs, int imageId) {
this.categoryName = categoryName;
this.categoryDescription = categoryDescription;
this.numberOfSongs = numberOfSongs;
this.imageId = imageId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryDescription() {
return categoryDescription;
}
public void setCategoryDescription(String categoryDescription) {
this.categoryDescription = categoryDescription;
}
public String getNumberOfSongs() {
return numberOfSongs;
}
public void setNumberOfSongs(String numberOfSongs) {
this.numberOfSongs = numberOfSongs;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
}
| 25.217391 | 105 | 0.686207 |
18e904729dcc852b4b4771c2c2ca6b552c2116f4 | 8,860 | /*
* Copyright 2015-2017 Austin Keener & Michael Ritter & Florian Spieß
*
* 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 net.dv8tion.jda.client.managers;
import net.dv8tion.jda.client.entities.Application;
import net.dv8tion.jda.client.entities.impl.ApplicationImpl;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.entities.Icon;
import net.dv8tion.jda.core.requests.RestAction;
import java.util.List;
import javax.annotation.CheckReturnValue;
/**
* Facade for an {@link net.dv8tion.jda.client.managers.ApplicationManagerUpdatable ApplicationManagerUpdatable} instance.
* <br>Simplifies managing flow for convenience.
*
* <p>This decoration allows to modify a single field by automatically building an update {@link net.dv8tion.jda.core.requests.RestAction RestAction}
*
* @since 3.0
* @author Aljoscha Grebe
*/
public class ApplicationManager
{
private final ApplicationManagerUpdatable updatable;
public ApplicationManager(final ApplicationImpl application)
{
this.updatable = new ApplicationManagerUpdatable(application);
}
/**
* The {@link net.dv8tion.jda.client.entities.Application Application} that will
* be modified by this Manager instance
*
* @return The {@link net.dv8tion.jda.client.entities.Application Application}
*/
public Application getApplication()
{
return this.updatable.getApplication();
}
/**
* The {@link net.dv8tion.jda.core.JDA JDA} instance of this Manager
*
* @return the corresponding JDA instance
*/
public JDA getJDA()
{
return this.updatable.getJDA();
}
/**
* Sets the <b><u>description</u></b> of the selected {@link net.dv8tion.jda.client.entities.Application Application}.
* <br>Wraps {@link net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getDescriptionField() ApplicationManagerUpdatable#getDescriptionField()}.
*
* <p>A description <b>must not</b> be than 400 characters long!
*
* @param description
* The new description for the selected {@link net.dv8tion.jda.client.entities.Application Application}
*
* @throws IllegalArgumentException
* If the provided description is more than 400 characters long
*
* @return {@link net.dv8tion.jda.core.requests.RestAction}
* <br>Update RestAction from {@link ApplicationManagerUpdatable#update() #update()}
*
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getDescriptionField()
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#update()
*/
@CheckReturnValue
public RestAction<Void> setDescription(final String description)
{
return this.updatable.getDescriptionField().setValue(description).update();
}
/**
* Sets the <b><u>code grant state</u></b> of the selected {@link net.dv8tion.jda.client.entities.Application Application's} bot.
* <br>Wraps {@link net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getDoesBotRequireCodeGrantField() ApplicationManagerUpdatable#getDoesBotRequireCodeGrantField()}.
*
* @param requireCodeGrant
* The new state for the selected {@link net.dv8tion.jda.client.entities.Application Application's} bot
*
* @return {@link net.dv8tion.jda.core.requests.RestAction}
* <br>Update RestAction from {@link ApplicationManagerUpdatable#update() #update()}
*
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getDoesBotRequireCodeGrantField()
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#update()
*/
@CheckReturnValue
public RestAction<Void> setDoesBotRequireCodeGrant(final boolean requireCodeGrant)
{
return this.updatable.getDoesBotRequireCodeGrantField().setValue(requireCodeGrant).update();
}
/**
* Sets the <b><u>icon</u></b> of the selected {@link net.dv8tion.jda.client.entities.Application Application}.
* <br>Wraps {@link net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getIconField() ApplicationManagerUpdatable#getIconField()}.
*
* @param icon
* The new {@link net.dv8tion.jda.core.entities.Icon Icon}
* for the selected {@link net.dv8tion.jda.client.entities.Application Application}
*
* @return {@link net.dv8tion.jda.core.requests.RestAction}
* <br>Update RestAction from {@link ApplicationManagerUpdatable#update() #update()}
*
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getIconField()
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#update()
*/
@CheckReturnValue
public RestAction<Void> setIcon(final Icon icon)
{
return this.updatable.getIconField().setValue(icon).update();
}
/**
* Sets the <b><u>public state</u></b> of the selected {@link net.dv8tion.jda.client.entities.Application Application's} bot.
* <br>Wraps {@link net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getIsBotPublicField() ApplicationManagerUpdatable#getIsBotPublicField()}.
*
* @param botPublic
* The new state for the selected {@link net.dv8tion.jda.client.entities.Application Application's} bot
*
* @return {@link net.dv8tion.jda.core.requests.RestAction}
* <br>Update RestAction from {@link ApplicationManagerUpdatable#update() #update()}
*
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getIsBotPublicField()
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#update()
*/
@CheckReturnValue
public RestAction<Void> setIsBotPublic(final boolean botPublic)
{
return this.updatable.getIsBotPublicField().setValue(botPublic).update();
}
/**
* Sets the <b><u>name</u></b> of the selected {@link net.dv8tion.jda.client.entities.Application Application}.
* <br>Wraps {@link net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getNameField() ApplicationManagerUpdatable#getNameField()}.
*
* <p>A name <b>must not</b> be {@code null} nor less than 2 characters or more than 32 characters long!
*
* @param name
* The new name for the selected {@link net.dv8tion.jda.client.entities.Application Application}
*
* @throws IllegalArgumentException
* If the provided name is {@code null}, less than 2 or more than 32 characters long
*
* @return {@link net.dv8tion.jda.core.requests.RestAction}
* <br>Update RestAction from {@link ApplicationManagerUpdatable#update() #update()}
*
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getNameField()
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#update()
*/
@CheckReturnValue
public RestAction<Void> setName(final String name)
{
return this.updatable.getNameField().setValue(name).update();
}
/**
* Sets the <b><u>redirect uris</u></b> of the selected {@link net.dv8tion.jda.client.entities.Application Application}.
* <br>Wraps {@link net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getRedirectUrisField() ApplicationManagerUpdatable#getRedirectUrisField()}.
*
* <p>The {@link java.util.List List} as well as all redirect uris <b>must not</b> be {@code null}!
*
* @param redirectUris
* The new redirect uris
* for the selected {@link net.dv8tion.jda.client.entities.Application Application}
*
* @throws IllegalArgumentException
* If either the provided {@link java.util.List List} or one of the uris is {@code null}
*
* @return {@link net.dv8tion.jda.core.requests.RestAction}
* <br>Update RestAction from {@link ApplicationManagerUpdatable#update() #update()}
*
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#getIconField()
* @see net.dv8tion.jda.client.managers.ApplicationManagerUpdatable#update()
*/
@CheckReturnValue
public RestAction<Void> setRedirectUris(final List<String> redirectUris)
{
return this.updatable.getRedirectUrisField().setValue(redirectUris).update();
}
}
| 44.747475 | 181 | 0.701354 |
dddc2267afad60dfc7e85255db4ba001fc31b624 | 4,714 | package org.drools.integrationtests;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.drools.Cheese;
import org.drools.Person;
import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.WorkingMemory;
import org.drools.compiler.DrlParser;
import org.drools.compiler.DroolsParserException;
import org.drools.compiler.PackageBuilder;
import org.drools.lang.descr.PackageDescr;
import org.drools.rule.Package;
import org.drools.util.DateUtils;
import org.mvel.MVEL;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class MVELTest extends TestCase {
public void testHelloWorld() throws Exception {
// read in the source
final Reader reader = new InputStreamReader( getClass().getResourceAsStream( "test_mvel.drl" ) );
RuleBase ruleBase = loadRuleBase( reader );
final WorkingMemory workingMemory = ruleBase.newStatefulSession();
final List list = new ArrayList();
workingMemory.setGlobal( "list",
list );
final List list2 = new ArrayList();
workingMemory.setGlobal( "list2",
list2 );
Cheese c = new Cheese("stilton", 10) ;
workingMemory.insert( c);
workingMemory.fireAllRules();
assertEquals( 2, list.size() );
assertEquals( new Integer(30), list.get(0));
assertEquals( new Integer(22), list.get(1));
assertEquals( "hello world", list2.get(0));
Date dt = DateUtils.parseDate( "10-Jul-1974" );
assertEquals(dt, c.getUsedBy());
}
public void testLocalVariableMVELConsequence() throws Exception {
final PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_LocalVariableMVELConsequence.drl" ) ) );
final Package pkg = builder.getPackage();
RuleBase ruleBase = getRuleBase();
ruleBase.addPackage( pkg );
ruleBase = SerializationHelper.serializeObject(ruleBase);
final WorkingMemory workingMemory = ruleBase.newStatefulSession();
final List list = new ArrayList();
workingMemory.setGlobal( "results",
list );
workingMemory.insert( new Person( "bob", "stilton" ) );
workingMemory.insert( new Person( "mark", "brie" ) );
try {
workingMemory.fireAllRules();
assertEquals( "should have fired twice",
2,
list.size() );
} catch (Exception e) {
e.printStackTrace();
fail( "Should not raise any exception");
}
}
public void testDuplicateLocalVariableMVELConsequence() throws Exception {
final PackageBuilder builder = new PackageBuilder();
builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_DuplicateLocalVariableMVELConsequence.drl" ) ) );
assertTrue ( builder.hasErrors() );
}
public Object compiledExecute(String ex) {
Serializable compiled = MVEL.compileExpression(ex);
return MVEL.executeExpression(compiled, new Object(), new HashMap());
}
private RuleBase loadRuleBase(final Reader reader) throws IOException,
DroolsParserException,
Exception {
final DrlParser parser = new DrlParser();
final PackageDescr packageDescr = parser.parse( reader );
if ( parser.hasErrors() ) {
Assert.fail( "Error messages in parser, need to sort this our (or else collect error messages)" );
}
// pre build the package
final PackageBuilder builder = new PackageBuilder();
builder.addPackage( packageDescr );
System.out.println( builder.getErrors() );
final Package pkg = builder.getPackage();
// add the package to a rulebase
RuleBase ruleBase = getRuleBase();
ruleBase.addPackage( pkg );
ruleBase = SerializationHelper.serializeObject(ruleBase);
// load up the rulebase
return ruleBase;
}
protected RuleBase getRuleBase() throws Exception {
return RuleBaseFactory.newRuleBase( RuleBase.RETEOO,
null );
}
}
| 35.984733 | 146 | 0.617947 |
be7f5f8d301f01800617947f67699f9d6bc86017 | 1,307 | //This file is automatically generated. DO NOT EDIT!
package com.robotraconteur.testing.TestService3;
import java.util.*;
import com.robotraconteur.*;
public class vector3 implements RRNamedArray
{
public double x;
public double y;
public double z;
public vector3()
{
x = 0.0;
y = 0.0;
z = 0.0;
}
public double[] getNumericArray()
{
double[] a = new double[3];
getNumericArray(a,0);
return a;
}
public void getNumericArray(double[] buffer, int offset)
{
buffer[offset + 0] = x;
buffer[offset + 1] = y;
buffer[offset + 2] = z;
}
public void assignFromNumericArray(double[] buffer, int offset)
{
x = buffer[offset + 0];
y = buffer[offset + 1];
z = buffer[offset + 2];
}
public static double[] getNumericArray(vector3[] s)
{
double[] a = new double[3 * s.length];
getNumericArray(s,a,0);
return a;
}
public static void getNumericArray(vector3[] s, double[] a, int offset)
{
for (int i=0; i<s.length; i++)
{
s[i].getNumericArray(a, offset + 3 * i);
}
}
public static void assignFromNumericArray(vector3[] s, double[] a, int offset)
{
for (int i=0; i<s.length; i++)
{
s[i].assignFromNumericArray(a, offset + 3 * i);
}
}
}
| 23.339286 | 82 | 0.591431 |
5d5078d9b5b6d612a8464aba35c35188e8a73f9a | 540 | package com.aminebag.larjson.configuration.propertyresolver;
import java.lang.reflect.Method;
/**
* @author Amine Bagdouri
*/
public class CamelCasePropertyResolver extends AbstractPropertyResolver {
public CamelCasePropertyResolver(Class<?> rootInterface) {
super(rootInterface);
}
@Override
protected String getAttributeNameInternal(Method getter) {
String getterName = getGetterNameWithoutPrefix(getter);
return Character.toLowerCase(getterName.charAt(0)) + getterName.substring(1);
}
}
| 27 | 85 | 0.748148 |
76647f471c3f209b26c55f9f721a8fe171c202dd | 901 | package com.vanniktech.emoji.sample;
import android.app.Application;
import android.os.StrictMode;
import androidx.appcompat.app.AppCompatDelegate;
import com.squareup.leakcanary.LeakCanary;
import com.vanniktech.emoji.EmojiManager;
import com.vanniktech.emoji.ios.IosEmojiProvider;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO;
public class EmojiApplication extends Application {
@Override public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) {
return;
}
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_AUTO);
EmojiManager.install(new IosEmojiProvider());
if (BuildConfig.DEBUG) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().build());
}
LeakCanary.install(this);
}
}
| 28.15625 | 92 | 0.769145 |
7b77536356ffee48713f828cedc79ac360e17557 | 927 | package de.mari_023.fabric.ae2wtlib;
import appeng.core.AEConfig;
import net.fabricmc.loader.api.FabricLoader;
public class Config {
private static boolean mineMenuChecked, mineMenuPresent;
public static double getPowerMultiplier(double range, boolean isOutOfRange) {
if(isOutOfRange)
return AEConfig.instance().wireless_getDrainRate(528 * getOutOfRangePowerMultiplier());
return AEConfig.instance().wireless_getDrainRate(range);
}
public static double getChargeRate() {
return 8000;
}
public static double WUTChargeRateMultiplier() {
return 1;
}
private static int getOutOfRangePowerMultiplier() {
return 2;
}
public static boolean allowMineMenu() {
if(!mineMenuChecked) mineMenuPresent = FabricLoader.getInstance().isModLoaded("minemenufabric");
mineMenuChecked = true;
return mineMenuPresent;
}
} | 28.090909 | 104 | 0.705502 |
06212520bd1feb6c2d0b5078ce75c336c30e401f | 1,899 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package testModelo;
import java.util.ArrayList;
import modelo.dataPoint;
import modelo.device;
import modelo.deviceControl;
/**
*
* @author michael
*/
public class testDataPoint {
public static void main(String args[]){
ArrayList<device> d = deviceControl.getDevices();
for(int i=0; i< d.size(); i++){
device dev = d.get(i);
System.out.println("Dispositivo: "+dev.getAddress());
ArrayList<dataPoint> points = dev.getDataPoints();
for(int j=0; j< points.size(); j++){
dataPoint p = points.get(j);
System.out.println("PuntoH: "+p.getAddressH()+" - "+(p.getLengthH()+p.getAddressH()-1)+", Largo: "+p.getLengthH());
}
}
int datah[] = {10,20,30,40,50,60,70,80,90,100};
//op1
dataPoint data_point = d.get(0).getDataPointAt(0);
data_point.setDataH(datah);
//op2
d.get(0).getDataPointAt(0).setDataH(datah);
d.get(0).setDataPoint(0, data_point);
//points.get(1).setDataH(datah);
System.out.println(d.get(0).getDataPointAt(0).getDataH(4097));
/*
dataPoint d = new dataPoint(4096,0,10,0);
//int datal[] = {0,1,2,3,4,5,6,7,8,9};
int datah[] = {10,20,30,40,50,60,70,80,90,100};
//d.setDataL(datal);
d.setDataH(datah);
System.out.println(d.getDataH(10));
System.out.println(d.getDataH(15));
System.out.println(d.getDataH(4105));
/*
System.out.println(d.getDataL(2));
System.out.println(d.getDataL(11));
*/
}
}
| 25.662162 | 131 | 0.511848 |
c2e3917c70b310ee616a2bae4de45f8592e472c9 | 2,388 | /*
* 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 com.alibaba.flink.shuffle.coordinator.utils;
import com.alibaba.flink.shuffle.coordinator.worker.ShuffleWorkerGateway;
import com.alibaba.flink.shuffle.coordinator.worker.ShuffleWorkerMetrics;
import com.alibaba.flink.shuffle.core.ids.DataPartitionID;
import com.alibaba.flink.shuffle.core.ids.DataSetID;
import com.alibaba.flink.shuffle.core.ids.InstanceID;
import com.alibaba.flink.shuffle.core.ids.JobID;
import com.alibaba.flink.shuffle.rpc.message.Acknowledge;
import java.util.concurrent.CompletableFuture;
/** A test empty shuffle worker gateway implementation. */
public class EmptyShuffleWorkerGateway implements ShuffleWorkerGateway {
@Override
public void heartbeatFromManager(InstanceID managerID) {}
@Override
public void disconnectManager(Exception cause) {}
@Override
public CompletableFuture<Acknowledge> releaseDataPartition(
JobID jobID, DataSetID dataSetID, DataPartitionID dataPartitionID) {
return CompletableFuture.completedFuture(Acknowledge.get());
}
@Override
public CompletableFuture<Acknowledge> removeReleasedDataPartitionMeta(
JobID jobID, DataSetID dataSetID, DataPartitionID dataPartitionID) {
return CompletableFuture.completedFuture(Acknowledge.get());
}
@Override
public CompletableFuture<ShuffleWorkerMetrics> getWorkerMetrics() {
return CompletableFuture.completedFuture(null);
}
@Override
public String getAddress() {
return "";
}
@Override
public String getHostname() {
return "";
}
}
| 35.641791 | 80 | 0.755444 |
e31a84cacd9651a2d741673ebfa15073219678f5 | 880 | /*
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.authenticate.factory;
import org.dspace.authenticate.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Factory implementation to get services for the authenticate package, use AuthenticateServiceFactory.getInstance()
* to retrieve an implementation
*
* @author kevinvandevelde at atmire.com
*/
public class AuthenticateServiceFactoryImpl extends AuthenticateServiceFactory {
@Autowired(required = true)
private AuthenticationService authenticationService;
@Override
public AuthenticationService getAuthenticationService() {
return authenticationService;
}
}
| 30.344828 | 116 | 0.781818 |
6db7f5d67fa1935942b3136ce9ab7fe4a3faeb80 | 1,057 | package com.guy.login.spring.configuration;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
public class LogIPAddressFilter extends OncePerRequestFilter {
private static final String KEY = "X-IP-ADDRESS";
private static Logger LOGGER = LoggerFactory.getLogger(LogIPAddressFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
ThreadContext.put(KEY, request.getRemoteAddr());
// LOGGER.info("{} : {}",KEY,request.getRemoteAddr());
chain.doFilter(request, response);
ThreadContext.clearAll();
}
}
| 35.233333 | 151 | 0.788079 |
43b5051d466aa7d25d55b674cdcc66c82a064f97 | 925 | package com.example.demo.hospital.domain;
import com.example.demo.member.domain.Member;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Getter
@NoArgsConstructor
public class Hospital {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "hospital_id", nullable = false)
private Long id;
@Column(name = "hospital_name", nullable = false)
private String name;
@Column(name = "hospital_tel", nullable = false)
private String tel;
@Column(name = "hospital_address", nullable = false)
private String address;
@OneToOne
@JoinColumn(name ="member_id")
private Member member;
@Builder
public Hospital(String name, String tel, String address, Member member) {
this.name = name;
this.tel = tel;
this.address = address;
this.member = member;
}
}
| 22.560976 | 77 | 0.687568 |
1b860a2ff718d45612d87be7316fa68426236b6a | 1,380 | package com.marshalchen.common.demoofui.sampleModules;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import com.marshalchen.common.demoofui.R;
import com.marshalchen.common.ui.NumberProgressBar;
import java.util.Timer;
import java.util.TimerTask;
public class NumberProgressBarActivity extends ActionBarActivity {
private int counter = 0;
private Timer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.number_progress_bar_activity_main);
final NumberProgressBar bnp = (NumberProgressBar)findViewById(R.id.numberbar1);
counter = 0;
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
bnp.incrementProgressBy(1);
counter ++;
if (counter == 110) {
bnp.setProgress(0);
counter=0;
}
}
});
}
}, 1000, 100);
}
@Override
protected void onDestroy() {
super.onDestroy();
timer.cancel();
}
}
| 26.037736 | 87 | 0.55942 |
4c331ad7834506d4ce9e7acf12ac82470c7eaf8c | 7,042 | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.rl4j.mdp.vizdoom;
import lombok.Getter;
import lombok.Setter;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacpp.Pointer;
import org.deeplearning4j.gym.StepReply;
import org.deeplearning4j.rl4j.mdp.MDP;
import org.deeplearning4j.rl4j.space.ArrayObservationSpace;
import org.deeplearning4j.rl4j.space.DiscreteSpace;
import org.deeplearning4j.rl4j.space.Encodable;
import org.deeplearning4j.rl4j.space.ObservationSpace;
import vizdoom.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author rubenfiszel ([email protected]) on 7/28/16.
*
* Mother abstract class for all VizDoom scenarios
*
* is mostly configured by
*
* String scenario; name of the scenario
* double livingReward; additional reward at each step for living
* double deathPenalty; negative reward when ded
* int doomSkill; skill of the ennemy
* int timeout; number of step after which simulation time out
* int startTime; number of internal tics before the simulation starts (useful to draw weapon by example)
* List<Button> buttons; the list of inputs one can press for a given scenario (noop is automatically added)
*
*
*
*/
@Slf4j
abstract public class VizDoom implements MDP<VizDoom.GameScreen, Integer, DiscreteSpace> {
final public static String DOOM_ROOT = "vizdoom";
protected DoomGame game;
final protected List<double[]> actions;
final protected DiscreteSpace discreteSpace;
final protected ObservationSpace<GameScreen> observationSpace;
@Getter
final protected boolean render;
@Setter
protected double scaleFactor = 1;
public VizDoom() {
this(false);
}
public VizDoom(boolean render) {
this.render = render;
actions = new ArrayList<double[]>();
game = new DoomGame();
setupGame();
discreteSpace = new DiscreteSpace(getConfiguration().getButtons().size() + 1);
observationSpace = new ArrayObservationSpace<>(new int[] {game.getScreenHeight(), game.getScreenWidth(), 3});
}
public void setupGame() {
Configuration conf = getConfiguration();
game.setViZDoomPath(DOOM_ROOT + "/vizdoom");
game.setDoomGamePath(DOOM_ROOT + "/freedoom2.wad");
game.setDoomScenarioPath(DOOM_ROOT + "/scenarios/" + conf.getScenario() + ".wad");
game.setDoomMap("map01");
game.setScreenFormat(ScreenFormat.RGB24);
game.setScreenResolution(ScreenResolution.RES_800X600);
// Sets other rendering options
game.setRenderHud(false);
game.setRenderCrosshair(false);
game.setRenderWeapon(true);
game.setRenderDecals(false);
game.setRenderParticles(false);
GameVariable[] gameVar = new GameVariable[] {GameVariable.KILLCOUNT, GameVariable.ITEMCOUNT,
GameVariable.SECRETCOUNT, GameVariable.FRAGCOUNT, GameVariable.HEALTH, GameVariable.ARMOR,
GameVariable.DEAD, GameVariable.ON_GROUND, GameVariable.ATTACK_READY,
GameVariable.ALTATTACK_READY, GameVariable.SELECTED_WEAPON, GameVariable.SELECTED_WEAPON_AMMO,
GameVariable.AMMO1, GameVariable.AMMO2, GameVariable.AMMO3, GameVariable.AMMO4,
GameVariable.AMMO5, GameVariable.AMMO6, GameVariable.AMMO7, GameVariable.AMMO8,
GameVariable.AMMO9, GameVariable.AMMO0};
// Adds game variables that will be included in state.
for (int i = 0; i < gameVar.length; i++) {
game.addAvailableGameVariable(gameVar[i]);
}
// Causes episodes to finish after timeout tics
game.setEpisodeTimeout(conf.getTimeout());
game.setEpisodeStartTime(conf.getStartTime());
game.setWindowVisible(render);
game.setSoundEnabled(false);
game.setMode(Mode.PLAYER);
game.setLivingReward(conf.getLivingReward());
// Adds buttons that will be allowed.
List<Button> buttons = conf.getButtons();
int size = buttons.size();
actions.add(new double[size + 1]);
for (int i = 0; i < size; i++) {
game.addAvailableButton(buttons.get(i));
double[] action = new double[size + 1];
action[i] = 1;
actions.add(action);
}
game.setDeathPenalty(conf.getDeathPenalty());
game.setDoomSkill(conf.getDoomSkill());
game.init();
}
public boolean isDone() {
return game.isEpisodeFinished();
}
public GameScreen reset() {
log.info("free Memory: " + Pointer.formatBytes(Pointer.availablePhysicalBytes()) + "/"
+ Pointer.formatBytes(Pointer.totalPhysicalBytes()));
game.newEpisode();
return new GameScreen(game.getState().screenBuffer);
}
public void close() {
game.close();
}
public StepReply<GameScreen> step(Integer action) {
double r = game.makeAction(actions.get(action)) * scaleFactor;
log.info(game.getEpisodeTime() + " " + r + " " + action + " ");
return new StepReply(new GameScreen(game.isEpisodeFinished()
? new byte[game.getScreenSize()]
: game.getState().screenBuffer), r, game.isEpisodeFinished(), null);
}
public ObservationSpace<GameScreen> getObservationSpace() {
return observationSpace;
}
public DiscreteSpace getActionSpace() {
return discreteSpace;
}
public abstract Configuration getConfiguration();
public abstract VizDoom newInstance();
@Value
public static class Configuration {
String scenario;
double livingReward;
double deathPenalty;
int doomSkill;
int timeout;
int startTime;
List<Button> buttons;
}
public static class GameScreen implements Encodable {
double[] array;
public GameScreen(byte[] screen) {
array = new double[screen.length];
for (int i = 0; i < screen.length; i++) {
array[i] = (screen[i] & 0xFF) / 255.0;
}
}
public double[] toArray() {
return array;
}
}
}
| 32.009091 | 118 | 0.639449 |
daeb4e00b04ee165aa162789d6f1fb41d8d02c40 | 502 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.javaagent.instrumentation.vertx.client;
import io.opentelemetry.context.propagation.TextMapSetter;
import io.vertx.core.http.HttpClientRequest;
public class HttpRequestHeaderSetter implements TextMapSetter<HttpClientRequest> {
@Override
public void set(HttpClientRequest carrier, String key, String value) {
if (carrier != null) {
carrier.putHeader(key, value);
}
}
}
| 25.1 | 82 | 0.76494 |
c797b95ef400b04215d44b5853ccd84a983521f6 | 2,160 | /**
*
*/
package com.JSPICE.SPICESolver;
import java.util.ArrayList;
import com.JSPICE.SElement.*;
import com.JSPICE.SMath.Complex;
import com.JSPICE.SMath.ComplexMatrixOperations;
import com.JSPICE.SElement.VSource.VSource;
/**
* @author 1sand0s
*
*/
public class ACSpiceSolver extends AbstractSpiceSolver {
private double frequency = 0;
/**
*
*/
public ACSpiceSolver() {
circuitElements = new ArrayList<SElement>();
wires = new ArrayList<Wire>();
result = new ACSpiceResult();
}
@Override
public void setFrequency(double frequency) {
this.frequency = frequency;
}
@Override
public void solve() {
solve(circuitElements,
wires);
}
@Override
public void solve(ArrayList<SElement> circuitElements,
ArrayList<Wire> wires) {
int vSourceIndex = 0;
G = new Complex[wires.size()][wires.size()];
B = new Complex[wires.size()][iVSource + iISource];
C = new Complex[iVSource + iISource][wires.size()];
D = new Complex[iVSource + iISource][iVSource + iISource];
z = new Complex[wires.size() + iVSource + iISource][numHarmonics];
x = new Complex[wires.size() + iVSource + iISource][numHarmonics];
numberNodes();
ComplexMatrixOperations.initializeMatrices(G);
ComplexMatrixOperations.initializeMatrices(B);
ComplexMatrixOperations.initializeMatrices(C);
ComplexMatrixOperations.initializeMatrices(D);
ComplexMatrixOperations.initializeMatrices(z);
ComplexMatrixOperations.initializeMatrices(x);
for (int j = 0; j < circuitElements.size(); j++) {
SElement element = circuitElements.get(j);
element.stampMatrixAC(G, B, C, D, z, x, vSourceIndex, frequency);
if (element instanceof VSource)
vSourceIndex++;
}
/* Exclude Row and Column corresponding to GND node to prevent singular matrix */
Complex A[][] = constructMNAMatrix(G, B, C, D);
x = ComplexMatrixOperations.computeLinearEquation(A, removeGNDFromResult(z));
x = addGNDToResult(x);
result.updateResult(x);
}
}
| 27.692308 | 82 | 0.654167 |
adc7c2a34b242224de099b4bac401ba2e354bf3a | 258 | public class EvenOrOdd {
public static String even_or_odd(int number) {
// ternary operator for a shorthand if else
// if divisible by 2 with no remainder then even else odd
return number % 2 == 0 ? "Even" : "Odd";
}
}
| 32.25 | 66 | 0.608527 |
81ea5790e190f385d1d133140f82e0b20d5fbb73 | 492 | package com.sgnbs.cms.entity;
public class Role {
private Integer roleId;
private String roleName;
private String rights;
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRights() {
return rights;
}
public void setRights(String rights) {
this.rights = rights;
}
}
| 18.222222 | 43 | 0.71748 |
7c2af81b2682cf21de7d9ef8af6e4dbbf0fff219 | 2,857 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.query;
import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException;
/**
* A query that will execute the wrapped query only for the specified indices, and "match_all" when
* it does not match those indices (by default).
*/
public class IndicesQueryBuilder extends QueryBuilder {
private final QueryBuilder queryBuilder;
private final String[] indices;
private String sNoMatchQuery;
private QueryBuilder noMatchQuery;
private String queryName;
public IndicesQueryBuilder(QueryBuilder queryBuilder, String... indices) {
this.queryBuilder = queryBuilder;
this.indices = indices;
}
/**
* Sets the no match query, can either be <tt>all</tt> or <tt>none</tt>.
*/
public IndicesQueryBuilder noMatchQuery(String type) {
this.sNoMatchQuery = type;
return this;
}
/**
* Sets the query to use when it executes on an index that does not match the indices provided.
*/
public IndicesQueryBuilder noMatchQuery(QueryBuilder noMatchQuery) {
this.noMatchQuery = noMatchQuery;
return this;
}
/**
* Sets the query name for the filter that can be used when searching for matched_filters per hit.
*/
public IndicesQueryBuilder queryName(String queryName) {
this.queryName = queryName;
return this;
}
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(IndicesQueryParser.NAME);
builder.field("indices", indices);
builder.field("query");
queryBuilder.toXContent(builder, params);
if (noMatchQuery != null) {
builder.field("no_match_query");
noMatchQuery.toXContent(builder, params);
} else if (sNoMatchQuery != null) {
builder.field("no_match_query", sNoMatchQuery);
}
if (queryName != null) {
builder.field("_name", queryName);
}
builder.endObject();
}
} | 32.83908 | 102 | 0.689184 |
c9d09a7b616db9e251eda5192061dc72dbf9ae92 | 6,022 | package org.firstinspires.ftc.teamcode.teleop;
import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.arcrobotics.ftclib.gamepad.ButtonReader;
import com.arcrobotics.ftclib.gamepad.GamepadEx;
import com.arcrobotics.ftclib.gamepad.GamepadKeys;
import com.arcrobotics.ftclib.gamepad.KeyReader;
import com.arcrobotics.ftclib.gamepad.ToggleButtonReader;
import com.arcrobotics.ftclib.gamepad.TriggerReader;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import org.firstinspires.ftc.teamcode.drive.Robot;
import org.firstinspires.ftc.teamcode.modules.capstone.Capstone;
import org.firstinspires.ftc.teamcode.modules.carousel.Carousel;
import org.firstinspires.ftc.teamcode.modules.deposit.Deposit;
import org.firstinspires.ftc.teamcode.modules.intake.Intake;
import org.firstinspires.ftc.teamcode.util.field.Balance;
import org.firstinspires.ftc.teamcode.util.field.Context;
import org.firstinspires.ftc.teamcode.util.field.OpModeType;
import static org.firstinspires.ftc.teamcode.util.field.Context.balance;
@TeleOp
public class DriverPractice extends LinearOpMode {
Robot robot;
Intake intake;
Deposit deposit;
Carousel carousel;
Capstone capstone;
GamepadEx primary;
GamepadEx secondary;
KeyReader[] keyReaders;
TriggerReader intakeButton, ninjaMode, liftButton;
ButtonReader levelIncrement, levelDecrement, dumpButton, tippedToward, tippedAway,
capstoneReady, capstoneDrop, capstoneIn;
ToggleButtonReader carouselButton;
Deposit.State defaultDepositState = Deposit.State.LEVEL3;
@Override
public void runOpMode() throws InterruptedException {
robot = new Robot(this, OpModeType.TELE);
intake = robot.intake;
deposit = robot.deposit;
carousel = robot.carousel;
capstone = robot.capstone;
primary = new GamepadEx(gamepad1);
secondary = new GamepadEx(gamepad2);
keyReaders = new KeyReader[] {
capstoneReady = new ButtonReader(primary, GamepadKeys.Button.B),
capstoneDrop = new ButtonReader(primary, GamepadKeys.Button.A),
capstoneIn = new ButtonReader(primary, GamepadKeys.Button.X),
intakeButton = new TriggerReader(secondary, GamepadKeys.Trigger.RIGHT_TRIGGER),
ninjaMode = new TriggerReader(primary, GamepadKeys.Trigger.LEFT_TRIGGER),
levelIncrement = new ButtonReader(secondary, GamepadKeys.Button.DPAD_UP),
levelDecrement = new ButtonReader(secondary, GamepadKeys.Button.DPAD_DOWN),
liftButton = new TriggerReader(secondary, GamepadKeys.Trigger.LEFT_TRIGGER),
tippedAway = new ButtonReader(secondary, GamepadKeys.Button.LEFT_BUMPER),
tippedToward = new ButtonReader(secondary, GamepadKeys.Button.RIGHT_BUMPER),
carouselButton = new ToggleButtonReader(primary, GamepadKeys.Button.LEFT_BUMPER),
dumpButton = new ButtonReader(primary, GamepadKeys.Button.RIGHT_BUMPER),
};
waitForStart();
while (opModeIsActive()) {
robot.update();
for (KeyReader reader : keyReaders) {
reader.readValue();
}
Pose2d drivePower = new Pose2d(
-gamepad1.left_stick_y,
0,
-gamepad1.right_stick_x
);
if (ninjaMode.isDown()) drivePower = drivePower.div(3);
robot.setWeightedDrivePower(drivePower);
setIntake();
setDeposit();
setCarousel();
Context.packet.addLine(intake.getState() + "");
Context.packet.addLine(defaultDepositState + "");
telemetry.addData("Intake State", intake.getState());
telemetry.addData("Default Height", defaultDepositState);
if (tippedAway.isDown() && tippedToward.isDown()) {
balance = Balance.BALANCED;
} else if (tippedAway.isDown()) {
balance = Balance.AWAY;
} else if (tippedToward.isDown()) {
balance = Balance.TOWARD;
}
if (liftButton.isDown()) {
Deposit.allowLift = true;
}
setCapstone();
}
}
void setCapstone() {
if (capstoneDrop.wasJustPressed()) {
if (robot.capstone.getState() == Capstone.State.PRECAP) {
robot.capstone.cap();
} else {
robot.capstone.preCap();
}
} else if (capstoneIn.wasJustPressed()) {
robot.capstone.hold();
}
}
void setIntake() {
if (intakeButton.isDown()) {
intake.setPower(1);
} else {
intake.setPower(0);
}
}
void setDeposit() {
if (levelIncrement.wasJustPressed()) {
switch (defaultDepositState) {
case LEVEL2:
defaultDepositState = Deposit.State.LEVEL3;
break;
case IDLE:
defaultDepositState = Deposit.State.LEVEL2;
break;
}
deposit.setState(defaultDepositState);
} else if (levelDecrement.wasJustPressed()) {
switch (defaultDepositState) {
case LEVEL3:
defaultDepositState = Deposit.State.LEVEL2;
break;
case LEVEL2:
defaultDepositState = Deposit.State.IDLE;
break;
}
deposit.setState(defaultDepositState);
}
if (dumpButton.wasJustPressed()) {
Deposit.allowLift = true;
deposit.dump();
}
}
void setCarousel() {
carousel.setPower(gamepad2.right_stick_y);
// if(carouselButton.getState()) {
// carousel.on();
// } else {
// carousel.off();
// }
}
}
| 38.356688 | 97 | 0.616573 |
fbaf22469159d3575b8a8b7563eb9741e9999e10 | 3,729 | /*-
* #%L
* jasmine-maven-plugin
* %%
* Copyright (C) 2010 - 2017 Justin Searls
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.searls.jasmine.io.scripts;
import com.github.searls.jasmine.io.CreatesTempDirectories;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class ResolvesLocationOfPreloadSourcesIntegrationTest {
private static final String SPEC = "spec";
private static final String SOURCE = "source";
private static final String SEPARATED_DIR = "separatedDir";
private ResolvesLocationOfPreloadSources subject = new ResolvesLocationOfPreloadSources(
new ConvertsFileToUriString()
);
private CreatesTempDirectories createsTempDirectories = new CreatesTempDirectories();
private File sourceDir = createsTempDirectories.create(SOURCE);
private File specDir = createsTempDirectories.create(SPEC);
private File separatedDir = createsTempDirectories.create(SEPARATED_DIR);
@AfterEach
public void deleteTempDirs() {
sourceDir.delete();
specDir.delete();
separatedDir.delete();
}
@Test
public void returnsListWhenSourcesIsNull() {
List<String> result = subject.resolve(null, sourceDir, specDir);
assertThat(result).isNotNull();
}
@Test
public void loadsSourceFileWhenItExistsUnderSourceAndSpec() throws IOException {
String expected = "panda";
new File(sourceDir, expected).createNewFile();
new File(specDir, expected).createNewFile();
List<String> preloadSources = Collections.singletonList(expected);
List<String> result = subject.resolve(preloadSources, sourceDir, specDir);
assertThat(result).hasSize(1);
assertThat(result.get(0)).contains(SOURCE);
assertThat(result.get(0)).contains(expected);
}
@Test
public void loadsSpecFileWhenItExistsUnderSpec() throws IOException {
String expected = "panda";
new File(specDir, expected).createNewFile();
List<String> preloadSources = Collections.singletonList(expected);
List<String> result = subject.resolve(preloadSources, sourceDir, specDir);
assertThat(result).hasSize(1);
assertThat(result.get(0)).contains(SPEC);
assertThat(result.get(0)).contains(expected);
}
@Test
public void loadsExistentFileWithURIIfItIsNotInEitherSourceAndSpecFolders() throws Exception {
String expected = "panda";
new File(separatedDir, expected).createNewFile();
List<String> preloadSources = Collections.singletonList(separatedDir.getAbsolutePath() + File.separator + expected);
List<String> result = subject.resolve(preloadSources, sourceDir, specDir);
assertThat(result).hasSize(1);
assertThat(result.get(0)).contains("file:/");
}
@Test
public void printsAsIsWhenItDoesNotExist() {
String expected = "telnet://woahItsTelnet";
List<String> preloadSources = Collections.singletonList(expected);
List<String> result = subject.resolve(preloadSources, sourceDir, specDir);
assertThat(result).hasSize(1);
assertThat(result.get(0)).isEqualTo(expected);
}
}
| 32.426087 | 120 | 0.747385 |
03a2e423b717b1219c775e662f94de0c70506f2c | 832 | package com.xxm.parking.pojo;
import com.xxm.parking.util.TimeUtil;
import lombok.Data;
/**
*
* 停车记录
*
* @author 许晓敏
*
*/
@Data
public class Record {
private int id;
private int seatid;
private int userid;
private long createtime;
private long endtime;
private User user;
private Seat seat;
private Plot plot;
private int button;
private String stayTime;// 停留时长
private String date1;
private String date2;
public String getStayTime() {
if(this.endtime!=0) {
this.stayTime = TimeUtil.dateDiff(createtime, endtime, 1);
}else {
this.stayTime = TimeUtil.dateDiff(createtime, System.currentTimeMillis(), 1);
}
return this.stayTime;
}
public String getDate1() {
return TimeUtil.timeToDate(this.createtime);
}
public String getDate2() {
return TimeUtil.timeToDate(this.endtime);
}
}
| 16.979592 | 80 | 0.709135 |
7c33bc5e183d28e92ab7ed1da0671c30a5f165b0 | 592 | package com.codeborne.selenide.collections;
import org.openqa.selenium.WebElement;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List;
import java.util.function.Predicate;
@ParametersAreNonnullByDefault
public class NoneMatch extends PredicateCollectionCondition {
public NoneMatch(String description, Predicate<WebElement> predicate) {
super("none", description, predicate);
}
@Override
public boolean test(List<WebElement> elements) {
if (elements.isEmpty()) {
return false;
}
return elements.stream().noneMatch(predicate);
}
}
| 25.73913 | 73 | 0.77027 |
684d31e5ef80d13cc135ea2d02e350c62361f7c1 | 1,508 | package com.litefeel.crossplatformapi.android.share;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.litefeel.crossplatformapi.android.utils.ActivityHelper;
import java.io.File;
/**
* Created by litefeel on 2017/7/24.
*/
public class Share {
private static final String TAG = Share.class.getSimpleName();
public static void shareText(String text) {
if (text == null || text.isEmpty())
return;
Intent sendIntent = new Intent();
sendIntent.setType("text/plain");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, text);
ActivityHelper.getActivity().startActivity(sendIntent);
}
public static void shareImage(String image, String text) {
File file = new File(image);
Uri imageUri = file.exists() ? Uri.fromFile(file) : Uri.parse(image);
Log.d(TAG, "nativeShareImage:" + image);
Log.d(TAG, "nativeShareImage uri" + imageUri.toString());
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
if (text != null && !text.isEmpty()) {
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
}
shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
shareIntent.setType("image/*");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
ActivityHelper.getActivity().startActivity(Intent.createChooser(shareIntent, "send"));
}
}
| 33.511111 | 94 | 0.674403 |
20688e8d50570d9b692b37efb20c416ea08e8dd7 | 132 | package io.snice.networking.examples.vplmn.fsm.users;
public enum UserManagerState {
INIT, RUNNING, TERMINATING, TERMINATED;
}
| 22 | 53 | 0.780303 |
42d613b5ffe244df97aa41a2a6d2ee4828fe6638 | 13,940 | package us.ihmc.quadrupedFootstepPlanning.pawPlanning.turnWalkTurn;
import us.ihmc.commons.MathTools;
import us.ihmc.euclid.geometry.Pose2D;
import us.ihmc.euclid.geometry.interfaces.Pose2DReadOnly;
import us.ihmc.euclid.tuple2D.Point2D;
import us.ihmc.euclid.tuple2D.Vector2D;
import us.ihmc.euclid.tuple2D.interfaces.Point2DReadOnly;
import us.ihmc.euclid.tuple2D.interfaces.Vector2DReadOnly;
import us.ihmc.pathPlanning.bodyPathPlanner.BodyPathPlanHolder;
import us.ihmc.pathPlanning.visibilityGraphs.tools.BodyPathPlan;
import us.ihmc.quadrupedPlanning.stepStream.bodyPath.QuadrupedBodyPathPlan;
import us.ihmc.yoVariables.registry.YoRegistry;
import us.ihmc.yoVariables.variable.YoDouble;
import us.ihmc.yoVariables.variable.YoEnum;
public class QuadrupedTurnWalkTurnPathPlanner
{
private final YoRegistry registry = new YoRegistry(getClass().getSimpleName());
private enum RobotSpeed
{
FAST, MEDIUM, SLOW
}
private static final Vector2DReadOnly forwardHeading = new Vector2D(1.0, 0.0);
private final YoDouble maxYawRate = new YoDouble("maxYawRate", registry);
private final YoDouble maxForwardAcceleration = new YoDouble("maxForwardAcceleration", registry);
private final YoDouble maxYawAcceleration = new YoDouble("maxYawAcceleration", registry);
private final YoDouble fastVelocity = new YoDouble("fastVelocity", registry);
private final YoDouble mediumVelocity = new YoDouble("mediumVelocity", registry);
private final YoDouble slowVelocity = new YoDouble("slowVelocity", registry);
private final YoEnum<RobotSpeed> robotSpeed = new YoEnum<>("robotSpeed", registry, RobotSpeed.class);
private final QuadrupedBodyPathPlan pathPlan = new QuadrupedBodyPathPlan();
private final BodyPathPlanHolder bodyPathPlanner;
public QuadrupedTurnWalkTurnPathPlanner(TurnWalkTurnPathParameters pathParameters, BodyPathPlanHolder bodyPathPlanner, YoRegistry parentRegistry)
{
this.bodyPathPlanner = bodyPathPlanner;
robotSpeed.set(RobotSpeed.MEDIUM);
maxYawRate.set(pathParameters.getMaxYawRate());
maxForwardAcceleration.set(pathParameters.getMaxForwardAcceleration());
maxYawAcceleration.set(pathParameters.getMaxYawAcceleration());
fastVelocity.set(pathParameters.getFastVelocity());
mediumVelocity.set(pathParameters.getMediumVelocity());
slowVelocity.set(pathParameters.getSlowVelocity());
parentRegistry.addChild(registry);
}
public void computePlan()
{
pathPlan.clear();
BodyPathPlan bodyPathWaypoints = bodyPathPlanner.getPlan();
Pose2DReadOnly startPose = bodyPathWaypoints.getStartPose();
Pose2DReadOnly goalPose = bodyPathWaypoints.getGoalPose();
pathPlan.setStartPose(startPose);
pathPlan.setGoalPose(goalPose);
computePlanDiscretelyTraversingWaypoints();
pathPlan.setExpressedInAbsoluteTime(false);
}
public QuadrupedBodyPathPlan getPlan()
{
return pathPlan;
}
private static final Vector2DReadOnly zeroVelocity = new Vector2D();
private final Vector2D desiredHeading = new Vector2D();
private void computePlanDiscretelyTraversingWaypoints()
{
double currentTime = 0.0;
BodyPathPlan bodyPathWaypoints = bodyPathPlanner.getPlan();
Pose2DReadOnly startPose = bodyPathWaypoints.getStartPose();
Point2D currentPosition = new Point2D(startPose.getPosition());
double currentYaw = startPose.getYaw();
Vector2D currentLinearVelocity = new Vector2D();
for (int currentWaypointIndex = 0; currentWaypointIndex < bodyPathWaypoints.getNumberOfWaypoints() - 1; currentWaypointIndex++)
{
int nextWaypointIndex = currentWaypointIndex + 1;
Point2DReadOnly nextWaypoint = new Point2D(bodyPathWaypoints.getWaypoint(nextWaypointIndex).getPosition());
desiredHeading.sub(nextWaypoint, currentPosition);
desiredHeading.normalize();
double desiredYaw = forwardHeading.angle(desiredHeading);
double timeToAccelerateTurnWithNoMaxRate = QuadrupedTurnWalkTurnPathPlanner.computeTimeToAccelerateToAchieveValueWithNoMaxRate(currentYaw, 0.0, desiredYaw, 0.0, maxYawAcceleration.getDoubleValue());
boolean reachesMaxYawRate = maxYawAcceleration.getDoubleValue() * timeToAccelerateTurnWithNoMaxRate > maxYawRate.getValue();
// handle turning
if (reachesMaxYawRate)
{
double angleDelta = desiredYaw - currentYaw;
double errorSign = Math.signum(angleDelta);
double timeToAccelerate = maxYawRate.getDoubleValue() / maxYawAcceleration.getValue();
double deltaWhileAccelerating = 0.5 * errorSign * maxYawAcceleration.getValue() * MathTools.square(timeToAccelerate);
currentYaw += deltaWhileAccelerating ;
currentTime += timeToAccelerate;
// add accelerating waypoint
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, errorSign * maxYawRate.getDoubleValue(), currentTime);
double timeForMaxVelocity = (Math.abs(angleDelta) - Math.abs(2.0 * deltaWhileAccelerating)) / maxYawRate.getDoubleValue();
// add constant velocity waypoint
currentYaw += timeForMaxVelocity * maxYawRate.getDoubleValue() * errorSign;
currentTime += timeForMaxVelocity;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, errorSign * maxYawRate.getDoubleValue(), currentTime);
currentYaw += deltaWhileAccelerating;
currentTime += timeToAccelerate;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, 0.0, currentTime);
}
else
{
double angleDelta = desiredYaw - currentYaw;
double errorSign = Math.signum(angleDelta);
double deltaWhileAccelerating = 0.5 * errorSign * maxYawAcceleration.getDoubleValue() * MathTools.square(timeToAccelerateTurnWithNoMaxRate);
double velocityAfterAccelerating = errorSign * maxYawAcceleration.getDoubleValue() * timeToAccelerateTurnWithNoMaxRate;
currentYaw += deltaWhileAccelerating ;
currentTime += timeToAccelerateTurnWithNoMaxRate;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, velocityAfterAccelerating, currentTime);
currentYaw += deltaWhileAccelerating;
currentTime += timeToAccelerateTurnWithNoMaxRate;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, 0.0, currentTime);
}
// handle translation
double desiredSpeed;
switch (robotSpeed.getEnumValue())
{
case FAST:
desiredSpeed = fastVelocity.getDoubleValue();
break;
case MEDIUM:
desiredSpeed = mediumVelocity.getDoubleValue();
break;
default:
desiredSpeed = slowVelocity.getDoubleValue();
break;
}
double distanceToTravel = currentPosition.distance(nextWaypoint);
double timeToAccelerateDistanceWithNoMaxRate = QuadrupedTurnWalkTurnPathPlanner.computeTimeToAccelerateToAchieveValueWithNoMaxRate(0.0, 0.0, distanceToTravel, 0.0, maxForwardAcceleration.getDoubleValue());
boolean reachesMaxForwardRate = maxForwardAcceleration.getDoubleValue() * timeToAccelerateDistanceWithNoMaxRate > desiredSpeed;
if (reachesMaxForwardRate)
{
double timeToAccelerate = desiredSpeed / maxForwardAcceleration.getValue();
double distanceWhileAccelerating = 0.5 * maxForwardAcceleration.getValue() * MathTools.square(timeToAccelerate);
desiredHeading.normalize();
desiredHeading.scale(distanceWhileAccelerating);
currentPosition.add(desiredHeading);
currentLinearVelocity.set(desiredHeading);
currentLinearVelocity.normalize();
currentLinearVelocity.scale(timeToAccelerate * maxForwardAcceleration.getDoubleValue());
currentTime += timeToAccelerate;
// add accelerating waypoint
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), currentLinearVelocity, 0.0 , currentTime);
double timeAtMaxVelocity = (Math.abs(distanceToTravel) - Math.abs(2.0 * distanceWhileAccelerating)) / desiredSpeed;
// add constant velocity waypoint
desiredHeading.set(currentLinearVelocity);
desiredHeading.scale(timeAtMaxVelocity);
currentPosition.add(desiredHeading);
currentTime += timeAtMaxVelocity;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), currentLinearVelocity, 0.0, currentTime);
desiredHeading.normalize();
desiredHeading.scale(distanceWhileAccelerating);
currentPosition.add(desiredHeading);
currentTime += timeToAccelerate;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, 0.0, currentTime);
}
else
{
double deltaWhileAccelerating = 0.5 * maxForwardAcceleration.getDoubleValue() * MathTools.square(timeToAccelerateDistanceWithNoMaxRate);
double velocityAfterAccelerating = maxForwardAcceleration.getDoubleValue() * timeToAccelerateDistanceWithNoMaxRate;
desiredHeading.normalize();
desiredHeading.scale(deltaWhileAccelerating);
currentPosition.add(desiredHeading);
currentLinearVelocity.set(desiredHeading);
currentLinearVelocity.normalize();
currentLinearVelocity.scale(velocityAfterAccelerating);
currentTime += timeToAccelerateDistanceWithNoMaxRate;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), currentLinearVelocity, 0.0, currentTime);
currentPosition.add(desiredHeading);
currentTime += timeToAccelerateDistanceWithNoMaxRate;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, 0.0, currentTime);
}
}
double goalYaw = bodyPathWaypoints.getGoalPose().getYaw();
if (!MathTools.epsilonEquals(currentYaw, goalYaw, 2.0e-3))
{
double timeToAccelerateTurnWithNoMaxRate = QuadrupedTurnWalkTurnPathPlanner.computeTimeToAccelerateToAchieveValueWithNoMaxRate(currentYaw, 0.0, goalYaw, 0.0, maxYawAcceleration.getDoubleValue());
boolean reachesMaxYawRate = maxYawAcceleration.getDoubleValue() * timeToAccelerateTurnWithNoMaxRate > maxYawRate.getValue();
// handle turning
if (reachesMaxYawRate)
{
double angleDelta = goalYaw - currentYaw;
double errorSign = Math.signum(angleDelta);
double timeToAccelerate = maxYawRate.getDoubleValue() / maxYawAcceleration.getValue();
double deltaWhileAccelerating = 0.5 * errorSign * maxYawAcceleration.getValue() * MathTools.square(timeToAccelerate);
currentYaw += deltaWhileAccelerating ;
currentTime += timeToAccelerate;
// add accelerating waypoint
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, errorSign * maxYawRate.getDoubleValue(), currentTime);
double timeForMaxVelocity = (Math.abs(angleDelta) - Math.abs(2.0 * deltaWhileAccelerating)) / maxYawRate.getDoubleValue();
// add constant velocity waypoint
currentYaw += timeForMaxVelocity * maxYawRate.getDoubleValue() * errorSign;
currentTime += timeForMaxVelocity;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, errorSign * maxYawRate.getDoubleValue(), currentTime);
currentYaw += deltaWhileAccelerating;
currentTime += timeToAccelerate;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, 0.0, currentTime);
}
else
{
double angleDelta = goalYaw - currentYaw;
double errorSign = Math.signum(angleDelta);
double deltaWhileAccelerating = 0.5 * errorSign * maxYawAcceleration.getDoubleValue() * MathTools.square(timeToAccelerateTurnWithNoMaxRate);
double velocityAfterAccelerating = errorSign * maxYawAcceleration.getDoubleValue() * timeToAccelerateTurnWithNoMaxRate;
currentYaw += deltaWhileAccelerating ;
currentTime += timeToAccelerateTurnWithNoMaxRate;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, velocityAfterAccelerating, currentTime);
currentYaw += deltaWhileAccelerating;
currentTime += timeToAccelerateTurnWithNoMaxRate;
pathPlan.addWaypoint(new Pose2D(currentPosition, currentYaw), zeroVelocity, 0.0, currentTime);
}
}
}
static double computeTimeToAccelerateToAchieveValueWithNoMaxRate(double currentValue, double currentRate, double desiredValue, double desiredRate,
double maxAcceleration)
{
double angleDelta = desiredValue - currentValue;
double motionDirection = Math.signum(desiredValue - currentValue);
double acceleration = motionDirection * maxAcceleration;
double velocityDelta = 1.0 / (2.0 * acceleration) * (MathTools.square(currentRate) - MathTools.square(desiredRate));
double a = acceleration;
double b = 2.0 * currentRate;
double c = -angleDelta + velocityDelta;
return largestQuadraticSolution(a, b, c);
}
static double largestQuadraticSolution(double a, double b, double c)
{
double radical = Math.sqrt(MathTools.square(b) - 4.0 * a * c);
if (a > 0)
{
return (-b + radical) / (2.0 * a);
}
else
{
return (-b - radical) / (2.0 * a);
}
}
}
| 43.426791 | 214 | 0.70868 |
6337a96c26f2e1f0a99a4fa95ff656db4744d18d | 626 | /**
* Copyright (c) SpaceToad, 2011
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.api.core;
import net.minecraft.world.World;
public interface IBox {
public void expand(int amount);
public void contract(int amount);
public boolean contains(int x, int y, int z);
public Position pMin();
public Position pMax();
public void createLasers(World world, LaserKind kind);
public void deleteLasers();
}
| 20.193548 | 76 | 0.72524 |
3ea19f52c35f74c235f94230bcf11492b9d92e5f | 2,025 | package com.intent.wx.util;
import com.intent.wx.constant.Const;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.internal.Util;
import java.util.concurrent.TimeUnit;
/**
* @author intent <a>[email protected]</a>
* @date 2021/5/13 3:28 下午
* @since 1.0
*/
public class OkHttpClientUtils {
private static volatile OkHttpClient okHttpClient;
private OkHttpClientUtils() {
}
public static OkHttpClient getInstance() {
if (okHttpClient == null) {
synchronized (OkHttpClient.class) {
if (okHttpClient == null) {
okHttpClient = new OkHttpClient.Builder()
.connectionPool(new ConnectionPool(
Const.DEFAULT_MAX_IDLE_CONNECTIONS, Const.KEEP_ALIVE_DURATION_MILLS, TimeUnit.SECONDS))
//连接超时
.connectTimeout(Const.DEFAULT_HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS)
//读取超时
.readTimeout(Const.DEFAULT_HTTP_READ_TIMEOUT, TimeUnit.SECONDS)
//写超时
.writeTimeout(Const.DEFAULT_HTTP_WRITE_TIMEOUT, TimeUnit.SECONDS)
.protocols(Util.immutableList(Protocol.HTTP_1_1))
.sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())
.hostnameVerifier(SSLSocketClient.getHostnameVerifier())
.build();
// okHttpClient.hostnameVerifier();
// okHttpClient.hostnameVerifier().verify("s",new SSLContextImpl())
// okHttpClient.sslSocketFactory(createSSLSocketFactory());
okHttpClient.dispatcher().setMaxRequests(1024);
okHttpClient.dispatcher().setMaxRequestsPerHost(12);
}
}
}
return okHttpClient;
}
}
| 38.942308 | 123 | 0.580247 |
83ba8b961d72b9e9518c222f295a669de6744836 | 2,352 | package com.github.sparkzxl.database.aspect;
import com.github.sparkzxl.annotation.ApiIdempotent;
import com.github.sparkzxl.annotation.ApiIdempotentParam;
import com.github.sparkzxl.core.generator.CacheKeyGenerator;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.ReflectionUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
/**
* description: 缓存key 生成
*
* @author zhouxinlei
*/
public class LockKeyGenerator implements CacheKeyGenerator {
@Override
public String getLockKey(ProceedingJoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ApiIdempotent apiIdempotent = method.getAnnotation(ApiIdempotent.class);
final Object[] args = joinPoint.getArgs();
final Parameter[] parameters = method.getParameters();
StringBuilder builder = new StringBuilder();
// TODO 默认解析方法里面带 ApiIdempotentParam 注解的属性,如果没有尝试着解析实体对象中的
for (int i = 0; i < parameters.length; i++) {
final ApiIdempotentParam annotation = parameters[i].getAnnotation(ApiIdempotentParam.class);
if (annotation == null) {
continue;
}
builder.append(apiIdempotent.delimiter()).append(args[i]);
}
if (StringUtils.isEmpty(builder.toString())) {
final Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameterAnnotations.length; i++) {
final Object object = args[i];
final Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
final ApiIdempotentParam annotation = field.getAnnotation(ApiIdempotentParam.class);
if (annotation == null) {
continue;
}
field.setAccessible(true);
builder.append(apiIdempotent.delimiter()).append(ReflectionUtils.getField(field, object));
}
}
}
return apiIdempotent.prefix() + builder;
}
}
| 41.263158 | 110 | 0.660289 |
18b7857aa4b0d2f175bf395dff977d2cf764632f | 969 | package com.github.brane08.pagila.actor.entities;
import com.github.brane08.pagila.seedworks.entities.BaseModel;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Objects;
@Entity
@Table(name = "actor")
public class Actor extends BaseModel {
@Id
@Column(name = "actor_id")
public Integer actorId;
@Column(name = "first_name")
public String firstName;
@Column(name = "last_name")
public String lastName;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Actor that = (Actor) o;
return actorId.equals(that.actorId) &&
Objects.equals(firstName, that.firstName) &&
Objects.equals(lastName, that.lastName) &&
Objects.equals(lastUpdate, that.lastUpdate);
}
@Override
public int hashCode() {
return Objects.hash(actorId, firstName, lastName, lastUpdate);
}
}
| 24.225 | 64 | 0.73065 |
1ec04c32b7adfe527f022fe5262cc80d0e7a6ce2 | 2,673 | /*
* Copyright (c) 2016. Universidad Politecnica de Madrid
*
* @author Badenes Olmedo, Carlos <[email protected]>
*
*/
package org.librairy.modeler.lda.tasks;
import org.librairy.boot.model.Event;
import org.librairy.boot.model.domain.resources.Resource;
import org.librairy.boot.model.modules.RoutingKey;
import org.librairy.boot.storage.generator.URIGenerator;
import org.librairy.computing.cluster.ComputingContext;
import org.librairy.modeler.lda.helper.ModelingHelper;
import org.librairy.modeler.lda.models.Corpus;
import org.librairy.modeler.lda.models.TopicModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
/**
* Created on 12/08/16:
*
* @author cbadenes
*/
public class LDAShapingTask implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(LDAShapingTask.class);
public static final String ROUTING_KEY_ID = "lda.shapes.created";
private final ModelingHelper helper;
private final String domainUri;
public LDAShapingTask(String domainUri, ModelingHelper modelingHelper) {
this.domainUri = domainUri;
this.helper = modelingHelper;
}
@Override
public void run() {
try{
final ComputingContext context = helper.getComputingHelper().newContext("lda.shapes."+ URIGenerator.retrieveId(domainUri));
helper.getComputingHelper().execute(context, () -> {
try{
// Create corpus
Corpus corpus = helper.getCorpusBuilder().build(context, domainUri, Arrays.asList(new Resource.Type[]{Resource.Type.ITEM, Resource.Type.PART}));
// Load existing model
String domainId = URIGenerator.retrieveId(domainUri);
TopicModel model = helper.getLdaBuilder().load(context, domainId);
// Use of existing vocabulary
corpus.setCountVectorizerModel(model.getVocabModel());
// Calculate topic distributions for Items and Parts
helper.getDealsBuilder().build(context, corpus,model);
corpus.clean();
helper.getEventBus().post(Event.from(domainUri), RoutingKey.of(ROUTING_KEY_ID));
} catch (Exception e){
if (e instanceof InterruptedException){ LOG.info("Execution interrupted during process.");}
else LOG.error("Error scheduling a new topic model for Items from domain: " + domainUri, e);
}
});
} catch (InterruptedException e) {
LOG.info("Execution interrupted.");
}
}
}
| 32.204819 | 164 | 0.653199 |
Subsets and Splits